1
0

test.cc 999 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. } // namespace tls
  69. } // namespace httplib
  70. #endif
  71. using namespace std;
  72. using namespace httplib;
  73. const char *HOST = "localhost";
  74. static int get_base_port() {
  75. const char *shard = getenv("GTEST_SHARD_INDEX");
  76. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  77. }
  78. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  79. // New standalone tests MUST use svr.bind_to_any_port() instead.
  80. const int PORT = get_base_port();
  81. const string LONG_QUERY_VALUE = string(25000, '@');
  82. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  83. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  84. const string TOO_LONG_QUERY_URL =
  85. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  86. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  87. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  88. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  89. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  90. return file.name == key;
  91. });
  92. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  93. return *it;
  94. #else
  95. if (it != items.end()) { return *it; }
  96. throw std::runtime_error("invalid multipart form data name error");
  97. #endif
  98. }
  99. static void read_file(const std::string &path, std::string &out) {
  100. std::ifstream fs(path, std::ios_base::binary);
  101. if (!fs) {
  102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  103. return;
  104. #else
  105. throw std::runtime_error("File not found: " + path);
  106. #endif
  107. }
  108. fs.seekg(0, std::ios_base::end);
  109. auto size = fs.tellg();
  110. fs.seekg(0);
  111. out.resize(static_cast<size_t>(size));
  112. fs.read(&out[0], static_cast<std::streamsize>(size));
  113. }
  114. class UnixSocketTest : public ::testing::Test {
  115. protected:
  116. void TearDown() override { std::remove(pathname_.c_str()); }
  117. void client_GET(const std::string &addr) {
  118. httplib::Client cli{addr};
  119. cli.set_address_family(AF_UNIX);
  120. ASSERT_TRUE(cli.is_valid());
  121. const auto &result = cli.Get(pattern_);
  122. ASSERT_TRUE(result) << "error: " << result.error();
  123. const auto &resp = result.value();
  124. EXPECT_EQ(resp.status, StatusCode::OK_200);
  125. EXPECT_EQ(resp.body, content_);
  126. }
  127. static std::string make_sock_path() {
  128. const char *shard = getenv("GTEST_SHARD_INDEX");
  129. return shard ? std::string("./httplib-server-") + shard + ".sock"
  130. : "./httplib-server.sock";
  131. }
  132. const std::string pathname_{make_sock_path()};
  133. const std::string pattern_{"/hi"};
  134. const std::string content_{"Hello World!"};
  135. };
  136. TEST_F(UnixSocketTest, pathname) {
  137. httplib::Server svr;
  138. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  139. res.set_content(content_, "text/plain");
  140. });
  141. std::thread t{[&] {
  142. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  143. }};
  144. auto se = detail::scope_exit([&] {
  145. svr.stop();
  146. t.join();
  147. ASSERT_FALSE(svr.is_running());
  148. });
  149. svr.wait_until_ready();
  150. ASSERT_TRUE(svr.is_running());
  151. client_GET(pathname_);
  152. // ".//x.sock", which is not taken for a URL
  153. client_GET("./" + pathname_.substr(1));
  154. }
  155. #if defined(__linux__) || \
  156. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  157. TEST_F(UnixSocketTest, PeerPid) {
  158. httplib::Server svr;
  159. std::string remote_port_val;
  160. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  161. res.set_content(content_, "text/plain");
  162. remote_port_val = std::to_string(req.remote_port);
  163. });
  164. std::thread t{[&] {
  165. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  166. }};
  167. auto se = detail::scope_exit([&] {
  168. svr.stop();
  169. t.join();
  170. ASSERT_FALSE(svr.is_running());
  171. });
  172. svr.wait_until_ready();
  173. ASSERT_TRUE(svr.is_running());
  174. client_GET(pathname_);
  175. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  176. }
  177. #endif
  178. #ifdef __linux__
  179. TEST_F(UnixSocketTest, abstract) {
  180. constexpr char svr_path[]{"\x00httplib-server.sock"};
  181. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  182. httplib::Server svr;
  183. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. client_GET(abstract_addr);
  197. }
  198. #endif
  199. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  200. httplib::Server svr;
  201. std::string received_host_header;
  202. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  203. // Capture the Host header sent by the client
  204. auto host_iter = req.headers.find("Host");
  205. if (host_iter != req.headers.end()) {
  206. received_host_header = host_iter->second;
  207. }
  208. res.set_content(content_, "text/plain");
  209. });
  210. std::thread t{[&] {
  211. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  212. }};
  213. auto se = detail::scope_exit([&] {
  214. svr.stop();
  215. t.join();
  216. ASSERT_FALSE(svr.is_running());
  217. });
  218. svr.wait_until_ready();
  219. ASSERT_TRUE(svr.is_running());
  220. // Test that Host header is automatically set to "localhost" for Unix socket
  221. // connections
  222. httplib::Client cli{pathname_};
  223. cli.set_address_family(AF_UNIX);
  224. ASSERT_TRUE(cli.is_valid());
  225. const auto &result = cli.Get(pattern_);
  226. ASSERT_TRUE(result) << "error: " << result.error();
  227. const auto &resp = result.value();
  228. EXPECT_EQ(resp.status, StatusCode::OK_200);
  229. EXPECT_EQ(resp.body, content_);
  230. // Verify that Host header was automatically set to "localhost"
  231. EXPECT_EQ(received_host_header, "localhost");
  232. }
  233. #ifndef _WIN32
  234. TEST(SocketStream, wait_writable_UNIX) {
  235. int fds[2];
  236. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  237. const auto asSocketStream = [&](socket_t fd,
  238. std::function<bool(Stream &)> func) {
  239. return detail::process_client_socket(
  240. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  241. };
  242. asSocketStream(fds[0], [&](Stream &s0) {
  243. EXPECT_EQ(s0.socket(), fds[0]);
  244. EXPECT_TRUE(s0.wait_writable());
  245. EXPECT_TRUE(s0.is_peer_alive());
  246. EXPECT_EQ(0, close(fds[1]));
  247. EXPECT_FALSE(s0.is_peer_alive());
  248. return true;
  249. });
  250. EXPECT_EQ(0, close(fds[0]));
  251. }
  252. TEST(SocketStream, wait_writable_INET) {
  253. sockaddr_in addr;
  254. memset(&addr, 0, sizeof(addr));
  255. addr.sin_family = AF_INET;
  256. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  257. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  258. int disconnected_svr_sock = -1;
  259. std::thread svr{[&] {
  260. const int s = socket(AF_INET, SOCK_STREAM, 0);
  261. ASSERT_LE(0, s);
  262. // PORT + 1 is shared with the SSL redirect tests and with
  263. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  264. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  265. // because that happens on a worker thread the ASSERT does not stop the
  266. // test: it runs on and fails at the disconnected_svr_sock check instead.
  267. default_socket_options(s);
  268. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  269. ASSERT_EQ(0, listen(s, 1));
  270. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  271. ASSERT_EQ(0, close(s));
  272. }};
  273. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  274. std::thread cli{[&] {
  275. const int s = socket(AF_INET, SOCK_STREAM, 0);
  276. ASSERT_LE(0, s);
  277. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  278. ASSERT_EQ(0, close(s));
  279. }};
  280. cli.join();
  281. svr.join();
  282. ASSERT_NE(disconnected_svr_sock, -1);
  283. const auto asSocketStream = [&](socket_t fd,
  284. std::function<bool(Stream &)> func) {
  285. return detail::process_client_socket(
  286. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  287. };
  288. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  289. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  290. // wait_writable() returns true because select_write() only checks if the
  291. // send buffer has space. Peer disconnection is detected later by send().
  292. EXPECT_TRUE(ss.wait_writable());
  293. return true;
  294. });
  295. ASSERT_EQ(0, close(disconnected_svr_sock));
  296. }
  297. #endif // #ifndef _WIN32
  298. TEST(SetSocketOptTest, TcpNoDelay) {
  299. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  300. ASSERT_NE(sock, INVALID_SOCKET);
  301. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  302. int val = 0;
  303. socklen_t len = sizeof(val);
  304. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  305. reinterpret_cast<char *>(&val), &len));
  306. EXPECT_NE(val, 0);
  307. detail::close_socket(sock);
  308. }
  309. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  310. // accept() reports failures through WSAGetLastError() on Windows and through
  311. // errno everywhere else. Asking the wrong one is what made the accept loop
  312. // treat every recoverable failure as fatal on Windows.
  313. struct Classification {
  314. bool resource;
  315. bool transient;
  316. };
  317. auto classify = [](int err) {
  318. #ifdef _WIN32
  319. WSASetLastError(err);
  320. #else
  321. errno = err;
  322. #endif
  323. // Read both before asserting: an assertion may clobber the error slot.
  324. Classification c;
  325. c.resource = detail::is_accept_resource_error();
  326. c.transient = detail::is_accept_transient_error();
  327. return c;
  328. };
  329. #ifdef _WIN32
  330. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  331. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  332. WSAECONNRESET, WSAECONNABORTED};
  333. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  334. #else
  335. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  336. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  337. ECONNABORTED};
  338. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  339. #endif
  340. for (auto err : resource_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.resource) << "error " << err;
  343. EXPECT_FALSE(c.transient) << "error " << err;
  344. }
  345. for (auto err : transient_errors) {
  346. const auto c = classify(err);
  347. EXPECT_TRUE(c.transient) << "error " << err;
  348. EXPECT_FALSE(c.resource) << "error " << err;
  349. }
  350. for (auto err : fatal_errors) {
  351. const auto c = classify(err);
  352. EXPECT_FALSE(c.resource) << "error " << err;
  353. EXPECT_FALSE(c.transient) << "error " << err;
  354. }
  355. #ifdef _WIN32
  356. WSASetLastError(0);
  357. #else
  358. errno = 0;
  359. #endif
  360. }
  361. TEST(ClientTest, MoveConstructible) {
  362. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  363. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  364. }
  365. TEST(ClientTest, MoveAssignable) {
  366. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  367. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  368. }
  369. #ifdef _WIN32
  370. TEST(StartupTest, WSAStartup) {
  371. WSADATA wsaData;
  372. int ret = WSAStartup(0x0002, &wsaData);
  373. ASSERT_EQ(0, ret);
  374. }
  375. #endif
  376. TEST(DecodePathTest, PercentCharacter) {
  377. EXPECT_EQ(
  378. decode_path_component(
  379. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  380. U8("descrip=Gastos áéíóúñÑ 6"));
  381. }
  382. TEST(DecodePathTest, PercentCharacterNUL) {
  383. string expected;
  384. expected.push_back('x');
  385. expected.push_back('\0');
  386. expected.push_back('x');
  387. EXPECT_EQ(decode_path_component("x%00x"), expected);
  388. }
  389. TEST(DecodePathTest, UnicodeEncoding) {
  390. // %u0041 = 'A' (1-byte UTF-8)
  391. EXPECT_EQ("A", decode_path_component("%u0041"));
  392. // %u00E9 = 'é' (2-byte UTF-8)
  393. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  394. // %u3042 = 'あ' (3-byte UTF-8)
  395. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  396. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  397. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  398. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  399. // neighbours)
  400. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  401. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  402. }
  403. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  404. // A sign or whitespace inside the two-character escape window must not be
  405. // accepted as a valid percent-encoding; the sequence is passed through
  406. // literally, matching decode_uri_component / decode_path_component.
  407. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  408. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  409. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  410. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  411. // Well-formed escapes still decode.
  412. EXPECT_EQ("-", decode_query_component("%2D", false));
  413. EXPECT_EQ("A", decode_query_component("%41", false));
  414. }
  415. TEST(SanitizeFilenameTest, VariousPatterns) {
  416. // Path traversal
  417. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  419. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  420. // Normal and edge cases
  421. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  422. EXPECT_EQ("filename.txt",
  423. httplib::sanitize_filename("/path/to/filename.txt"));
  424. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  425. EXPECT_EQ("", httplib::sanitize_filename(".."));
  426. EXPECT_EQ("", httplib::sanitize_filename(""));
  427. // Null bytes stripped
  428. EXPECT_EQ("safe.txt",
  429. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  430. // Whitespace-only rejected
  431. EXPECT_EQ("", httplib::sanitize_filename(" "));
  432. }
  433. // Forward declaration (see the base64_encode note below): split builds move the
  434. // definition into httplib.cc, so re-declaring it here lets the test link.
  435. namespace httplib {
  436. namespace detail {
  437. bool is_chunked_transfer_encoding(const Headers &headers);
  438. } // namespace detail
  439. } // namespace httplib
  440. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  441. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  442. auto make = [](std::initializer_list<const char *> lines) {
  443. Headers h;
  444. for (auto te : lines) {
  445. if (te) { h.emplace("Transfer-Encoding", te); }
  446. }
  447. return h;
  448. };
  449. // Sole coding, matched case-insensitively.
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  453. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  457. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  462. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  463. // were received, into one list. Headers preserves that order, so the answer
  464. // is decided by the last coding of the last line and the order the lines
  465. // arrived in is significant.
  466. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  467. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  469. // The split can fall anywhere in the list.
  470. EXPECT_TRUE(
  471. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  472. EXPECT_FALSE(
  473. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  474. // A trailing line naming no coding leaves the list ending in nothing, so it
  475. // must not inherit the chunked from the line before it.
  476. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  477. }
  478. // Forward declarations (see the base64_encode note below).
  479. namespace httplib {
  480. namespace detail {
  481. bool parse_status_line(const char *line, std::string &version, int &status,
  482. std::string &reason);
  483. std::string file_extension(const std::string &path);
  484. std::string
  485. find_content_type(const std::string &path,
  486. const std::map<std::string, std::string> &user_data,
  487. const std::string &default_content_type);
  488. bool can_compress_content_type(const std::string &content_type);
  489. bool is_prohibited_header_name(const std::string &name);
  490. #ifdef CPPHTTPLIB_SSL_ENABLED
  491. bool match_hostname(const std::string &pattern, const std::string &hostname);
  492. #endif
  493. } // namespace detail
  494. } // namespace httplib
  495. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  496. struct {
  497. const char *line;
  498. const char *version;
  499. int status;
  500. const char *reason;
  501. } cases[] = {
  502. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  503. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  504. // The reason phrase may be empty, or left out along with its space.
  505. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  506. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  507. };
  508. for (const auto &c : cases) {
  509. std::string version;
  510. int status = 0;
  511. std::string reason = "unset";
  512. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  513. << c.line;
  514. EXPECT_EQ(c.version, version);
  515. EXPECT_EQ(c.status, status);
  516. EXPECT_EQ(c.reason, reason);
  517. }
  518. }
  519. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  520. const char *lines[] = {
  521. "HTTP/2 200 OK\r\n",
  522. "HTTP/1.2 200 OK\r\n",
  523. "HTTP/1.1 20 OK\r\n",
  524. "HTTP/1.1 2000 OK\r\n",
  525. "HTTP/1.1 2x0 OK\r\n",
  526. "HTTP/1.1 200 OK\r\n",
  527. "HTTP/1.1 200OK\r\n",
  528. "HTTP/1.1 200 O\rK\r\n",
  529. "HTTP/1.1 200 OK",
  530. "HTTP/1.1 200 OK\r\nX",
  531. "",
  532. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  533. "HTTP/1.1 200 OK\n",
  534. #endif
  535. };
  536. for (auto line : lines) {
  537. std::string version;
  538. int status = 0;
  539. std::string reason;
  540. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  541. << line;
  542. }
  543. }
  544. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  545. // Long enough to overflow the stack when matched with std::regex.
  546. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  547. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  548. std::string version;
  549. int status = 0;
  550. std::string reason;
  551. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  552. EXPECT_EQ(200, status);
  553. EXPECT_EQ(long_reason, reason);
  554. }
  555. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  556. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  557. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  558. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  559. EXPECT_EQ("", detail::file_extension("noext"));
  560. EXPECT_EQ("", detail::file_extension("a."));
  561. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  562. EXPECT_EQ("", detail::file_extension("a.b-c"));
  563. // Long enough to overflow the stack when matched with std::regex.
  564. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  565. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  566. }
  567. #ifdef CPPHTTPLIB_SSL_ENABLED
  568. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  569. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  570. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  572. // A wildcard needs two labels after it, in the leftmost label only
  573. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  574. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  575. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  576. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  577. EXPECT_FALSE(
  578. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  579. // No name may have an empty label
  580. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  581. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  582. }
  583. #endif
  584. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  585. detail::case_ignore::hash hash;
  586. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  587. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  588. // Long enough to overflow the stack if hashed one call per character.
  589. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  590. }
  591. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  592. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  593. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  594. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  595. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  596. // Same 26-bit hash as html, svg and js.
  597. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  598. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  600. }
  601. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  602. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  603. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  604. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  605. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  606. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  607. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  608. // Same 26-bit hash as application/json.
  609. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  610. }
  611. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  612. Request req;
  613. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  614. EXPECT_TRUE(req.is_multipart_form_data());
  615. std::string boundary;
  616. EXPECT_TRUE(detail::parse_multipart_boundary(
  617. req.get_header_value("Content-Type"), boundary));
  618. EXPECT_EQ("x", boundary);
  619. }
  620. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  621. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  622. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  623. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  624. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  625. // Same 26-bit hash as REMOTE_ADDR.
  626. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  627. }
  628. // Forward declaration: in split builds split.py strips `inline` and moves the
  629. // definition into httplib.cc, so detail::base64_encode is not visible from the
  630. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  631. // in both header-only and split builds.
  632. namespace httplib {
  633. namespace detail {
  634. std::string base64_encode(const std::string &in);
  635. } // namespace detail
  636. } // namespace httplib
  637. TEST(Base64EncodeTest, KnownAnswers) {
  638. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  639. // where the accumulator's top bit is already set before the next shift.
  640. EXPECT_EQ("", detail::base64_encode(""));
  641. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  642. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  643. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  644. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  645. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  646. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  647. // High bytes keep the top bit set across several rounds.
  648. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  649. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  650. }
  651. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  652. string unescapedCharacters = "-_.!~*'()";
  653. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  654. }
  655. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  656. string reservedCharacters = ";,/?:@&=+$";
  657. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  658. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  659. }
  660. TEST(ClientQueryOrder, PreserveOrder) {
  661. // This test reproduces Issue #2259: client may reorder query parameters
  662. // when sending a GET request. The expected behavior is that the client
  663. // preserves the original query string order when the caller supplied it
  664. // as part of the path.
  665. Server svr;
  666. svr.Get("/", [&](const Request &req, Response &res) {
  667. // Echo back the raw target so the test can assert ordering
  668. res.set_content(req.target, "text/plain");
  669. });
  670. std::thread t{[&] { svr.listen(HOST, PORT); }};
  671. auto se = detail::scope_exit([&] {
  672. svr.stop();
  673. t.join();
  674. ASSERT_FALSE(svr.is_running());
  675. });
  676. svr.wait_until_ready();
  677. Client cli(HOST, PORT);
  678. ASSERT_TRUE(cli.is_valid());
  679. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  680. auto res = cli.Get(original);
  681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  682. // Expect the echoed target to exactly match the original path (order
  683. // preserved)
  684. EXPECT_EQ(res->body, original);
  685. }
  686. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  687. string chineseCharacters = U8("中国語");
  688. string russianCharacters = U8("дом");
  689. string brazilianCharacters = U8("óculos");
  690. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  691. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  692. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  693. "%D0%B4%D0%BE%D0%BC");
  694. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  695. }
  696. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  697. string unescapedCharacters = "-_.!~*'()";
  698. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  699. }
  700. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  701. string reservedCharacters = ";,/?:@&=+$";
  702. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  703. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  704. }
  705. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  706. string chineseCharacters = U8("中国語");
  707. string russianCharacters = U8("дом");
  708. string brazilianCharacters = U8("óculos");
  709. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  710. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  711. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  712. "%D0%B4%D0%BE%D0%BC");
  713. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  714. }
  715. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  716. // Issue #2082 use case: encoding path component with ampersand
  717. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  718. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  719. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  720. }
  721. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  722. string unescapedCharacters = "-_.!~*'()";
  723. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  724. }
  725. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  726. string reservedCharacters = ";,/?:@&=+$#";
  727. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  728. }
  729. TEST(EncodeUriTest, TestUTF8Characters) {
  730. string chineseCharacters = U8("中国語");
  731. string russianCharacters = U8("дом");
  732. string brazilianCharacters = U8("óculos");
  733. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  734. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  735. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  736. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  737. }
  738. TEST(EncodeUriTest, TestCompleteUri) {
  739. string uri =
  740. "https://example.com/path/to/resource?query=value&param=test#fragment";
  741. EXPECT_EQ(
  742. httplib::encode_uri(uri),
  743. "https://example.com/path/to/resource?query=value&param=test#fragment");
  744. }
  745. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  746. string uri =
  747. "https://example.com/path with spaces/file name.html?q=hello world";
  748. EXPECT_EQ(httplib::encode_uri(uri),
  749. "https://example.com/path%20with%20spaces/"
  750. "file%20name.html?q=hello%20world");
  751. }
  752. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  753. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  754. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  755. }
  756. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  757. string unescapedCharacters = "-_.!~*'()";
  758. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  759. }
  760. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  761. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  762. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  763. string encodedBrazilian = "%C3%B3culos";
  764. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  765. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  767. }
  768. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  769. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  770. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  771. "Piri Tommy Villiers - on & on");
  772. }
  773. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  774. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  775. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  776. }
  777. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  778. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  779. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  780. }
  781. TEST(DecodeUriTest, TestUTF8Characters) {
  782. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  783. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  784. string encodedBrazilian = "%C3%B3culos";
  785. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  786. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  787. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  788. }
  789. TEST(DecodeUriTest, TestCompleteUri) {
  790. string encodedUri = "https://example.com/path%20with%20spaces/"
  791. "file%20name.html?q=hello%20world";
  792. EXPECT_EQ(
  793. httplib::decode_uri(encodedUri),
  794. "https://example.com/path with spaces/file name.html?q=hello world");
  795. }
  796. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  797. string original =
  798. "https://example.com/path with spaces/file name.html?q=hello world";
  799. string encoded = httplib::encode_uri(original);
  800. string decoded = httplib::decode_uri(encoded);
  801. EXPECT_EQ(decoded, original);
  802. }
  803. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  804. // decode_uri is the inverse of encode_uri: an escaped reserved character
  805. // stays encoded so it is not promoted into a real delimiter, while
  806. // non-reserved escapes still decode (like JS decodeURI).
  807. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  808. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  809. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  810. "%3F%3A%40%26%3D%2B%24%2C%3B");
  811. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  812. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  813. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  814. "http://example.com/a%2Fb");
  815. // decode_uri_component still decodes the reserved character.
  816. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  817. }
  818. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  819. string original = "Piri Tommy Villiers - on & on";
  820. string encoded = httplib::encode_uri_component(original);
  821. string decoded = httplib::decode_uri_component(encoded);
  822. EXPECT_EQ(decoded, original);
  823. }
  824. TEST(TrimTests, TrimStringTests) {
  825. EXPECT_EQ("abc", detail::trim_copy("abc"));
  826. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  827. EXPECT_TRUE(detail::trim_copy("").empty());
  828. }
  829. TEST(AsciiTest, LocaleIndependentClassification) {
  830. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  831. // which consult the global C locale: std::isalnum(0xC5) can return true
  832. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  833. // helpers must classify every byte by the ASCII grammar alone.
  834. for (int i = 0; i < 256; i++) {
  835. auto c = static_cast<char>(i);
  836. auto is_digit = i >= '0' && i <= '9';
  837. auto is_upper = i >= 'A' && i <= 'Z';
  838. auto is_lower = i >= 'a' && i <= 'z';
  839. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  840. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  841. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  842. << "byte " << i;
  843. }
  844. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  845. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  846. // Non-ASCII bytes must be percent-encoded, never passed through as
  847. // alphanumeric.
  848. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  849. }
  850. TEST(FromCharsTest, Double) {
  851. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  852. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  853. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  854. auto parse = [](const std::string &s, double &v) {
  855. return detail::from_chars(s.data(), s.data() + s.size(), v);
  856. };
  857. double v = -1.0;
  858. // Representative quality values.
  859. EXPECT_EQ(parse("0", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 0.0);
  861. EXPECT_EQ(parse("1", v).ec, std::errc{});
  862. EXPECT_DOUBLE_EQ(v, 1.0);
  863. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.8);
  865. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 0.001);
  867. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 1.0);
  869. // A missing integer or fractional part is tolerated.
  870. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 0.5);
  872. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 5.0);
  874. // Values outside [0, 1] still parse; the caller range-checks them.
  875. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 123.456);
  877. // Stops at the first byte that is not part of the number and reports where.
  878. std::string trailing = "0.9, text/html";
  879. auto r = parse(trailing, v);
  880. EXPECT_EQ(r.ec, std::errc{});
  881. EXPECT_DOUBLE_EQ(v, 0.9);
  882. EXPECT_EQ(*r.ptr, ',');
  883. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  884. // outright, and an 'e'/'E' simply ends the number.
  885. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  886. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  887. std::string exp_input = "1.5e3";
  888. r = parse(exp_input, v);
  889. EXPECT_EQ(r.ec, std::errc{});
  890. EXPECT_DOUBLE_EQ(v, 1.5);
  891. EXPECT_EQ(*r.ptr, 'e');
  892. // Invalid inputs.
  893. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  898. // Pathological but well-formed inputs must stay bounded (no overflow, no
  899. // out-of-bounds table access) and stay within [0, 1] for the caller.
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  901. std::errc{});
  902. EXPECT_DOUBLE_EQ(v, 0.0);
  903. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  904. std::errc{});
  905. EXPECT_GE(v, 0.0);
  906. EXPECT_LE(v, 1.0);
  907. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  908. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  909. }
  910. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  911. // Simple case without quality values
  912. std::vector<std::string> result1;
  913. EXPECT_TRUE(detail::parse_accept_header(
  914. "text/html,application/json,text/plain", result1));
  915. EXPECT_EQ(result1.size(), 3U);
  916. EXPECT_EQ(result1[0], "text/html");
  917. EXPECT_EQ(result1[1], "application/json");
  918. EXPECT_EQ(result1[2], "text/plain");
  919. // With quality values
  920. std::vector<std::string> result2;
  921. EXPECT_TRUE(detail::parse_accept_header(
  922. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  923. EXPECT_EQ(result2.size(), 3U);
  924. EXPECT_EQ(result2[0], "application/json"); // highest q value
  925. EXPECT_EQ(result2[1], "text/html");
  926. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  927. }
  928. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  929. // Mixed with and without quality values
  930. std::vector<std::string> result;
  931. EXPECT_TRUE(detail::parse_accept_header(
  932. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  933. EXPECT_EQ(result.size(), 3U);
  934. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  935. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  936. EXPECT_EQ(result[2], "application/json"); // q=0.5
  937. }
  938. TEST(ParseAcceptHeaderTest, EdgeCases) {
  939. // Empty header
  940. std::vector<std::string> empty_result;
  941. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  942. EXPECT_TRUE(empty_result.empty());
  943. // Single type
  944. std::vector<std::string> single_result;
  945. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  946. EXPECT_EQ(single_result.size(), 1U);
  947. EXPECT_EQ(single_result[0], "application/json");
  948. // Wildcard types
  949. std::vector<std::string> wildcard_result;
  950. EXPECT_TRUE(detail::parse_accept_header(
  951. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  952. EXPECT_EQ(wildcard_result.size(), 3U);
  953. EXPECT_EQ(wildcard_result[0], "application/json");
  954. EXPECT_EQ(wildcard_result[1], "text/*");
  955. EXPECT_EQ(wildcard_result[2], "*/*");
  956. }
  957. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  958. // Common browser Accept header
  959. std::vector<std::string> browser_result;
  960. EXPECT_TRUE(
  961. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  962. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  963. browser_result));
  964. EXPECT_EQ(browser_result.size(), 6U);
  965. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  970. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  971. // API client header
  972. std::vector<std::string> api_result;
  973. EXPECT_TRUE(detail::parse_accept_header(
  974. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  975. api_result));
  976. EXPECT_EQ(api_result.size(), 3U);
  977. EXPECT_EQ(api_result[0], "application/json");
  978. EXPECT_EQ(api_result[1], "application/xml");
  979. EXPECT_EQ(api_result[2], "text/plain");
  980. }
  981. TEST(ParseAcceptHeaderTest, SpecialCases) {
  982. // Quality value with 3 decimal places
  983. std::vector<std::string> decimal_result;
  984. EXPECT_TRUE(detail::parse_accept_header(
  985. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  986. EXPECT_EQ(decimal_result.size(), 2U);
  987. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  988. EXPECT_EQ(decimal_result[1], "text/html");
  989. // Zero quality (should still be included but with lowest priority)
  990. std::vector<std::string> zero_q_result;
  991. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  992. zero_q_result));
  993. EXPECT_EQ(zero_q_result.size(), 2U);
  994. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  995. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  996. // No spaces around commas
  997. std::vector<std::string> no_space_result;
  998. EXPECT_TRUE(detail::parse_accept_header(
  999. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1000. no_space_result));
  1001. EXPECT_EQ(no_space_result.size(), 3U);
  1002. EXPECT_EQ(no_space_result[0], "text/html");
  1003. EXPECT_EQ(no_space_result[1], "application/json");
  1004. EXPECT_EQ(no_space_result[2], "text/plain");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1007. // Quality values always use '.' as the decimal separator, so parsing must
  1008. // not depend on the process locale. An embedding application may have
  1009. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1010. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1011. std::string saved = cur ? cur : "C";
  1012. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1013. "fr_FR.UTF-8"};
  1014. bool switched = false;
  1015. for (const auto loc : comma_locales) {
  1016. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1017. std::localeconv()->decimal_point[0] == ',') {
  1018. switched = true;
  1019. break;
  1020. }
  1021. }
  1022. if (!switched) {
  1023. std::setlocale(LC_NUMERIC, saved.c_str());
  1024. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1025. }
  1026. // The higher-weighted type appears later in the list, so a correct parse
  1027. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1028. // sensitive parse reads both weights as 0 and leaves the original order.
  1029. std::vector<std::string> result;
  1030. EXPECT_TRUE(detail::parse_accept_header(
  1031. "application/json;q=0.1,text/html;q=0.9", result));
  1032. ASSERT_EQ(result.size(), 2U);
  1033. EXPECT_EQ(result[0], "text/html");
  1034. EXPECT_EQ(result[1], "application/json");
  1035. std::setlocale(LC_NUMERIC, saved.c_str());
  1036. }
  1037. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1038. std::vector<std::string> result;
  1039. // Invalid quality value (> 1.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1042. // Invalid quality value (< 0.0)
  1043. EXPECT_FALSE(
  1044. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1045. // Invalid quality value (not a number)
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=invalid,application/json", result));
  1048. // A valid numeric prefix does not make the entire quality value valid.
  1049. EXPECT_FALSE(detail::parse_accept_header(
  1050. "text/html;q=0.5junk,application/json", result));
  1051. // Empty quality value
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("text/html;q=,application/json", result));
  1054. // Invalid media type format (no slash and not wildcard)
  1055. EXPECT_FALSE(
  1056. detail::parse_accept_header("invalidtype,application/json", result));
  1057. // Valid cases should still work
  1058. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*/*");
  1061. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "*");
  1064. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1065. EXPECT_EQ(result.size(), 1U);
  1066. EXPECT_EQ(result[0], "text/*");
  1067. }
  1068. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1069. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1070. // and must not be answered with 400 Bad Request.
  1071. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1072. struct {
  1073. const char *value;
  1074. std::vector<std::string> expected;
  1075. } cases[] = {
  1076. {",application/json", {"application/json"}},
  1077. {"text/html,", {"text/html"}},
  1078. {"text/html,,*/*", {"text/html", "*/*"}},
  1079. // An empty element may be spelled with whitespace in it
  1080. {"text/html, , application/json", {"text/html", "application/json"}},
  1081. // Nothing but empty elements is an empty list, which means the same
  1082. // thing as no Accept header at all
  1083. {",,,", {}},
  1084. // Quality values still apply across ignored empty elements
  1085. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1086. };
  1087. for (const auto &c : cases) {
  1088. std::vector<std::string> result;
  1089. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1090. << "value: " << c.value;
  1091. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1092. }
  1093. // An invalid entry is still rejected when empty elements surround it
  1094. std::vector<std::string> result;
  1095. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1096. }
  1097. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1098. // or ';' inside one does not end the list element or the parameter. Section
  1099. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1100. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1101. struct {
  1102. const char *value;
  1103. std::vector<std::string> expected;
  1104. } cases[] = {
  1105. {"text/html;profile=\"a,b\",application/json",
  1106. {"text/html", "application/json"}},
  1107. // A "q=" inside a quoted value is not the weight
  1108. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1109. {"text/html", "application/json"}},
  1110. // The weight after a quoted value still applies
  1111. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1112. {"application/json", "text/html"}},
  1113. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1114. {"application/json", "text/html"}},
  1115. {"text/html;profile=\"a\\\"b\",application/json",
  1116. {"text/html", "application/json"}},
  1117. // An escaped backslash does not escape the '"' after it
  1118. {"text/html;profile=\"a\\\\\",application/json",
  1119. {"text/html", "application/json"}},
  1120. };
  1121. for (const auto &c : cases) {
  1122. std::vector<std::string> result;
  1123. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1124. << "value: " << c.value;
  1125. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1126. }
  1127. }
  1128. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1129. Server svr;
  1130. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1131. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1132. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1133. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1134. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1135. res.set_content("ok", "text/plain");
  1136. });
  1137. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1138. EXPECT_TRUE(false);
  1139. res.set_content("bad request", "text/plain");
  1140. });
  1141. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1142. auto se = detail::scope_exit([&] {
  1143. svr.stop();
  1144. listen_thread.join();
  1145. ASSERT_FALSE(svr.is_running());
  1146. });
  1147. svr.wait_until_ready();
  1148. Client cli("localhost", PORT);
  1149. {
  1150. auto res = cli.Get(
  1151. "/accept_ok",
  1152. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1154. EXPECT_EQ(StatusCode::OK_200, res->status);
  1155. }
  1156. {
  1157. auto res = cli.Get("/accept_bad_request",
  1158. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1161. }
  1162. }
  1163. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1164. Server svr;
  1165. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1166. res.set_content("ok", "text/plain");
  1167. });
  1168. std::atomic<int> start_count{0};
  1169. std::atomic<bool> running_when_called{false};
  1170. svr.set_start_handler([&]() {
  1171. running_when_called = svr.is_running();
  1172. start_count++;
  1173. });
  1174. auto port = svr.bind_to_any_port(HOST);
  1175. std::thread t([&]() { svr.listen_after_bind(); });
  1176. auto se = detail::scope_exit([&] {
  1177. svr.stop();
  1178. t.join();
  1179. ASSERT_FALSE(svr.is_running());
  1180. });
  1181. svr.wait_until_ready();
  1182. // A successful request proves the accept loop is running, which the start
  1183. // handler precedes; so by now the handler must have run exactly once.
  1184. Client cli(HOST, port);
  1185. cli.set_connection_timeout(std::chrono::seconds(5));
  1186. auto res = cli.Get("/");
  1187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1188. EXPECT_EQ(StatusCode::OK_200, res->status);
  1189. EXPECT_EQ(1, start_count.load());
  1190. EXPECT_TRUE(running_when_called.load());
  1191. }
  1192. TEST(DivideTest, DivideStringTests) {
  1193. auto divide = [](const std::string &str, char d) {
  1194. std::string lhs;
  1195. std::string rhs;
  1196. detail::divide(str, d,
  1197. [&](const char *lhs_data, std::size_t lhs_size,
  1198. const char *rhs_data, std::size_t rhs_size) {
  1199. lhs.assign(lhs_data, lhs_size);
  1200. rhs.assign(rhs_data, rhs_size);
  1201. });
  1202. return std::make_pair(std::move(lhs), std::move(rhs));
  1203. };
  1204. {
  1205. const auto res = divide("", '=');
  1206. EXPECT_EQ(res.first, "");
  1207. EXPECT_EQ(res.second, "");
  1208. }
  1209. {
  1210. const auto res = divide("=", '=');
  1211. EXPECT_EQ(res.first, "");
  1212. EXPECT_EQ(res.second, "");
  1213. }
  1214. {
  1215. const auto res = divide(" ", '=');
  1216. EXPECT_EQ(res.first, " ");
  1217. EXPECT_EQ(res.second, "");
  1218. }
  1219. {
  1220. const auto res = divide("a", '=');
  1221. EXPECT_EQ(res.first, "a");
  1222. EXPECT_EQ(res.second, "");
  1223. }
  1224. {
  1225. const auto res = divide("a=", '=');
  1226. EXPECT_EQ(res.first, "a");
  1227. EXPECT_EQ(res.second, "");
  1228. }
  1229. {
  1230. const auto res = divide("=b", '=');
  1231. EXPECT_EQ(res.first, "");
  1232. EXPECT_EQ(res.second, "b");
  1233. }
  1234. {
  1235. const auto res = divide("a=b", '=');
  1236. EXPECT_EQ(res.first, "a");
  1237. EXPECT_EQ(res.second, "b");
  1238. }
  1239. {
  1240. const auto res = divide("a=b=", '=');
  1241. EXPECT_EQ(res.first, "a");
  1242. EXPECT_EQ(res.second, "b=");
  1243. }
  1244. {
  1245. const auto res = divide("a=b=c", '=');
  1246. EXPECT_EQ(res.first, "a");
  1247. EXPECT_EQ(res.second, "b=c");
  1248. }
  1249. }
  1250. TEST(SplitTest, ParseQueryString) {
  1251. string s = "key1=val1&key2=val2&key3=val3";
  1252. Params dic;
  1253. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1254. [&](const char *b, const char *e) {
  1255. string key, val;
  1256. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1257. if (key.empty()) {
  1258. key.assign(b2, e2);
  1259. } else {
  1260. val.assign(b2, e2);
  1261. }
  1262. });
  1263. dic.emplace(key, val);
  1264. });
  1265. EXPECT_EQ("val1", dic.find("key1")->second);
  1266. EXPECT_EQ("val2", dic.find("key2")->second);
  1267. EXPECT_EQ("val3", dic.find("key3")->second);
  1268. }
  1269. TEST(SplitTest, ParseInvalidQueryTests) {
  1270. {
  1271. string s = " ";
  1272. Params dict;
  1273. detail::parse_query_text(s, dict);
  1274. EXPECT_TRUE(dict.empty());
  1275. }
  1276. {
  1277. string s = " = =";
  1278. Params dict;
  1279. detail::parse_query_text(s, dict);
  1280. EXPECT_TRUE(dict.empty());
  1281. }
  1282. }
  1283. TEST(ParseQueryTest, ParseQueryString) {
  1284. {
  1285. std::string s = "key1=val1&key2=val2&key3=val3";
  1286. Params dic;
  1287. detail::parse_query_text(s, dic);
  1288. EXPECT_EQ("val1", dic.find("key1")->second);
  1289. EXPECT_EQ("val2", dic.find("key2")->second);
  1290. EXPECT_EQ("val3", dic.find("key3")->second);
  1291. }
  1292. {
  1293. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1294. Params dic;
  1295. detail::parse_query_text(s, dic);
  1296. EXPECT_EQ("", dic.find("key1")->second);
  1297. EXPECT_EQ("val1", dic.find("key2")->second);
  1298. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1299. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1300. }
  1301. }
  1302. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1303. Params dic;
  1304. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1305. dic.emplace("key1", "val1");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1307. dic.emplace("key2", "val2");
  1308. dic.emplace("key3", "val3");
  1309. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1310. }
  1311. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1312. Params params;
  1313. params.emplace("a", "1");
  1314. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1315. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1316. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1317. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1318. // Long enough to overflow the stack when matched with std::regex.
  1319. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1320. EXPECT_EQ("/p?" + long_query + "&a=1",
  1321. append_query_params("/p?" + long_query, params));
  1322. }
  1323. // Joins every entry of a Headers or Params into "key=value " so a whole
  1324. // traversal can be compared in one assertion. Both are instantiations of the
  1325. // same insertion-ordered container, so one helper serves both.
  1326. template <typename Map> static std::string entries_to_string(const Map &m) {
  1327. std::string s;
  1328. for (const auto &entry : m) {
  1329. s += entry.first + "=" + entry.second + " ";
  1330. }
  1331. return s;
  1332. }
  1333. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1334. // Params used to be a std::multimap, which sorted by name and handed the
  1335. // caller's query back alphabetised. A client signing its query string could
  1336. // not reproduce the order it asked for.
  1337. Params dic;
  1338. dic.emplace("zulu", "1");
  1339. dic.emplace("alpha", "2");
  1340. dic.emplace("mike", "3");
  1341. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1342. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1343. }
  1344. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1345. Params dic;
  1346. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1347. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1348. }
  1349. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1350. Request req;
  1351. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1352. req.params);
  1353. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1354. EXPECT_EQ("first", req.get_param_value("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1356. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1357. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1358. EXPECT_EQ("", req.get_param_value("tag", 3));
  1359. }
  1360. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1361. // Params shares its container with Headers, which matches field names
  1362. // case-insensitively. Parameter names must not pick that up.
  1363. Params dic;
  1364. dic.emplace("Key", "upper");
  1365. dic.emplace("key", "lower");
  1366. EXPECT_EQ(2U, dic.size());
  1367. EXPECT_EQ(1U, dic.count("Key"));
  1368. EXPECT_EQ(1U, dic.count("key"));
  1369. EXPECT_EQ("upper", dic.find("Key")->second);
  1370. EXPECT_EQ("lower", dic.find("key")->second);
  1371. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1372. }
  1373. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1374. Server svr;
  1375. std::string order;
  1376. svr.Get("/order", [&](const Request &req, Response &res) {
  1377. order = entries_to_string(req.params);
  1378. res.set_content("ok", "text/plain");
  1379. });
  1380. auto port = svr.bind_to_any_port(HOST);
  1381. thread t = thread([&] { svr.listen_after_bind(); });
  1382. auto se = detail::scope_exit([&] {
  1383. svr.stop();
  1384. t.join();
  1385. ASSERT_FALSE(svr.is_running());
  1386. });
  1387. svr.wait_until_ready();
  1388. Client cli(HOST, port);
  1389. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1390. ASSERT_TRUE(res);
  1391. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1392. }
  1393. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1394. Server svr;
  1395. std::string field_order, file_order;
  1396. svr.Post("/order", [&](const Request &req, Response &res) {
  1397. for (const auto &field : req.form.fields) {
  1398. field_order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. for (const auto &file : req.form.files) {
  1401. file_order += file.first + "=" + file.second.filename + " ";
  1402. }
  1403. res.set_content("ok", "text/plain");
  1404. });
  1405. auto port = svr.bind_to_any_port(HOST);
  1406. thread t = thread([&] { svr.listen_after_bind(); });
  1407. auto se = detail::scope_exit([&] {
  1408. svr.stop();
  1409. t.join();
  1410. ASSERT_FALSE(svr.is_running());
  1411. });
  1412. svr.wait_until_ready();
  1413. UploadFormDataItems items = {
  1414. {"zulu", "1", "", ""},
  1415. {"alpha", "2", "", ""},
  1416. {"mike", "3", "", ""},
  1417. {"zebra", "z", "z.txt", "text/plain"},
  1418. {"apple", "a", "a.txt", "text/plain"},
  1419. };
  1420. Client cli(HOST, port);
  1421. auto res = cli.Post("/order", items);
  1422. ASSERT_TRUE(res);
  1423. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1424. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1425. }
  1426. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1427. Server svr;
  1428. std::vector<std::string> values;
  1429. std::string first, second, out_of_range, order;
  1430. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1431. values = req.form.get_fields("tag");
  1432. first = req.form.get_field("tag", 0);
  1433. second = req.form.get_field("tag", 1);
  1434. out_of_range = req.form.get_field("tag", 2);
  1435. for (const auto &field : req.form.fields) {
  1436. order += field.first + "=" + field.second.content + " ";
  1437. }
  1438. res.set_content("ok", "text/plain");
  1439. });
  1440. auto port = svr.bind_to_any_port(HOST);
  1441. thread t = thread([&] { svr.listen_after_bind(); });
  1442. auto se = detail::scope_exit([&] {
  1443. svr.stop();
  1444. t.join();
  1445. ASSERT_FALSE(svr.is_running());
  1446. });
  1447. svr.wait_until_ready();
  1448. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1449. // not adjacent in the container.
  1450. UploadFormDataItems items = {
  1451. {"tag", "first", "", ""},
  1452. {"other", "x", "", ""},
  1453. {"tag", "second", "", ""},
  1454. };
  1455. Client cli(HOST, port);
  1456. auto res = cli.Post("/repeated", items);
  1457. ASSERT_TRUE(res);
  1458. ASSERT_EQ(2U, values.size());
  1459. EXPECT_EQ("first", values[0]);
  1460. EXPECT_EQ("second", values[1]);
  1461. EXPECT_EQ("first", first);
  1462. EXPECT_EQ("second", second);
  1463. // std::multimap already kept entries sharing a name in insertion order, so
  1464. // everything above passes without this change too. The whole traversal is
  1465. // what tells the two apart: sorting by name would hoist "other" to the front
  1466. // and the two "tag" parts would end up adjacent.
  1467. EXPECT_EQ("tag=first other=x tag=second ", order);
  1468. // Advancing past the last entry of a name used to run off the container;
  1469. // the container's saturating increment makes it return the default instead.
  1470. EXPECT_EQ("", out_of_range);
  1471. }
  1472. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1473. Server svr;
  1474. std::string file_names;
  1475. svr.Post("/upload", [&](const Request &req, Response &res) {
  1476. for (const auto &file : req.form.files) {
  1477. file_names += file.first + "|" + file.second.filename + " ";
  1478. }
  1479. res.set_content("ok", "text/plain");
  1480. });
  1481. auto port = svr.bind_to_any_port(HOST);
  1482. thread t = thread([&] { svr.listen_after_bind(); });
  1483. auto se = detail::scope_exit([&] {
  1484. svr.stop();
  1485. t.join();
  1486. ASSERT_FALSE(svr.is_running());
  1487. });
  1488. svr.wait_until_ready();
  1489. // A trailing backslash would otherwise escape the closing quote.
  1490. UploadFormDataItems items = {
  1491. {"dir\\", "x", "a.txt", "text/plain"},
  1492. {"b", "y", "a\\\\b.txt", "text/plain"},
  1493. };
  1494. Client cli(HOST, port);
  1495. auto res = cli.Post("/upload", items);
  1496. ASSERT_TRUE(res);
  1497. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1498. }
  1499. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1500. // Server::read_content() keeps a FormFields::iterator alive across the
  1501. // content callbacks that fill the part it points at. The container is
  1502. // vector-backed, so a later emplace can reallocate and invalidate an older
  1503. // iterator; 64 parts grow the vector through seven reallocations, which
  1504. // checks that every part's content still lands in its own entry.
  1505. const size_t part_count = 64;
  1506. // One formula for both the parts sent and the values expected back, so the
  1507. // two cannot drift apart.
  1508. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1509. auto content_of = [](size_t i) {
  1510. return std::string(64, static_cast<char>('a' + (i % 26)));
  1511. };
  1512. Server svr;
  1513. std::vector<std::pair<std::string, std::string>> received;
  1514. svr.Post("/many", [&](const Request &req, Response &res) {
  1515. for (const auto &field : req.form.fields) {
  1516. received.emplace_back(field.first, field.second.content);
  1517. }
  1518. res.set_content("ok", "text/plain");
  1519. });
  1520. auto port = svr.bind_to_any_port(HOST);
  1521. thread t = thread([&] { svr.listen_after_bind(); });
  1522. auto se = detail::scope_exit([&] {
  1523. svr.stop();
  1524. t.join();
  1525. ASSERT_FALSE(svr.is_running());
  1526. });
  1527. svr.wait_until_ready();
  1528. UploadFormDataItems items;
  1529. for (size_t i = 0; i < part_count; i++) {
  1530. items.push_back({name_of(i), content_of(i), "", ""});
  1531. }
  1532. Client cli(HOST, port);
  1533. auto res = cli.Post("/many", items);
  1534. ASSERT_TRUE(res);
  1535. ASSERT_EQ(part_count, received.size());
  1536. for (size_t i = 0; i < part_count; i++) {
  1537. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1538. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1539. }
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1542. string content_type = "multipart/form-data; boundary=something";
  1543. string boundary;
  1544. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1545. EXPECT_TRUE(ret);
  1546. EXPECT_EQ(boundary, "something");
  1547. }
  1548. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1549. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1550. string boundary;
  1551. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1552. EXPECT_TRUE(ret);
  1553. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1556. string content_type =
  1557. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1558. string boundary;
  1559. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1562. }
  1563. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1564. string content_type =
  1565. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1566. string boundary;
  1567. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1568. EXPECT_TRUE(ret);
  1569. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1570. }
  1571. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1572. const string boundary(70, 'a');
  1573. string content_type = "multipart/form-data; boundary=" + boundary;
  1574. string parsed;
  1575. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1576. EXPECT_TRUE(ret);
  1577. EXPECT_EQ(parsed, boundary);
  1578. }
  1579. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1580. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1581. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1582. string parsed;
  1583. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1584. EXPECT_FALSE(ret);
  1585. }
  1586. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1587. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1588. // is 72 characters on the wire and still valid.
  1589. const string boundary(70, 'a');
  1590. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1591. string parsed;
  1592. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1593. EXPECT_EQ(parsed, boundary);
  1594. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1595. parsed.clear();
  1596. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1597. }
  1598. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1599. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1600. // The parameter parser must not treat that '=' as the key/value separator.
  1601. string content_type =
  1602. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1603. "charset=UTF-8";
  1604. string parsed;
  1605. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1606. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1607. }
  1608. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1609. // A ';' inside the quoted-string is part of the value, not a parameter
  1610. // separator, so it must not truncate the boundary.
  1611. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1612. string parsed;
  1613. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1614. EXPECT_EQ(parsed, "a;b");
  1615. }
  1616. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1617. string parsed;
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1620. EXPECT_EQ("a\\b", parsed);
  1621. EXPECT_TRUE(detail::parse_multipart_boundary(
  1622. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1623. EXPECT_EQ("a\"b", parsed);
  1624. }
  1625. TEST(ParseDispositionParamsTest, QuotedValues) {
  1626. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1627. // ';' and '=' are ordinary characters inside one.
  1628. struct {
  1629. const char *value;
  1630. std::vector<std::pair<const char *, const char *>> expected;
  1631. } cases[] = {
  1632. {"name=\"file1\"; filename=\"a.txt\"",
  1633. {{"name", "file1"}, {"filename", "a.txt"}}},
  1634. // Whitespace around '=' and ';' is still trimmed
  1635. {"name=\"file2\" ;filename = \"a.html\"",
  1636. {{"name", "file2"}, {"filename", "a.html"}}},
  1637. // '=' inside the value used to leave only the text after the last one
  1638. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1639. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1640. {"name=\"x=y\"", {{"name", "x=y"}}},
  1641. // ';' inside the value used to truncate the pair and leave a bogus one
  1642. {"name=\"file3\"; filename=\"a;b.txt\"",
  1643. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1644. // An unquoted value keeps working, and so does filename*
  1645. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1646. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1647. // A parameter with no key is dropped rather than turned into one whose
  1648. // key is the value
  1649. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1650. // An escaped quote does not end the value
  1651. {"name=\"a\\\"; filename=evil.php\"",
  1652. {{"name", "a\"; filename=evil.php"}}},
  1653. // Other backslashes, as in a Windows path, are kept
  1654. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1655. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1656. };
  1657. for (const auto &c : cases) {
  1658. Params params;
  1659. detail::parse_disposition_params(c.value, params);
  1660. for (const auto &kv : c.expected) {
  1661. auto it = params.find(kv.first);
  1662. ASSERT_NE(it, params.end())
  1663. << "value: " << c.value << ", key: " << kv.first;
  1664. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1665. }
  1666. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1667. }
  1668. }
  1669. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1670. Server svr;
  1671. std::string filename;
  1672. std::string content;
  1673. svr.Post("/upload", [&](const Request &req, Response &) {
  1674. const auto &file = req.form.get_file("file");
  1675. filename = file.filename;
  1676. content = file.content;
  1677. });
  1678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1679. auto se = detail::scope_exit([&] {
  1680. svr.stop();
  1681. thread.join();
  1682. ASSERT_FALSE(svr.is_running());
  1683. });
  1684. svr.wait_until_ready();
  1685. std::string body = "--B\r\n"
  1686. "Content-Disposition: form-data; name=\"file\"; "
  1687. "filename=\"a.txt\"\r\n"
  1688. "Content-Type: text/plain\r\n"
  1689. "\r\n"
  1690. "hello\r\n"
  1691. "--B--\r\n";
  1692. Client cli(HOST, PORT);
  1693. auto res = cli.Post(
  1694. "/upload",
  1695. [&](size_t offset, DataSink &sink) {
  1696. if (offset < body.size()) {
  1697. sink.write(&body[offset], 1);
  1698. } else {
  1699. sink.done();
  1700. }
  1701. return true;
  1702. },
  1703. "multipart/form-data; boundary=B");
  1704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1705. EXPECT_EQ(StatusCode::OK_200, res->status);
  1706. EXPECT_EQ("a.txt", filename);
  1707. EXPECT_EQ("hello", content);
  1708. }
  1709. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1710. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1711. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1712. Server svr;
  1713. std::string field_value, file_name, file_filename;
  1714. bool has_field = false, has_file = false;
  1715. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1716. has_field = req.form.has_field("x=y");
  1717. field_value = req.form.get_field("x=y");
  1718. has_file = req.form.has_file("file1");
  1719. const auto &file = req.form.get_file("file1");
  1720. file_name = file.name;
  1721. file_filename = file.filename;
  1722. res.set_content("ok", "text/plain");
  1723. });
  1724. auto port = svr.bind_to_any_port(HOST);
  1725. thread t = thread([&] { svr.listen_after_bind(); });
  1726. auto se = detail::scope_exit([&] {
  1727. svr.stop();
  1728. t.join();
  1729. ASSERT_FALSE(svr.is_running());
  1730. });
  1731. svr.wait_until_ready();
  1732. UploadFormDataItems items = {
  1733. {"x=y", "field-value", "", ""},
  1734. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1735. };
  1736. Client cli(HOST, port);
  1737. auto res = cli.Post("/quoted", items);
  1738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1739. ASSERT_EQ(StatusCode::OK_200, res->status);
  1740. EXPECT_TRUE(has_field);
  1741. EXPECT_EQ("field-value", field_value);
  1742. EXPECT_TRUE(has_file);
  1743. EXPECT_EQ("file1", file_name);
  1744. EXPECT_EQ("a;b=report.pdf", file_filename);
  1745. }
  1746. TEST(GetHeaderValueTest, DefaultValue) {
  1747. Headers headers = {{"Dummy", "Dummy"}};
  1748. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1749. EXPECT_STREQ("text/plain", val);
  1750. }
  1751. TEST(GetHeaderValueTest, DefaultValueInt) {
  1752. Headers headers = {{"Dummy", "Dummy"}};
  1753. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1754. EXPECT_EQ(100ull, val);
  1755. }
  1756. TEST(GetHeaderValueTest, RegularValue) {
  1757. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1758. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1759. EXPECT_STREQ("text/html", val);
  1760. }
  1761. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1762. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1763. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1764. EXPECT_STREQ("text/html", val);
  1765. }
  1766. TEST(GetHeaderValueTest, SetContent) {
  1767. Response res;
  1768. res.set_content("html", "text/html");
  1769. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1770. res.set_content("text", "text/plain");
  1771. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1772. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1773. }
  1774. TEST(GetHeaderValueTest, RegularValueInt) {
  1775. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1776. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1777. EXPECT_EQ(100ull, val);
  1778. }
  1779. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1780. Headers headers = {{"Content-Length", "x"}};
  1781. auto is_invalid_value = false;
  1782. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1783. is_invalid_value);
  1784. EXPECT_EQ(0ull, val);
  1785. EXPECT_TRUE(is_invalid_value);
  1786. }
  1787. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1788. // An all-digit value that overflows size_t must be reported as invalid, not
  1789. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1790. // a large length to a small one on 32-bit builds, leaving the framing length
  1791. // wrong while is_invalid_value stayed false.
  1792. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1793. auto is_invalid_value = false;
  1794. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1795. is_invalid_value);
  1796. EXPECT_TRUE(is_invalid_value);
  1797. // A well-formed length is unaffected.
  1798. Headers ok = {{"Content-Length", "1234"}};
  1799. is_invalid_value = false;
  1800. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1801. is_invalid_value);
  1802. EXPECT_EQ(1234ull, val);
  1803. EXPECT_FALSE(is_invalid_value);
  1804. }
  1805. TEST(GetHeaderValueTest, Range) {
  1806. {
  1807. Headers headers = {make_range_header({{1, -1}})};
  1808. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1809. EXPECT_STREQ("bytes=1-", val);
  1810. }
  1811. {
  1812. Headers headers = {make_range_header({{-1, 1}})};
  1813. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1814. EXPECT_STREQ("bytes=-1", val);
  1815. }
  1816. {
  1817. Headers headers = {make_range_header({{1, 10}})};
  1818. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1819. EXPECT_STREQ("bytes=1-10", val);
  1820. }
  1821. {
  1822. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1823. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1824. EXPECT_STREQ("bytes=1-10, 100-", val);
  1825. }
  1826. {
  1827. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1828. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1829. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1830. }
  1831. {
  1832. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1833. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1834. EXPECT_STREQ("bytes=0-0, -1", val);
  1835. }
  1836. }
  1837. TEST(BearerTokenAuthTest, SchemeValidation) {
  1838. // A value shorter than "Bearer " must not throw from the fixed-length
  1839. // substr, and a non-Bearer scheme must not be reported as a token.
  1840. struct {
  1841. const char *value;
  1842. const char *expected;
  1843. } cases[] = {
  1844. {"x", ""},
  1845. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1846. {"Bearer abc123", "abc123"},
  1847. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1848. };
  1849. for (const auto &c : cases) {
  1850. Request req;
  1851. req.set_header("Authorization", c.value);
  1852. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1853. }
  1854. }
  1855. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1856. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1857. // to depend on the standard library (libstdc++ handed back duplicates in
  1858. // reverse insertion order, libc++ in insertion order).
  1859. Request req;
  1860. req.set_header("Accept-Encoding", "gzip");
  1861. req.set_header("Accept-Encoding", "deflate");
  1862. req.set_header("Accept-Encoding", "br");
  1863. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1864. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1866. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1867. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1868. }
  1869. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1870. Request req;
  1871. req.set_header("X-Test", "only");
  1872. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1873. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1875. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1876. }
  1877. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1878. Request req;
  1879. req.set_header("X-First", "1");
  1880. req.set_header("X-Test", "2");
  1881. req.params.emplace("first", "1");
  1882. req.params.emplace("test", "2");
  1883. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1884. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1885. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1886. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1887. // The second one is negative when read as a signed value
  1888. const auto max_id = (std::numeric_limits<size_t>::max)();
  1889. for (auto id : {max_id / 2, max_id}) {
  1890. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1891. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1892. EXPECT_EQ("", req.get_param_value("test", id));
  1893. EXPECT_EQ("", req.form.get_field("test", id));
  1894. EXPECT_EQ("", req.form.get_file("test", id).content);
  1895. }
  1896. }
  1897. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1898. Headers headers;
  1899. headers.emplace("Host", "example.com");
  1900. headers.emplace("Accept-Encoding", "gzip");
  1901. headers.emplace("User-Agent", "test");
  1902. headers.emplace("Accept-Encoding", "deflate");
  1903. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1904. "Accept-Encoding=deflate ",
  1905. entries_to_string(headers));
  1906. }
  1907. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1908. Headers headers = {{"Content-Type", "text/html"},
  1909. {"CONTENT-TYPE", "text/xml"}};
  1910. EXPECT_EQ(2U, headers.count("content-type"));
  1911. auto it = headers.find("content-type");
  1912. ASSERT_TRUE(it != headers.end());
  1913. EXPECT_EQ("text/html", it->second);
  1914. }
  1915. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1916. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1917. // drop only those fields and leave everything positioned between them.
  1918. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1919. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1920. auto rng = headers.equal_range("a");
  1921. headers.erase(rng.first, rng.second);
  1922. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1923. }
  1924. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1925. Headers headers = {
  1926. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1927. EXPECT_EQ(3U, headers.erase("A"));
  1928. EXPECT_EQ(0U, headers.count("A"));
  1929. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1930. }
  1931. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1932. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1933. headers.emplace_front("Host", "example.com");
  1934. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1935. entries_to_string(headers));
  1936. }
  1937. TEST(ParseHeaderValueTest, Range) {
  1938. {
  1939. Ranges ranges;
  1940. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1941. EXPECT_TRUE(ret);
  1942. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1943. }
  1944. {
  1945. Ranges ranges;
  1946. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1947. EXPECT_TRUE(ret);
  1948. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1949. }
  1950. {
  1951. Ranges ranges;
  1952. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1953. EXPECT_TRUE(ret);
  1954. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1955. }
  1956. {
  1957. Ranges ranges;
  1958. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1959. EXPECT_FALSE(ret);
  1960. }
  1961. {
  1962. Ranges ranges;
  1963. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1964. EXPECT_TRUE(ret);
  1965. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1966. }
  1967. {
  1968. Ranges ranges;
  1969. auto ret =
  1970. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1971. EXPECT_TRUE(ret);
  1972. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1973. }
  1974. {
  1975. Ranges ranges;
  1976. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1977. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1978. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1979. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1980. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1981. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1982. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1983. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1989. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1990. EXPECT_FALSE(
  1991. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1992. EXPECT_TRUE(ranges.empty());
  1993. }
  1994. {
  1995. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1996. // remainder of the representation, so it stays accepted.
  1997. Ranges ranges;
  1998. auto ret =
  1999. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2000. EXPECT_TRUE(ret);
  2001. ASSERT_EQ(1u, ranges.size());
  2002. EXPECT_EQ(0, ranges[0].first);
  2003. EXPECT_EQ(-1, ranges[0].second);
  2004. }
  2005. // RFC 9110 14.1: range unit names are case-insensitive.
  2006. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2007. Ranges ranges;
  2008. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2009. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2010. }
  2011. }
  2012. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2013. Request req;
  2014. req.set_header("Accept-Encoding", "gzip");
  2015. Response res;
  2016. res.set_header("Content-Type", "text/plain");
  2017. auto ret = detail::encoding_type(req, res);
  2018. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2019. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2020. #else
  2021. EXPECT_TRUE(ret == detail::EncodingType::None);
  2022. #endif
  2023. }
  2024. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2025. Request req;
  2026. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2027. Response res;
  2028. res.set_header("Content-Type", "text/plain");
  2029. auto ret = detail::encoding_type(req, res);
  2030. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2031. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2032. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2033. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2034. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2035. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2036. #else
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. #endif
  2039. }
  2040. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2041. Request req;
  2042. req.set_header("Accept-Encoding",
  2043. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2044. Response res;
  2045. res.set_header("Content-Type", "text/plain");
  2046. auto ret = detail::encoding_type(req, res);
  2047. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2048. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2049. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2050. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2051. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2052. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2053. #else
  2054. EXPECT_TRUE(ret == detail::EncodingType::None);
  2055. #endif
  2056. }
  2057. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2058. // All supported encodings rejected with q=0 should return None
  2059. Request req;
  2060. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2061. Response res;
  2062. res.set_header("Content-Type", "text/plain");
  2063. auto ret = detail::encoding_type(req, res);
  2064. EXPECT_TRUE(ret == detail::EncodingType::None);
  2065. }
  2066. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2067. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2068. Request req;
  2069. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2070. Response res;
  2071. res.set_header("Content-Type", "text/plain");
  2072. auto ret = detail::encoding_type(req, res);
  2073. EXPECT_TRUE(ret == detail::EncodingType::None);
  2074. }
  2075. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2076. Request req;
  2077. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2078. Response res;
  2079. res.set_header("Content-Type", "text/plain");
  2080. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2081. }
  2082. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2083. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2084. Request req;
  2085. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2086. Response res;
  2087. res.set_header("Content-Type", "text/plain");
  2088. auto ret = detail::encoding_type(req, res);
  2089. EXPECT_TRUE(ret == detail::EncodingType::None);
  2090. }
  2091. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2092. // RFC 7231: Accept-Encoding values are case-insensitive
  2093. Request req;
  2094. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2095. Response res;
  2096. res.set_header("Content-Type", "text/plain");
  2097. auto ret = detail::encoding_type(req, res);
  2098. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2100. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2101. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2102. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2103. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2104. #else
  2105. EXPECT_TRUE(ret == detail::EncodingType::None);
  2106. #endif
  2107. }
  2108. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2109. // q value should determine priority, not hardcoded order
  2110. Request req;
  2111. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2112. Response res;
  2113. res.set_header("Content-Type", "text/plain");
  2114. auto ret = detail::encoding_type(req, res);
  2115. // gzip has highest q=1.0, so it should be selected even though
  2116. // br and zstd are also supported
  2117. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2118. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2119. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2120. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2121. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2122. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2123. #else
  2124. EXPECT_TRUE(ret == detail::EncodingType::None);
  2125. #endif
  2126. }
  2127. TEST(BufferStreamTest, read) {
  2128. detail::BufferStream strm1;
  2129. Stream &strm = strm1;
  2130. EXPECT_EQ(5, strm.write("hello"));
  2131. char buf[512];
  2132. EXPECT_EQ(2, strm.read(buf, 2));
  2133. EXPECT_EQ('h', buf[0]);
  2134. EXPECT_EQ('e', buf[1]);
  2135. EXPECT_EQ(2, strm.read(buf, 2));
  2136. EXPECT_EQ('l', buf[0]);
  2137. EXPECT_EQ('l', buf[1]);
  2138. EXPECT_EQ(1, strm.read(buf, 1));
  2139. EXPECT_EQ('o', buf[0]);
  2140. EXPECT_EQ(0, strm.read(buf, 1));
  2141. }
  2142. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2143. auto host = "www.httpwatch.com";
  2144. auto ip = hosted_at(host);
  2145. EXPECT_EQ("23.96.13.243", ip);
  2146. std::vector<std::string> addrs;
  2147. hosted_at(host, addrs);
  2148. EXPECT_EQ(1u, addrs.size());
  2149. }
  2150. #if 0 // It depends on each test environment...
  2151. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2152. auto host = "www.youtube.com";
  2153. std::vector<std::string> addrs;
  2154. hosted_at(host, addrs);
  2155. EXPECT_EQ(20u, addrs.size());
  2156. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2157. EXPECT_TRUE(it != addrs.end());
  2158. }
  2159. #endif
  2160. class ChunkedEncodingTest : public ::testing::Test {
  2161. protected:
  2162. ChunkedEncodingTest()
  2163. : cli_(HOST, PORT)
  2164. #ifdef CPPHTTPLIB_SSL_ENABLED
  2165. ,
  2166. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2167. #endif
  2168. {
  2169. cli_.set_connection_timeout(2);
  2170. #ifdef CPPHTTPLIB_SSL_ENABLED
  2171. cli_.enable_server_certificate_verification(false);
  2172. #endif
  2173. }
  2174. virtual void SetUp() {
  2175. read_file("./image.jpg", image_data_);
  2176. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2177. res.set_content("Hello World!", "text/plain");
  2178. });
  2179. svr_.Get(
  2180. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2181. res.set_chunked_content_provider(
  2182. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2183. size_t remaining = image_data_.size() - offset;
  2184. if (remaining == 0) {
  2185. sink.done();
  2186. } else {
  2187. constexpr size_t CHUNK_SIZE = 1024;
  2188. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2189. sink.write(&image_data_[offset], send_size);
  2190. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2191. }
  2192. return true;
  2193. });
  2194. });
  2195. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2196. svr_.wait_until_ready();
  2197. }
  2198. virtual void TearDown() {
  2199. svr_.stop();
  2200. if (!request_threads_.empty()) {
  2201. std::this_thread::sleep_for(std::chrono::seconds(1));
  2202. for (auto &t : request_threads_) {
  2203. t.join();
  2204. }
  2205. }
  2206. t_.join();
  2207. }
  2208. #ifdef CPPHTTPLIB_SSL_ENABLED
  2209. SSLClient cli_;
  2210. SSLServer svr_;
  2211. #else
  2212. Client cli_;
  2213. Server svr_;
  2214. #endif
  2215. thread t_;
  2216. std::vector<thread> request_threads_;
  2217. std::string image_data_;
  2218. };
  2219. TEST_F(ChunkedEncodingTest, NormalGet) {
  2220. auto res = cli_.Get("/chunked");
  2221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2222. std::string out;
  2223. read_file("./image.jpg", out);
  2224. EXPECT_EQ(StatusCode::OK_200, res->status);
  2225. EXPECT_EQ(out, res->body);
  2226. }
  2227. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2228. std::string body;
  2229. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2230. body.append(data, data_length);
  2231. return true;
  2232. });
  2233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2234. std::string out;
  2235. read_file("./image.jpg", out);
  2236. EXPECT_EQ(StatusCode::OK_200, res->status);
  2237. EXPECT_EQ(out, body);
  2238. }
  2239. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2240. std::string body;
  2241. auto res = cli_.Get(
  2242. "/chunked",
  2243. [&](const Response &response) {
  2244. EXPECT_EQ(StatusCode::OK_200, response.status);
  2245. return true;
  2246. },
  2247. [&](const char *data, size_t data_length) {
  2248. body.append(data, data_length);
  2249. return true;
  2250. });
  2251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2252. std::string out;
  2253. read_file("./image.jpg", out);
  2254. EXPECT_EQ(StatusCode::OK_200, res->status);
  2255. EXPECT_EQ(out, body);
  2256. }
  2257. TEST(RangeTest, FromHTTPBin_Online) {
  2258. auto host = "httpbingo.org";
  2259. auto path = std::string{"/range/32"};
  2260. #ifdef CPPHTTPLIB_SSL_ENABLED
  2261. auto port = 443;
  2262. SSLClient cli(host, port);
  2263. #else
  2264. auto port = 80;
  2265. Client cli(host, port);
  2266. #endif
  2267. cli.set_connection_timeout(5);
  2268. {
  2269. auto res = cli.Get(path);
  2270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2271. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2272. EXPECT_EQ(StatusCode::OK_200, res->status);
  2273. }
  2274. {
  2275. Headers headers = {make_range_header({{1, -1}})};
  2276. auto res = cli.Get(path, headers);
  2277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2278. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2279. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2280. }
  2281. {
  2282. Headers headers = {make_range_header({{1, 10}})};
  2283. auto res = cli.Get(path, headers);
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ("bcdefghijk", res->body);
  2286. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2287. }
  2288. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2289. // entire resource, while the original httpbin returned 200. Both are
  2290. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2291. {
  2292. Headers headers = {make_range_header({{0, 31}})};
  2293. auto res = cli.Get(path, headers);
  2294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2295. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2296. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2297. res->status == StatusCode::PartialContent_206);
  2298. }
  2299. {
  2300. Headers headers = {make_range_header({{0, -1}})};
  2301. auto res = cli.Get(path, headers);
  2302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2303. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2304. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2305. res->status == StatusCode::PartialContent_206);
  2306. }
  2307. // go-httpbin returns 206 with clamped range for over-range requests,
  2308. // while the original httpbin returned 416. Both behaviors are observed
  2309. // in real servers, so we only verify the request succeeds.
  2310. {
  2311. Headers headers = {make_range_header({{0, 32}})};
  2312. auto res = cli.Get(path, headers);
  2313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2314. }
  2315. }
  2316. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2317. auto host = "unresolvableaddress.local";
  2318. auto path = std::string{"/"};
  2319. #ifdef CPPHTTPLIB_SSL_ENABLED
  2320. auto port = 443;
  2321. SSLClient cli(host, port);
  2322. #else
  2323. auto port = 80;
  2324. Client cli(host, port);
  2325. #endif
  2326. cli.set_connection_timeout(1);
  2327. {
  2328. auto res = cli.Get(path);
  2329. ASSERT_FALSE(res);
  2330. }
  2331. std::this_thread::sleep_for(std::chrono::seconds(8));
  2332. }
  2333. #if defined(__linux__) && defined(__GLIBC__) && \
  2334. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2335. // Forward declaration: in split builds split.py strips `inline` and moves the
  2336. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2337. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2338. // against the symbol in both header-only and split builds.
  2339. namespace httplib {
  2340. namespace detail {
  2341. int getaddrinfo_with_timeout(const char *node, const char *service,
  2342. const struct addrinfo *hints,
  2343. struct addrinfo **res, time_t timeout_sec);
  2344. } // namespace detail
  2345. } // namespace httplib
  2346. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2347. //
  2348. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2349. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2350. // gai_suspend() call hits the connection timeout the function calls
  2351. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2352. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2353. // still alive and still references the now-destroyed stack frame.
  2354. //
  2355. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2356. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2357. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2358. // and runs them in a container.
  2359. namespace {
  2360. bool should_run_issue_2431_tests() {
  2361. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2362. return v && *v && std::string(v) != "0";
  2363. }
  2364. std::string unique_unresolvable_host(int n) {
  2365. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2366. // glibc still asks the configured nameserver — which is exactly the path
  2367. // we want to exercise. A unique label per call avoids the resolver cache.
  2368. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2369. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2370. std::to_string(n) + ".invalid";
  2371. }
  2372. } // namespace
  2373. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2374. if (!should_run_issue_2431_tests()) {
  2375. GTEST_SKIP()
  2376. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2377. }
  2378. for (int i = 0; i < 8; ++i) {
  2379. struct addrinfo hints;
  2380. memset(&hints, 0, sizeof(hints));
  2381. hints.ai_family = AF_UNSPEC;
  2382. hints.ai_socktype = SOCK_STREAM;
  2383. auto host = unique_unresolvable_host(i);
  2384. struct addrinfo *result = nullptr;
  2385. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2386. &result, /*timeout_sec=*/1);
  2387. if (rc == 0 && result) { freeaddrinfo(result); }
  2388. }
  2389. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2390. // stack region they still believe holds their gaicb.
  2391. std::this_thread::sleep_for(std::chrono::seconds(3));
  2392. }
  2393. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2394. if (!should_run_issue_2431_tests()) {
  2395. GTEST_SKIP()
  2396. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2397. }
  2398. std::atomic<bool> stop{false};
  2399. std::vector<std::thread> threads;
  2400. for (int t = 0; t < 8; ++t) {
  2401. threads.emplace_back([t, &stop] {
  2402. int i = 0;
  2403. while (!stop.load(std::memory_order_relaxed)) {
  2404. struct addrinfo hints;
  2405. memset(&hints, 0, sizeof(hints));
  2406. hints.ai_family = AF_UNSPEC;
  2407. hints.ai_socktype = SOCK_STREAM;
  2408. auto host = unique_unresolvable_host(t * 100000 + i++);
  2409. struct addrinfo *result = nullptr;
  2410. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2411. &result, /*timeout_sec=*/1);
  2412. if (rc == 0 && result) { freeaddrinfo(result); }
  2413. }
  2414. });
  2415. }
  2416. std::this_thread::sleep_for(std::chrono::seconds(8));
  2417. stop.store(true, std::memory_order_relaxed);
  2418. for (auto &th : threads) {
  2419. th.join();
  2420. }
  2421. std::this_thread::sleep_for(std::chrono::seconds(3));
  2422. }
  2423. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2424. if (!should_run_issue_2431_tests()) {
  2425. GTEST_SKIP()
  2426. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2427. }
  2428. std::atomic<bool> stop{false};
  2429. std::vector<std::thread> threads;
  2430. for (int t = 0; t < 8; ++t) {
  2431. threads.emplace_back([t, &stop] {
  2432. int i = 0;
  2433. while (!stop.load(std::memory_order_relaxed)) {
  2434. auto host = unique_unresolvable_host(t * 100000 + i++);
  2435. Client cli(host, 80);
  2436. cli.set_connection_timeout(1, 0);
  2437. cli.set_read_timeout(1, 0);
  2438. cli.set_write_timeout(1, 0);
  2439. (void)cli.Get("/");
  2440. }
  2441. });
  2442. }
  2443. std::this_thread::sleep_for(std::chrono::seconds(8));
  2444. stop.store(true, std::memory_order_relaxed);
  2445. for (auto &th : threads) {
  2446. th.join();
  2447. }
  2448. std::this_thread::sleep_for(std::chrono::seconds(3));
  2449. }
  2450. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2451. TEST(ConnectionErrorTest, InvalidHost) {
  2452. auto host = "-abcde.com";
  2453. #ifdef CPPHTTPLIB_SSL_ENABLED
  2454. auto port = 443;
  2455. SSLClient cli(host, port);
  2456. #else
  2457. auto port = 80;
  2458. Client cli(host, port);
  2459. #endif
  2460. cli.set_connection_timeout(std::chrono::seconds(2));
  2461. auto res = cli.Get("/");
  2462. ASSERT_TRUE(!res);
  2463. EXPECT_EQ(Error::Connection, res.error());
  2464. }
  2465. TEST(ConnectionErrorTest, InvalidHost2) {
  2466. auto host = "httpcan.org/";
  2467. #ifdef CPPHTTPLIB_SSL_ENABLED
  2468. SSLClient cli(host);
  2469. #else
  2470. Client cli(host);
  2471. #endif
  2472. cli.set_connection_timeout(std::chrono::seconds(2));
  2473. auto res = cli.Get("/");
  2474. ASSERT_TRUE(!res);
  2475. EXPECT_EQ(Error::Connection, res.error());
  2476. }
  2477. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2478. auto host = "httpcan.org/";
  2479. #ifdef CPPHTTPLIB_SSL_ENABLED
  2480. SSLClient cli(host);
  2481. #else
  2482. Client cli(host);
  2483. #endif
  2484. cli.set_connection_timeout(std::chrono::seconds(2));
  2485. auto res = cli.Get("/");
  2486. ASSERT_TRUE(!res);
  2487. stringstream s;
  2488. s << "error code: " << res.error();
  2489. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2490. }
  2491. TEST(ConnectionErrorTest, InvalidPort) {
  2492. auto host = "localhost";
  2493. auto port = 44380;
  2494. #ifdef CPPHTTPLIB_SSL_ENABLED
  2495. SSLClient cli(host, port);
  2496. #else
  2497. Client cli(host, port);
  2498. #endif
  2499. cli.set_connection_timeout(std::chrono::seconds(2));
  2500. auto res = cli.Get("/");
  2501. ASSERT_TRUE(!res);
  2502. EXPECT_TRUE(Error::Connection == res.error() ||
  2503. Error::ConnectionTimeout == res.error());
  2504. }
  2505. TEST(ConnectionErrorTest, Timeout_Online) {
  2506. auto host = "google.com";
  2507. #ifdef CPPHTTPLIB_SSL_ENABLED
  2508. auto port = 44380;
  2509. SSLClient cli(host, port);
  2510. #else
  2511. auto port = 8080;
  2512. Client cli(host, port);
  2513. #endif
  2514. cli.set_connection_timeout(std::chrono::seconds(2));
  2515. // only probe one address type so that the error reason
  2516. // correlates to the timed-out IPv4, not the unsupported
  2517. // IPv6 connection attempt
  2518. cli.set_address_family(AF_INET);
  2519. auto res = cli.Get("/");
  2520. ASSERT_TRUE(!res);
  2521. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2522. }
  2523. TEST(CancelTest, NoCancel_Online) {
  2524. auto host = "httpbingo.org";
  2525. auto path = std::string{"/range/32"};
  2526. #ifdef CPPHTTPLIB_SSL_ENABLED
  2527. auto port = 443;
  2528. SSLClient cli(host, port);
  2529. #else
  2530. auto port = 80;
  2531. Client cli(host, port);
  2532. #endif
  2533. cli.set_connection_timeout(std::chrono::seconds(5));
  2534. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2536. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. }
  2539. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2540. // Use /bytes with a large payload so that the DownloadProgress callback
  2541. // (which only fires for Content-Length responses) is invoked before the
  2542. // entire body is received, giving cancellation a chance to fire.
  2543. auto host = "httpbingo.org";
  2544. auto path = std::string{"/bytes/524288"};
  2545. #ifdef CPPHTTPLIB_SSL_ENABLED
  2546. auto port = 443;
  2547. SSLClient cli(host, port);
  2548. #else
  2549. auto port = 80;
  2550. Client cli(host, port);
  2551. #endif
  2552. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2553. cli.set_connection_timeout(std::chrono::seconds(5));
  2554. ASSERT_TRUE(!res);
  2555. EXPECT_EQ(Error::Canceled, res.error());
  2556. }
  2557. TEST(CancelTest, WithCancelLargePayload_Online) {
  2558. auto host = "httpbingo.org";
  2559. auto path = std::string{"/bytes/524288"};
  2560. #ifdef CPPHTTPLIB_SSL_ENABLED
  2561. auto port = 443;
  2562. SSLClient cli(host, port);
  2563. #else
  2564. auto port = 80;
  2565. Client cli(host, port);
  2566. #endif
  2567. cli.set_connection_timeout(std::chrono::seconds(5));
  2568. uint32_t count = 0;
  2569. auto res =
  2570. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2571. ASSERT_TRUE(!res);
  2572. EXPECT_EQ(Error::Canceled, res.error());
  2573. }
  2574. TEST(CancelTest, NoCancelPost) {
  2575. Server svr;
  2576. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2577. res.set_content("Hello World!", "text/plain");
  2578. });
  2579. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2580. auto se = detail::scope_exit([&] {
  2581. svr.stop();
  2582. thread.join();
  2583. ASSERT_FALSE(svr.is_running());
  2584. });
  2585. svr.wait_until_ready();
  2586. Client cli(HOST, PORT);
  2587. cli.set_connection_timeout(std::chrono::seconds(5));
  2588. auto res =
  2589. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2590. "application/json", [](uint64_t, uint64_t) { return true; });
  2591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2592. EXPECT_EQ("Hello World!", res->body);
  2593. EXPECT_EQ(StatusCode::OK_200, res->status);
  2594. }
  2595. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2596. Server svr;
  2597. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2598. res.set_content("Hello World!", "text/plain");
  2599. });
  2600. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2601. auto se = detail::scope_exit([&] {
  2602. svr.stop();
  2603. thread.join();
  2604. ASSERT_FALSE(svr.is_running());
  2605. });
  2606. svr.wait_until_ready();
  2607. Client cli(HOST, PORT);
  2608. cli.set_connection_timeout(std::chrono::seconds(5));
  2609. auto res =
  2610. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2611. "application/json", [](uint64_t, uint64_t) { return false; });
  2612. ASSERT_TRUE(!res);
  2613. EXPECT_EQ(Error::Canceled, res.error());
  2614. }
  2615. TEST(CancelTest, WithCancelLargePayloadPost) {
  2616. Server svr;
  2617. svr.set_payload_max_length(200 * 1024 * 1024);
  2618. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2619. res.set_content(LARGE_DATA, "text/plain");
  2620. });
  2621. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2622. auto se = detail::scope_exit([&] {
  2623. svr.stop();
  2624. thread.join();
  2625. ASSERT_FALSE(svr.is_running());
  2626. });
  2627. svr.wait_until_ready();
  2628. Client cli(HOST, PORT);
  2629. cli.set_payload_max_length(200 * 1024 * 1024);
  2630. cli.set_connection_timeout(std::chrono::seconds(5));
  2631. auto res =
  2632. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2633. "application/json", [](uint64_t, uint64_t) { return false; });
  2634. ASSERT_TRUE(!res);
  2635. EXPECT_EQ(Error::Canceled, res.error());
  2636. }
  2637. TEST(CancelTest, NoCancelPut) {
  2638. Server svr;
  2639. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2640. res.set_content("Hello World!", "text/plain");
  2641. });
  2642. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2643. auto se = detail::scope_exit([&] {
  2644. svr.stop();
  2645. thread.join();
  2646. ASSERT_FALSE(svr.is_running());
  2647. });
  2648. svr.wait_until_ready();
  2649. Client cli(HOST, PORT);
  2650. cli.set_connection_timeout(std::chrono::seconds(5));
  2651. auto res =
  2652. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2653. "application/json", [](uint64_t, uint64_t) { return true; });
  2654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2655. EXPECT_EQ("Hello World!", res->body);
  2656. EXPECT_EQ(StatusCode::OK_200, res->status);
  2657. }
  2658. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2659. Server svr;
  2660. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2661. res.set_content("Hello World!", "text/plain");
  2662. });
  2663. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2664. auto se = detail::scope_exit([&] {
  2665. svr.stop();
  2666. thread.join();
  2667. ASSERT_FALSE(svr.is_running());
  2668. });
  2669. svr.wait_until_ready();
  2670. Client cli(HOST, PORT);
  2671. cli.set_connection_timeout(std::chrono::seconds(5));
  2672. auto res =
  2673. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2674. "application/json", [](uint64_t, uint64_t) { return false; });
  2675. ASSERT_TRUE(!res);
  2676. EXPECT_EQ(Error::Canceled, res.error());
  2677. }
  2678. TEST(CancelTest, WithCancelLargePayloadPut) {
  2679. Server svr;
  2680. svr.set_payload_max_length(200 * 1024 * 1024);
  2681. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2682. res.set_content(LARGE_DATA, "text/plain");
  2683. });
  2684. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2685. auto se = detail::scope_exit([&] {
  2686. svr.stop();
  2687. thread.join();
  2688. ASSERT_FALSE(svr.is_running());
  2689. });
  2690. svr.wait_until_ready();
  2691. Client cli(HOST, PORT);
  2692. cli.set_payload_max_length(200 * 1024 * 1024);
  2693. cli.set_connection_timeout(std::chrono::seconds(5));
  2694. auto res =
  2695. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2696. "application/json", [](uint64_t, uint64_t) { return false; });
  2697. ASSERT_TRUE(!res);
  2698. EXPECT_EQ(Error::Canceled, res.error());
  2699. }
  2700. TEST(CancelTest, NoCancelPatch) {
  2701. Server svr;
  2702. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2703. res.set_content("Hello World!", "text/plain");
  2704. });
  2705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2706. auto se = detail::scope_exit([&] {
  2707. svr.stop();
  2708. thread.join();
  2709. ASSERT_FALSE(svr.is_running());
  2710. });
  2711. svr.wait_until_ready();
  2712. Client cli(HOST, PORT);
  2713. cli.set_connection_timeout(std::chrono::seconds(5));
  2714. auto res =
  2715. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2716. "application/json", [](uint64_t, uint64_t) { return true; });
  2717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2718. EXPECT_EQ("Hello World!", res->body);
  2719. EXPECT_EQ(StatusCode::OK_200, res->status);
  2720. }
  2721. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2722. Server svr;
  2723. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2724. res.set_content("Hello World!", "text/plain");
  2725. });
  2726. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2727. auto se = detail::scope_exit([&] {
  2728. svr.stop();
  2729. thread.join();
  2730. ASSERT_FALSE(svr.is_running());
  2731. });
  2732. svr.wait_until_ready();
  2733. Client cli(HOST, PORT);
  2734. cli.set_connection_timeout(std::chrono::seconds(5));
  2735. auto res =
  2736. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2737. "application/json", [](uint64_t, uint64_t) { return false; });
  2738. ASSERT_TRUE(!res);
  2739. EXPECT_EQ(Error::Canceled, res.error());
  2740. }
  2741. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2742. Server svr;
  2743. svr.set_payload_max_length(200 * 1024 * 1024);
  2744. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2745. res.set_content(LARGE_DATA, "text/plain");
  2746. });
  2747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2748. auto se = detail::scope_exit([&] {
  2749. svr.stop();
  2750. thread.join();
  2751. ASSERT_FALSE(svr.is_running());
  2752. });
  2753. svr.wait_until_ready();
  2754. Client cli(HOST, PORT);
  2755. cli.set_payload_max_length(200 * 1024 * 1024);
  2756. cli.set_connection_timeout(std::chrono::seconds(5));
  2757. auto res =
  2758. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2759. "application/json", [](uint64_t, uint64_t) { return false; });
  2760. ASSERT_TRUE(!res);
  2761. EXPECT_EQ(Error::Canceled, res.error());
  2762. }
  2763. TEST(CancelTest, NoCancelDelete) {
  2764. Server svr;
  2765. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2766. res.set_content("Hello World!", "text/plain");
  2767. });
  2768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2769. auto se = detail::scope_exit([&] {
  2770. svr.stop();
  2771. thread.join();
  2772. ASSERT_FALSE(svr.is_running());
  2773. });
  2774. svr.wait_until_ready();
  2775. Client cli(HOST, PORT);
  2776. cli.set_connection_timeout(std::chrono::seconds(5));
  2777. auto res =
  2778. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2779. "application/json", [](uint64_t, uint64_t) { return true; });
  2780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2781. EXPECT_EQ("Hello World!", res->body);
  2782. EXPECT_EQ(StatusCode::OK_200, res->status);
  2783. }
  2784. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2785. Server svr;
  2786. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2787. res.set_content("Hello World!", "text/plain");
  2788. });
  2789. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2790. auto se = detail::scope_exit([&] {
  2791. svr.stop();
  2792. thread.join();
  2793. ASSERT_FALSE(svr.is_running());
  2794. });
  2795. svr.wait_until_ready();
  2796. Client cli(HOST, PORT);
  2797. cli.set_connection_timeout(std::chrono::seconds(5));
  2798. auto res =
  2799. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2800. "application/json", [](uint64_t, uint64_t) { return false; });
  2801. ASSERT_TRUE(!res);
  2802. EXPECT_EQ(Error::Canceled, res.error());
  2803. }
  2804. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2805. Server svr;
  2806. svr.set_payload_max_length(200 * 1024 * 1024);
  2807. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2808. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  2819. cli.set_connection_timeout(std::chrono::seconds(5));
  2820. auto res =
  2821. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2822. "application/json", [](uint64_t, uint64_t) { return false; });
  2823. ASSERT_TRUE(!res);
  2824. EXPECT_EQ(Error::Canceled, res.error());
  2825. }
  2826. static std::string remove_whitespace(const std::string &input) {
  2827. std::string output;
  2828. output.reserve(input.size());
  2829. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2830. [](unsigned char c) { return !std::isspace(c); });
  2831. return output;
  2832. }
  2833. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2834. auto host = "httpbingo.org";
  2835. auto path = std::string{"/basic-auth/hello/world"};
  2836. #ifdef CPPHTTPLIB_SSL_ENABLED
  2837. auto port = 443;
  2838. SSLClient cli(host, port);
  2839. #else
  2840. auto port = 80;
  2841. Client cli(host, port);
  2842. #endif
  2843. {
  2844. auto res = cli.Get(path);
  2845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2846. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2847. }
  2848. {
  2849. auto res = cli.Get(
  2850. path, Headers{make_basic_authentication_header("hello", "world")});
  2851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2852. auto body = remove_whitespace(res->body);
  2853. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2854. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2855. EXPECT_EQ(StatusCode::OK_200, res->status);
  2856. }
  2857. {
  2858. cli.set_basic_auth("hello", "world");
  2859. auto res = cli.Get(path);
  2860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2861. auto body = remove_whitespace(res->body);
  2862. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2863. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2864. EXPECT_EQ(StatusCode::OK_200, res->status);
  2865. }
  2866. {
  2867. cli.set_basic_auth("hello", "bad");
  2868. auto res = cli.Get(path);
  2869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2870. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2871. }
  2872. {
  2873. cli.set_basic_auth("bad", "world");
  2874. auto res = cli.Get(path);
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2877. }
  2878. }
  2879. #ifdef CPPHTTPLIB_SSL_ENABLED
  2880. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2881. auto host = "httpbingo.org";
  2882. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2883. auto paths = std::vector<std::string>{
  2884. "/digest-auth/auth/hello/world/MD5",
  2885. "/digest-auth/auth/hello/world/SHA-256",
  2886. };
  2887. auto port = 443;
  2888. SSLClient cli(host, port);
  2889. {
  2890. auto res = cli.Get(unauth_path);
  2891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2892. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2893. }
  2894. {
  2895. cli.set_digest_auth("hello", "world");
  2896. for (const auto &path : paths) {
  2897. auto res = cli.Get(path.c_str());
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. auto body = remove_whitespace(res->body);
  2900. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2901. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2902. EXPECT_EQ(StatusCode::OK_200, res->status);
  2903. }
  2904. cli.set_digest_auth("hello", "bad");
  2905. for (const auto &path : paths) {
  2906. auto res = cli.Get(path.c_str());
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2909. }
  2910. }
  2911. }
  2912. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2913. // comma-separated list of challenges, and each challenge may itself carry a
  2914. // comma-separated auth-param list, so a server can legally offer Basic
  2915. // before Digest, either as two field lines or packed into one. Runs one 401
  2916. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2917. // value() joins them in receipt order) and checks that the retry carries a
  2918. // well-formed Digest Authorization header naming expected_realm.
  2919. static void
  2920. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2921. const std::string &expected_realm) {
  2922. std::atomic<int> hits{0};
  2923. Server svr;
  2924. svr.Get("/x", [&](const Request &req, Response &res) {
  2925. if (++hits == 1) {
  2926. res.status = StatusCode::Unauthorized_401;
  2927. for (const auto &challenge : challenges) {
  2928. res.set_header("WWW-Authenticate", challenge);
  2929. }
  2930. } else {
  2931. auto authorization = req.get_header_value("Authorization");
  2932. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2933. EXPECT_NE(std::string::npos,
  2934. authorization.find("realm=\"" + expected_realm + "\""));
  2935. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2936. res.set_content("ok", "text/plain");
  2937. }
  2938. });
  2939. auto port = svr.bind_to_any_port(HOST);
  2940. std::thread t([&]() { svr.listen_after_bind(); });
  2941. auto se = detail::scope_exit([&] {
  2942. svr.stop();
  2943. t.join();
  2944. });
  2945. svr.wait_until_ready();
  2946. Client cli(HOST, port);
  2947. cli.set_digest_auth("hello", "world");
  2948. auto res = cli.Get("/x");
  2949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2950. EXPECT_EQ(2, hits.load());
  2951. }
  2952. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2953. static const char *kDigestChallenge =
  2954. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2955. "algorithm=MD5";
  2956. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2957. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2958. "testrealm");
  2959. }
  2960. // Same challenge list with the schemes in the opposite order, to make sure
  2961. // the fix above didn't just special-case "Basic first".
  2962. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2963. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2964. "testrealm");
  2965. }
  2966. // A comma inside a quoted auth-param value must not be mistaken for the
  2967. // separator between two challenges (or two auth-params).
  2968. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2969. run_digest_challenge_list_test(
  2970. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2971. "algorithm=MD5"},
  2972. "test,realm");
  2973. }
  2974. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2975. // the params and leaves out the fragment.
  2976. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2977. Server svr;
  2978. std::string uri, target;
  2979. svr.Get("/a b", [&](const Request &req, Response &res) {
  2980. auto auth = req.get_header_value("Authorization");
  2981. if (auth.empty()) {
  2982. res.status = StatusCode::Unauthorized_401;
  2983. res.set_header("WWW-Authenticate",
  2984. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2985. return;
  2986. }
  2987. auto b = auth.find("uri=\"") + 5;
  2988. uri = auth.substr(b, auth.find('"', b) - b);
  2989. target = req.target;
  2990. });
  2991. auto port = svr.bind_to_any_port(HOST);
  2992. std::thread t([&]() { svr.listen_after_bind(); });
  2993. auto se = detail::scope_exit([&] {
  2994. svr.stop();
  2995. t.join();
  2996. });
  2997. svr.wait_until_ready();
  2998. Client cli(HOST, port);
  2999. cli.set_digest_auth("hello", "world");
  3000. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3002. EXPECT_EQ("/a%20b?x=1", target);
  3003. EXPECT_EQ(target, uri);
  3004. }
  3005. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3006. // make_digest_authentication_header() dereferences both unconditionally, so
  3007. // a server sending a challenge missing either one must not be treated as
  3008. // usable -- doing so used to crash the client with std::out_of_range.
  3009. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3010. Server svr;
  3011. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3012. res.status = StatusCode::Unauthorized_401;
  3013. res.set_header("WWW-Authenticate", challenge);
  3014. });
  3015. auto port = svr.bind_to_any_port(HOST);
  3016. std::thread t([&]() { svr.listen_after_bind(); });
  3017. auto se = detail::scope_exit([&] {
  3018. svr.stop();
  3019. t.join();
  3020. });
  3021. svr.wait_until_ready();
  3022. Client cli(HOST, port);
  3023. cli.set_digest_auth("hello", "world");
  3024. auto res = cli.Get("/x");
  3025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3026. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3027. }
  3028. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3029. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3030. }
  3031. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3032. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3033. }
  3034. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3035. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3036. }
  3037. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3038. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3039. // when storing the values, so the header builder has to re-escape them (and
  3040. // keep algorithm a bare token); otherwise the value breaks out of its
  3041. // quoted-string and injects extra auth-params into the client's Authorization.
  3042. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3043. std::atomic<int> hits{0};
  3044. std::string authorization;
  3045. Server svr;
  3046. svr.Get("/x", [&](const Request &req, Response &res) {
  3047. if (++hits == 1) {
  3048. res.status = StatusCode::Unauthorized_401;
  3049. // On the wire the quotes embedded in the values are backslash-escaped.
  3050. res.set_header("WWW-Authenticate",
  3051. "Digest realm=\"testrealm\", "
  3052. "nonce=\"n\\\"; injected=\\\"x\", "
  3053. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3054. } else {
  3055. authorization = req.get_header_value("Authorization");
  3056. res.set_content("ok", "text/plain");
  3057. }
  3058. });
  3059. auto port = svr.bind_to_any_port(HOST);
  3060. std::thread t([&]() { svr.listen_after_bind(); });
  3061. auto se = detail::scope_exit([&] {
  3062. svr.stop();
  3063. t.join();
  3064. });
  3065. svr.wait_until_ready();
  3066. Client cli(HOST, port);
  3067. cli.set_digest_auth("hello", "world");
  3068. auto res = cli.Get("/x");
  3069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3070. EXPECT_EQ(2, hits.load());
  3071. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3072. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3073. // inside its quoted-string rather than starting an "injected" auth-param.
  3074. EXPECT_NE(std::string::npos,
  3075. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3076. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3077. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3078. }
  3079. #endif
  3080. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3081. auto host = "google.com";
  3082. auto another_host = "example.com";
  3083. auto wrong_ip = "0.0.0.0";
  3084. #ifdef CPPHTTPLIB_SSL_ENABLED
  3085. SSLClient cli(host);
  3086. #else
  3087. Client cli(host);
  3088. #endif
  3089. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3090. auto res = cli.Get("/");
  3091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3092. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3093. }
  3094. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3095. auto host = "google.com";
  3096. auto wrong_ip = "0.0.0.0";
  3097. #ifdef CPPHTTPLIB_SSL_ENABLED
  3098. SSLClient cli(host);
  3099. #else
  3100. Client cli(host);
  3101. #endif
  3102. cli.set_hostname_addr_map({{host, wrong_ip}});
  3103. auto res = cli.Get("/");
  3104. ASSERT_TRUE(!res);
  3105. EXPECT_EQ(Error::Connection, res.error());
  3106. }
  3107. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3108. // A mapped value that is not an IP literal must be resolved. "localhost"
  3109. // resolves from the hosts file, so this test needs no external DNS.
  3110. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3111. auto host = "target.invalid";
  3112. Server svr;
  3113. std::string received_host;
  3114. svr.Get("/hi", [&](const Request &req, Response &res) {
  3115. received_host = req.get_header_value("Host");
  3116. res.set_content("Hello World!", "text/plain");
  3117. });
  3118. auto port = svr.bind_to_any_port(HOST);
  3119. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3120. auto se = detail::scope_exit([&] {
  3121. svr.stop();
  3122. thread.join();
  3123. ASSERT_FALSE(svr.is_running());
  3124. });
  3125. svr.wait_until_ready();
  3126. Client cli(host, port);
  3127. cli.set_hostname_addr_map({{host, HOST}});
  3128. auto res = cli.Get("/hi");
  3129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3130. EXPECT_EQ(StatusCode::OK_200, res->status);
  3131. // The mapping only redirects the connection; the identity stays host_.
  3132. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3133. }
  3134. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3135. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3136. auto host = "target.invalid";
  3137. Server svr;
  3138. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3139. res.set_content("Hello World!", "text/plain");
  3140. });
  3141. auto port = svr.bind_to_any_port("127.0.0.1");
  3142. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3143. auto se = detail::scope_exit([&] {
  3144. svr.stop();
  3145. thread.join();
  3146. ASSERT_FALSE(svr.is_running());
  3147. });
  3148. svr.wait_until_ready();
  3149. Client cli(host, port);
  3150. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3151. auto res = cli.Get("/hi");
  3152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. }
  3155. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3156. // An empty mapped value must leave host_ as the connection target. Without
  3157. // that guard the empty value would become the host argument, getaddrinfo
  3158. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3159. // loopback - silently connecting somewhere the caller never asked for.
  3160. // The server listens on loopback, so such a fallback would succeed and is
  3161. // therefore observable as a failure of this test.
  3162. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3163. Server svr;
  3164. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3165. res.set_content("Hello World!", "text/plain");
  3166. });
  3167. auto port = svr.bind_to_any_port(HOST);
  3168. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3169. auto se = detail::scope_exit([&] {
  3170. svr.stop();
  3171. thread.join();
  3172. ASSERT_FALSE(svr.is_running());
  3173. });
  3174. svr.wait_until_ready();
  3175. Client cli(blackhole, port);
  3176. cli.set_hostname_addr_map({{blackhole, ""}});
  3177. cli.set_connection_timeout(1);
  3178. auto res = cli.Get("/hi");
  3179. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3180. }
  3181. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3182. auto host = "httpbingo.org";
  3183. auto path = std::string{"/absolute-redirect/3"};
  3184. #ifdef CPPHTTPLIB_SSL_ENABLED
  3185. SSLClient cli(host);
  3186. #else
  3187. Client cli(host);
  3188. #endif
  3189. cli.set_follow_location(true);
  3190. auto res = cli.Get(path);
  3191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3192. EXPECT_EQ(StatusCode::OK_200, res->status);
  3193. }
  3194. TEST(RedirectTest, Redirect_Online) {
  3195. auto host = "httpbingo.org";
  3196. auto path = std::string{"/redirect/3"};
  3197. #ifdef CPPHTTPLIB_SSL_ENABLED
  3198. SSLClient cli(host);
  3199. #else
  3200. Client cli(host);
  3201. #endif
  3202. cli.set_follow_location(true);
  3203. auto res = cli.Get(path);
  3204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3205. EXPECT_EQ(StatusCode::OK_200, res->status);
  3206. }
  3207. TEST(RelativeRedirectTest, Redirect_Online) {
  3208. auto host = "httpbingo.org";
  3209. auto path = std::string{"/relative-redirect/3"};
  3210. #ifdef CPPHTTPLIB_SSL_ENABLED
  3211. SSLClient cli(host);
  3212. #else
  3213. Client cli(host);
  3214. #endif
  3215. cli.set_follow_location(true);
  3216. auto res = cli.Get(path);
  3217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3218. EXPECT_EQ(StatusCode::OK_200, res->status);
  3219. }
  3220. TEST(TooManyRedirectTest, Redirect_Online) {
  3221. auto host = "httpbingo.org";
  3222. auto path = std::string{"/redirect/21"};
  3223. #ifdef CPPHTTPLIB_SSL_ENABLED
  3224. SSLClient cli(host);
  3225. #else
  3226. Client cli(host);
  3227. #endif
  3228. cli.set_follow_location(true);
  3229. auto res = cli.Get(path);
  3230. ASSERT_TRUE(!res);
  3231. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3232. }
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. TEST(YahooRedirectTest, Redirect_Online) {
  3235. Client cli("yahoo.com");
  3236. auto res = cli.Get("/");
  3237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3238. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3239. cli.set_follow_location(true);
  3240. res = cli.Get("/");
  3241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3242. EXPECT_EQ(StatusCode::OK_200, res->status);
  3243. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3244. }
  3245. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3246. #define REDIR_HOST "httpbingo.org"
  3247. #define REDIR_PATH "/redirect-to"
  3248. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3249. SSLClient cli(REDIR_HOST);
  3250. cli.set_follow_location(true);
  3251. auto res =
  3252. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::OK_200, res->status);
  3255. }
  3256. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3257. SSLClient cli(REDIR_HOST);
  3258. cli.set_follow_location(true);
  3259. Params params;
  3260. params.emplace("url", "http://example.com");
  3261. params.emplace("status_code", "302");
  3262. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3264. EXPECT_EQ(StatusCode::OK_200, res->status);
  3265. }
  3266. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3267. SSLClient cli(REDIR_HOST);
  3268. cli.set_follow_location(true);
  3269. Params params;
  3270. params.emplace("url", "http://example.com");
  3271. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3273. EXPECT_EQ(StatusCode::OK_200, res->status);
  3274. }
  3275. TEST(UrlWithSpace, Redirect_Online) {
  3276. SSLClient cli("edge.forgecdn.net");
  3277. cli.set_follow_location(true);
  3278. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3282. }
  3283. #endif
  3284. #if !defined(_WIN32) && !defined(_WIN64)
  3285. TEST(ReceiveSignals, Signal) {
  3286. auto setupSignalHandlers = []() {
  3287. struct sigaction act;
  3288. sigemptyset(&act.sa_mask);
  3289. act.sa_flags = SA_SIGINFO;
  3290. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3291. switch (sig) {
  3292. case SIGINT:
  3293. default: break;
  3294. }
  3295. };
  3296. ::sigaction(SIGINT, &act, nullptr);
  3297. };
  3298. Server svr;
  3299. int port = 0;
  3300. auto thread = std::thread([&]() {
  3301. setupSignalHandlers();
  3302. port = svr.bind_to_any_port(HOST);
  3303. svr.listen_after_bind();
  3304. });
  3305. auto se = detail::scope_exit([&] {
  3306. svr.stop();
  3307. thread.join();
  3308. ASSERT_FALSE(svr.is_running());
  3309. });
  3310. svr.wait_until_ready();
  3311. ASSERT_TRUE(svr.is_running());
  3312. pthread_kill(thread.native_handle(), SIGINT);
  3313. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3314. ASSERT_TRUE(svr.is_running());
  3315. }
  3316. #endif
  3317. TEST(RedirectToDifferentPort, Redirect) {
  3318. Server svr1;
  3319. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3320. res.set_content("Hello World!", "text/plain");
  3321. });
  3322. int svr1_port = 0;
  3323. auto thread1 = std::thread([&]() {
  3324. svr1_port = svr1.bind_to_any_port(HOST);
  3325. svr1.listen_after_bind();
  3326. });
  3327. Server svr2;
  3328. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3329. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3330. });
  3331. int svr2_port = 0;
  3332. auto thread2 = std::thread([&]() {
  3333. svr2_port = svr2.bind_to_any_port(HOST);
  3334. svr2.listen_after_bind();
  3335. });
  3336. auto se = detail::scope_exit([&] {
  3337. svr2.stop();
  3338. thread2.join();
  3339. svr1.stop();
  3340. thread1.join();
  3341. ASSERT_FALSE(svr2.is_running());
  3342. ASSERT_FALSE(svr1.is_running());
  3343. });
  3344. svr1.wait_until_ready();
  3345. svr2.wait_until_ready();
  3346. Client cli("localhost", svr2_port);
  3347. cli.set_follow_location(true);
  3348. auto res = cli.Get("/2");
  3349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3350. EXPECT_EQ(StatusCode::OK_200, res->status);
  3351. EXPECT_EQ("Hello World!", res->body);
  3352. }
  3353. // GET /redir on one server redirects to /target on another port, so the
  3354. // client follows it with a new client.
  3355. static Result
  3356. GetThroughRedirectToDifferentPort(Server::Handler target,
  3357. const std::function<void(Client &)> &setup,
  3358. const Headers &headers = Headers()) {
  3359. Server target_svr;
  3360. target_svr.Get("/target", target);
  3361. int target_port = 0;
  3362. auto target_thread = std::thread([&]() {
  3363. target_port = target_svr.bind_to_any_port(HOST);
  3364. target_svr.listen_after_bind();
  3365. });
  3366. Server origin_svr;
  3367. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3368. res.set_redirect(
  3369. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3370. });
  3371. int origin_port = 0;
  3372. auto origin_thread = std::thread([&]() {
  3373. origin_port = origin_svr.bind_to_any_port(HOST);
  3374. origin_svr.listen_after_bind();
  3375. });
  3376. auto se = detail::scope_exit([&] {
  3377. origin_svr.stop();
  3378. origin_thread.join();
  3379. target_svr.stop();
  3380. target_thread.join();
  3381. });
  3382. target_svr.wait_until_ready();
  3383. origin_svr.wait_until_ready();
  3384. Client cli("localhost", origin_port);
  3385. cli.set_follow_location(true);
  3386. setup(cli);
  3387. return cli.Get("/redir", headers);
  3388. }
  3389. static void
  3390. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3391. std::string captured_authorization;
  3392. auto result = GetThroughRedirectToDifferentPort(
  3393. [&](const Request &req, Response &res) {
  3394. captured_authorization = req.get_header_value("Authorization");
  3395. res.set_content("OK", "text/plain");
  3396. },
  3397. set_auth);
  3398. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3399. EXPECT_EQ(StatusCode::OK_200, result->status);
  3400. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3401. EXPECT_TRUE(captured_authorization.empty());
  3402. }
  3403. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3404. TestDoNotForwardCredentialsOnRedirect(
  3405. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3406. }
  3407. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3408. TestDoNotForwardCredentialsOnRedirect(
  3409. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3410. }
  3411. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3412. std::string captured_cookie;
  3413. auto result = GetThroughRedirectToDifferentPort(
  3414. [&](const Request &req, Response &res) {
  3415. captured_cookie = req.get_header_value("Cookie");
  3416. res.set_content("OK", "text/plain");
  3417. },
  3418. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3419. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3420. EXPECT_EQ(StatusCode::OK_200, result->status);
  3421. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3422. EXPECT_TRUE(captured_cookie.empty());
  3423. }
  3424. TEST(RedirectToSamePort, ForwardCookie) {
  3425. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3426. // header so that ordinary session flows keep working.
  3427. Server svr;
  3428. std::string captured_cookie;
  3429. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3430. res.set_redirect("/target", 302);
  3431. });
  3432. svr.Get("/target", [&](const Request &req, Response &res) {
  3433. captured_cookie = req.get_header_value("Cookie");
  3434. res.set_content("OK", "text/plain");
  3435. });
  3436. auto port = svr.bind_to_any_port(HOST);
  3437. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3438. auto se = detail::scope_exit([&] {
  3439. svr.stop();
  3440. thread.join();
  3441. ASSERT_FALSE(svr.is_running());
  3442. });
  3443. svr.wait_until_ready();
  3444. Client cli(HOST, port);
  3445. cli.set_follow_location(true);
  3446. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3447. auto res = cli.Get("/redir", headers);
  3448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3449. EXPECT_EQ(StatusCode::OK_200, res->status);
  3450. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3451. }
  3452. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3453. std::string authorization;
  3454. std::string trace_id;
  3455. auto result = GetThroughRedirectToDifferentPort(
  3456. [&](const Request &req, Response &res) {
  3457. authorization = req.get_header_value("Authorization");
  3458. trace_id = req.get_header_value("X-Trace-Id");
  3459. res.set_content("OK", "text/plain");
  3460. },
  3461. [](Client &cli) {
  3462. cli.set_default_headers(
  3463. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3464. });
  3465. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3466. EXPECT_EQ(StatusCode::OK_200, result->status);
  3467. // Like a header given with the request, a default one goes along unless it
  3468. // carries credentials (RFC 9110 15.4).
  3469. EXPECT_TRUE(authorization.empty());
  3470. EXPECT_EQ("42", trace_id);
  3471. }
  3472. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3473. auto result = GetThroughRedirectToDifferentPort(
  3474. [](const Request &, Response &res) {
  3475. res.set_content(std::string(2048, 'x'), "text/plain");
  3476. },
  3477. [](Client &cli) { cli.set_payload_max_length(1024); });
  3478. EXPECT_FALSE(result);
  3479. }
  3480. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3481. auto result = GetThroughRedirectToDifferentPort(
  3482. [](const Request &req, Response &res) {
  3483. // Answer after a second, or once the client gives up.
  3484. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3485. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3486. }
  3487. res.set_content("late", "text/plain");
  3488. },
  3489. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3490. ASSERT_FALSE(result);
  3491. EXPECT_EQ(Error::Read, result.error());
  3492. }
  3493. #ifdef CPPHTTPLIB_SSL_ENABLED
  3494. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3495. auto result = GetThroughRedirectToDifferentPort(
  3496. [](const Request &, Response &res) {
  3497. res.status = StatusCode::Unauthorized_401;
  3498. res.set_header("WWW-Authenticate",
  3499. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3500. },
  3501. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3502. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3503. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3504. }
  3505. #endif
  3506. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3507. Server svr;
  3508. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3509. // Port number that overflows int — should not crash
  3510. res.set_redirect("http://localhost:99999999999999999999/target");
  3511. });
  3512. auto port = svr.bind_to_any_port(HOST);
  3513. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3514. auto se = detail::scope_exit([&] {
  3515. svr.stop();
  3516. thread.join();
  3517. ASSERT_FALSE(svr.is_running());
  3518. });
  3519. svr.wait_until_ready();
  3520. Client cli(HOST, port);
  3521. cli.set_follow_location(true);
  3522. auto res = cli.Get("/redir");
  3523. // Should fail gracefully, not crash (no valid response due to bad port)
  3524. EXPECT_FALSE(res);
  3525. }
  3526. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3527. Server svr;
  3528. auto port = svr.bind_to_any_port(HOST);
  3529. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3530. // The server's own port followed by junk must not be followed
  3531. res.set_redirect("http://" + std::string(HOST) + ":" +
  3532. std::to_string(port) + "junk/target");
  3533. });
  3534. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3535. res.set_content("target", "text/plain");
  3536. });
  3537. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3538. auto se = detail::scope_exit([&] {
  3539. svr.stop();
  3540. thread.join();
  3541. ASSERT_FALSE(svr.is_running());
  3542. });
  3543. svr.wait_until_ready();
  3544. Client cli(HOST, port);
  3545. cli.set_follow_location(true);
  3546. auto res = cli.Get("/redir");
  3547. EXPECT_FALSE(res);
  3548. }
  3549. TEST(RedirectFromPageWithContent, Redirect) {
  3550. Server svr;
  3551. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3552. res.set_content("___", "text/plain");
  3553. res.set_redirect("/2");
  3554. });
  3555. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3556. res.set_content("Hello World!", "text/plain");
  3557. });
  3558. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3559. auto se = detail::scope_exit([&] {
  3560. svr.stop();
  3561. th.join();
  3562. ASSERT_FALSE(svr.is_running());
  3563. });
  3564. svr.wait_until_ready();
  3565. {
  3566. Client cli("localhost", PORT);
  3567. cli.set_follow_location(true);
  3568. std::string body;
  3569. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3570. body.append(data, data_length);
  3571. return true;
  3572. });
  3573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3574. EXPECT_EQ(StatusCode::OK_200, res->status);
  3575. EXPECT_EQ("Hello World!", body);
  3576. }
  3577. {
  3578. Client cli("localhost", PORT);
  3579. std::string body;
  3580. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3581. body.append(data, data_length);
  3582. return true;
  3583. });
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ(StatusCode::Found_302, res->status);
  3586. EXPECT_EQ("___", body);
  3587. }
  3588. }
  3589. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3590. Server svr;
  3591. auto port_str = std::to_string(PORT);
  3592. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3593. auto expected_host = "[::1]:" + port_str;
  3594. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3595. res.set_content("___", "text/plain");
  3596. // res.set_redirect("/2");
  3597. res.set_redirect(redirect_url);
  3598. });
  3599. svr.Get("/2", [&](const Request &req, Response &res) {
  3600. auto host_header = req.headers.find("Host");
  3601. ASSERT_TRUE(host_header != req.headers.end());
  3602. EXPECT_EQ(expected_host, host_header->second);
  3603. res.set_content("Hello World!", "text/plain");
  3604. });
  3605. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3606. auto se = detail::scope_exit([&] {
  3607. svr.stop();
  3608. th.join();
  3609. ASSERT_FALSE(svr.is_running());
  3610. });
  3611. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3612. // actually starts anything, so the condition !svr.is_running() will
  3613. // always remain true, and the loop never stops.
  3614. // This basically counts how many milliseconds have passed since the
  3615. // call to svr.listen(), and if after 5 seconds nothing started yet
  3616. // aborts the test.
  3617. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3618. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3619. ASSERT_LT(milliseconds, 5000U);
  3620. }
  3621. {
  3622. Client cli("::1", PORT);
  3623. cli.set_follow_location(true);
  3624. std::string body;
  3625. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3626. body.append(data, data_length);
  3627. return true;
  3628. });
  3629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3630. EXPECT_EQ(StatusCode::OK_200, res->status);
  3631. EXPECT_EQ("Hello World!", body);
  3632. }
  3633. {
  3634. Client cli("::1", PORT);
  3635. std::string body;
  3636. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3637. body.append(data, data_length);
  3638. return true;
  3639. });
  3640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3641. EXPECT_EQ(StatusCode::Found_302, res->status);
  3642. EXPECT_EQ("___", body);
  3643. }
  3644. }
  3645. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3646. Server svr;
  3647. svr.Get("/foo", [](const Request &req, Response &res) {
  3648. auto a = req.params.find("a");
  3649. if (a != req.params.end()) {
  3650. res.set_content((*a).second, "text/plain");
  3651. res.status = StatusCode::OK_200;
  3652. } else {
  3653. res.status = StatusCode::BadRequest_400;
  3654. }
  3655. });
  3656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3657. auto se = detail::scope_exit([&] {
  3658. svr.stop();
  3659. thread.join();
  3660. ASSERT_FALSE(svr.is_running());
  3661. });
  3662. svr.wait_until_ready();
  3663. {
  3664. Client cli(HOST, PORT);
  3665. cli.set_path_encode(false);
  3666. auto res = cli.Get("/foo?a=explicitly+encoded");
  3667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3668. EXPECT_EQ(StatusCode::OK_200, res->status);
  3669. // This expects it back with a space, as the `+` won't have been
  3670. // url-encoded, and server-side the params get decoded turning `+`
  3671. // into spaces.
  3672. EXPECT_EQ("explicitly encoded", res->body);
  3673. }
  3674. }
  3675. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3676. // When path encoding is disabled the client must transmit the supplied
  3677. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3678. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3679. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3680. // than a space (0x20). Assert on the raw wire target to catch this.
  3681. Server svr;
  3682. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3683. svr.Get("/foo", [&](const Request &req, Response &res) {
  3684. EXPECT_EQ(expected_target, req.target);
  3685. res.status = StatusCode::OK_200;
  3686. });
  3687. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3688. auto se = detail::scope_exit([&] {
  3689. svr.stop();
  3690. thread.join();
  3691. ASSERT_FALSE(svr.is_running());
  3692. });
  3693. svr.wait_until_ready();
  3694. {
  3695. Client cli(HOST, PORT);
  3696. cli.set_path_encode(false);
  3697. auto res = cli.Get(expected_target.c_str());
  3698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3699. EXPECT_EQ(StatusCode::OK_200, res->status);
  3700. }
  3701. }
  3702. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3703. // `open_stream()` used to skip the path encoding that the buffered send
  3704. // path applies, so the same `path` produced different bytes in the request
  3705. // line depending on which API was used. Assert the two agree.
  3706. Server svr;
  3707. std::string target;
  3708. svr.Get(".*", [&](const Request &req, Response &res) {
  3709. target = req.target;
  3710. res.status = StatusCode::OK_200;
  3711. });
  3712. auto port = svr.bind_to_any_port(HOST);
  3713. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3714. auto se = detail::scope_exit([&] {
  3715. svr.stop();
  3716. thread.join();
  3717. ASSERT_FALSE(svr.is_running());
  3718. });
  3719. svr.wait_until_ready();
  3720. struct {
  3721. const char *path;
  3722. const char *expected;
  3723. } cases[] = {
  3724. {"/a b?x=1", "/a%20b?x=1"},
  3725. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3726. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3727. };
  3728. for (const auto &c : cases) {
  3729. Client cli(HOST, port);
  3730. target.clear();
  3731. auto res = cli.Get(c.path);
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3734. auto buffered_target = target;
  3735. target.clear();
  3736. auto handle = cli.open_stream("GET", c.path);
  3737. EXPECT_TRUE(handle.is_valid())
  3738. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3739. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3740. }
  3741. }
  3742. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3743. // The `set_path_encode(false)` contract — transmit the supplied target
  3744. // verbatim — must hold for the streaming API too.
  3745. Server svr;
  3746. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3747. std::string target;
  3748. svr.Get("/foo", [&](const Request &req, Response &res) {
  3749. target = req.target;
  3750. res.status = StatusCode::OK_200;
  3751. });
  3752. auto port = svr.bind_to_any_port(HOST);
  3753. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3754. auto se = detail::scope_exit([&] {
  3755. svr.stop();
  3756. thread.join();
  3757. ASSERT_FALSE(svr.is_running());
  3758. });
  3759. svr.wait_until_ready();
  3760. {
  3761. Client cli(HOST, port);
  3762. cli.set_path_encode(false);
  3763. auto handle = cli.open_stream("GET", expected_target);
  3764. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3765. EXPECT_EQ(expected_target, target);
  3766. }
  3767. }
  3768. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3769. // With path encoding enabled a CR/LF in the target is percent-encoded
  3770. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3771. // write_request_line still backstops `set_path_encode(false)`, which is
  3772. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3773. Server svr;
  3774. // Captured before routing: the decoded path contains a newline, which a
  3775. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3776. std::string target;
  3777. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3778. target = req.target;
  3779. res.status = StatusCode::OK_200;
  3780. return Server::HandlerResponse::Handled;
  3781. });
  3782. auto port = svr.bind_to_any_port(HOST);
  3783. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3784. auto se = detail::scope_exit([&] {
  3785. svr.stop();
  3786. thread.join();
  3787. ASSERT_FALSE(svr.is_running());
  3788. });
  3789. svr.wait_until_ready();
  3790. {
  3791. Client cli(HOST, port);
  3792. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3793. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3794. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3795. }
  3796. }
  3797. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3798. // Every control character is percent-encoded, not just CR/LF, so the target
  3799. // passes the request-target check in write_request_line.
  3800. Server svr;
  3801. std::string target;
  3802. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3803. target = req.target;
  3804. res.status = StatusCode::OK_200;
  3805. return Server::HandlerResponse::Handled;
  3806. });
  3807. auto port = svr.bind_to_any_port(HOST);
  3808. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3809. auto se = detail::scope_exit([&] {
  3810. svr.stop();
  3811. thread.join();
  3812. ASSERT_FALSE(svr.is_running());
  3813. });
  3814. svr.wait_until_ready();
  3815. {
  3816. Client cli(HOST, port);
  3817. auto res = cli.Get("/a\tb\x1b\x7f");
  3818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3819. EXPECT_EQ("/a%09b%1B%7F", target);
  3820. }
  3821. }
  3822. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3823. // Nothing may reach the wire: a raw CR/LF target would split the request
  3824. // line and inject headers.
  3825. Server svr;
  3826. // Pre-routing so that "not called" means nothing reached the server at all,
  3827. // rather than merely failing to match a handler pattern.
  3828. auto handler_called = false;
  3829. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3830. handler_called = true;
  3831. res.status = StatusCode::OK_200;
  3832. return Server::HandlerResponse::Handled;
  3833. });
  3834. auto port = svr.bind_to_any_port(HOST);
  3835. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3836. auto se = detail::scope_exit([&] {
  3837. svr.stop();
  3838. thread.join();
  3839. ASSERT_FALSE(svr.is_running());
  3840. });
  3841. svr.wait_until_ready();
  3842. {
  3843. Client cli(HOST, port);
  3844. cli.set_path_encode(false);
  3845. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3846. EXPECT_FALSE(handle.is_valid());
  3847. EXPECT_EQ(Error::Write, handle.error);
  3848. EXPECT_FALSE(handler_called);
  3849. }
  3850. }
  3851. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3852. // Which of the two branches runs is decided by whether the query component
  3853. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3854. // an empty query and must still fall back to building one from
  3855. // `req.params`, while a non-empty query must win over `req.params`.
  3856. Server svr;
  3857. std::string target;
  3858. svr.Get("/foo", [&](const Request &req, Response &res) {
  3859. target = req.target;
  3860. res.status = StatusCode::OK_200;
  3861. });
  3862. auto port = svr.bind_to_any_port(HOST);
  3863. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3864. auto se = detail::scope_exit([&] {
  3865. svr.stop();
  3866. thread.join();
  3867. ASSERT_FALSE(svr.is_running());
  3868. });
  3869. svr.wait_until_ready();
  3870. {
  3871. // Trailing `?` -> empty query component -> `req.params` is used.
  3872. Client cli(HOST, port);
  3873. Request req;
  3874. req.method = "GET";
  3875. req.path = "/foo?";
  3876. req.params.emplace("a", "1");
  3877. target.clear();
  3878. auto res = cli.send(req);
  3879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3880. EXPECT_EQ("/foo?a=1", target);
  3881. }
  3882. {
  3883. // Non-empty query in `req.path` -> `req.params` is not appended.
  3884. Client cli(HOST, port);
  3885. Request req;
  3886. req.method = "GET";
  3887. req.path = "/foo?b=2";
  3888. req.params.emplace("a", "1");
  3889. target.clear();
  3890. auto res = cli.send(req);
  3891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3892. EXPECT_EQ("/foo?b=2", target);
  3893. }
  3894. }
  3895. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3896. Server svr;
  3897. svr.Get("/", [](const Request &req, Response &) {
  3898. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3899. });
  3900. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3901. auto se = detail::scope_exit([&] {
  3902. svr.stop();
  3903. thread.join();
  3904. ASSERT_FALSE(svr.is_running());
  3905. });
  3906. svr.wait_until_ready();
  3907. {
  3908. Client cli(HOST, PORT);
  3909. cli.set_path_encode(false);
  3910. auto res = cli.Get("/?something=%0A");
  3911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3912. EXPECT_EQ(StatusCode::OK_200, res->status);
  3913. }
  3914. }
  3915. TEST(BindServerTest, BindDualStack) {
  3916. Server svr;
  3917. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3918. res.set_content("Hello World!", "text/plain");
  3919. });
  3920. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3921. auto se = detail::scope_exit([&] {
  3922. svr.stop();
  3923. thread.join();
  3924. ASSERT_FALSE(svr.is_running());
  3925. });
  3926. svr.wait_until_ready();
  3927. {
  3928. Client cli("127.0.0.1", PORT);
  3929. auto res = cli.Get("/1");
  3930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3931. EXPECT_EQ(StatusCode::OK_200, res->status);
  3932. EXPECT_EQ("Hello World!", res->body);
  3933. }
  3934. {
  3935. Client cli("::1", PORT);
  3936. auto res = cli.Get("/1");
  3937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3938. EXPECT_EQ(StatusCode::OK_200, res->status);
  3939. EXPECT_EQ("Hello World!", res->body);
  3940. }
  3941. }
  3942. TEST(BindServerTest, BindAndListenSeparately) {
  3943. Server svr;
  3944. int port = svr.bind_to_any_port("0.0.0.0");
  3945. ASSERT_TRUE(svr.is_valid());
  3946. ASSERT_TRUE(port > 0);
  3947. svr.stop();
  3948. }
  3949. // Reports whether anything is still listening on a loopback port. A plain
  3950. // connect() is used instead of a Client request because a socket left bound by
  3951. // mistake accepts the connection into its backlog and never answers, which
  3952. // would hang the test instead of failing it.
  3953. static bool is_loopback_port_accepting(int port) {
  3954. sockaddr_in addr{};
  3955. addr.sin_family = AF_INET;
  3956. addr.sin_port = htons(static_cast<uint16_t>(port));
  3957. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3958. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3959. EXPECT_NE(sock, INVALID_SOCKET);
  3960. if (sock == INVALID_SOCKET) { return false; }
  3961. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3962. static_cast<socklen_t>(sizeof(addr)));
  3963. detail::close_socket(sock);
  3964. return ret == 0;
  3965. }
  3966. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3967. Server svr;
  3968. auto port = svr.bind_to_any_port("127.0.0.1");
  3969. ASSERT_TRUE(port > 0);
  3970. svr.stop();
  3971. // bind_to_any_port() already called listen(2), so until stop() closed the
  3972. // descriptor the port kept accepting connections into the backlog. ASSERT
  3973. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3974. // below blocks forever in the accept loop.
  3975. ASSERT_FALSE(is_loopback_port_accepting(port));
  3976. // Nothing is left to accept on, so listen_after_bind() must report failure
  3977. // instead of returning success without ever serving.
  3978. EXPECT_FALSE(svr.listen_after_bind());
  3979. // The failed listen marks the server decommissioned, so a waiter returns
  3980. // instead of spinning forever.
  3981. svr.wait_until_ready();
  3982. }
  3983. #ifdef CPPHTTPLIB_SSL_ENABLED
  3984. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3985. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3986. CLIENT_CA_CERT_DIR);
  3987. int port = svr.bind_to_any_port("0.0.0.0");
  3988. ASSERT_TRUE(svr.is_valid());
  3989. ASSERT_TRUE(port > 0);
  3990. svr.stop();
  3991. }
  3992. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3993. // or a rejected CustomRoute() registration would not stop the server binding.
  3994. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3996. CLIENT_CA_CERT_DIR);
  3997. ASSERT_TRUE(svr.is_valid());
  3998. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3999. EXPECT_FALSE(svr.is_valid());
  4000. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4001. }
  4002. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4003. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4004. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4005. int port = svr.bind_to_any_port("0.0.0.0");
  4006. ASSERT_TRUE(svr.is_valid());
  4007. ASSERT_TRUE(port > 0);
  4008. svr.stop();
  4009. }
  4010. TEST(BindServerTest, UpdateCertsPem) {
  4011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4012. int port = svr.bind_to_any_port("0.0.0.0");
  4013. ASSERT_TRUE(svr.is_valid());
  4014. ASSERT_TRUE(port > 0);
  4015. // Read PEM files
  4016. std::string cert_pem, key_pem, ca_pem;
  4017. read_file(SERVER_CERT_FILE, cert_pem);
  4018. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4019. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4020. // Update server certificates using PEM API
  4021. ASSERT_TRUE(
  4022. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4023. ASSERT_TRUE(svr.is_valid());
  4024. svr.stop();
  4025. }
  4026. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4027. // Start server with client CA (enables client auth)
  4028. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4029. ASSERT_TRUE(svr.is_valid());
  4030. bool handler_called = false;
  4031. svr.Get("/test", [&](const Request &req, Response &res) {
  4032. handler_called = true;
  4033. // Verify client certificate is present
  4034. auto cert = req.peer_cert();
  4035. EXPECT_TRUE(static_cast<bool>(cert));
  4036. res.set_content("ok", "text/plain");
  4037. });
  4038. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4039. auto se = detail::scope_exit([&] {
  4040. svr.stop();
  4041. t.join();
  4042. ASSERT_FALSE(svr.is_running());
  4043. });
  4044. svr.wait_until_ready();
  4045. // Read PEM files
  4046. std::string cert_pem, key_pem, ca_pem;
  4047. read_file(SERVER_CERT_FILE, cert_pem);
  4048. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4049. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4050. // Update server certificates and client CA using PEM API while server running
  4051. ASSERT_TRUE(
  4052. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4053. // Connect with client certificate
  4054. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4055. cli.enable_server_certificate_verification(false);
  4056. cli.set_connection_timeout(30);
  4057. auto res = cli.Get("/test");
  4058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4059. ASSERT_EQ(StatusCode::OK_200, res->status);
  4060. ASSERT_TRUE(handler_called);
  4061. EXPECT_EQ("ok", res->body);
  4062. }
  4063. // Puts a CA that did not sign the client's certificate in the old one's place.
  4064. static bool replace_client_ca(SSLServer &svr) {
  4065. std::string cert_pem, key_pem, ca_pem;
  4066. read_file(SERVER_CERT_FILE, cert_pem);
  4067. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4068. read_file(SERVER_CERT2_FILE, ca_pem);
  4069. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4070. ca_pem.c_str());
  4071. }
  4072. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4074. ASSERT_TRUE(svr.is_valid());
  4075. svr.Get("/test", [](const Request &, Response &res) {
  4076. res.set_content("ok", "text/plain");
  4077. });
  4078. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4079. auto se = detail::scope_exit([&] {
  4080. svr.stop();
  4081. t.join();
  4082. ASSERT_FALSE(svr.is_running());
  4083. });
  4084. svr.wait_until_ready();
  4085. auto get = [] {
  4086. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4087. cli.enable_server_certificate_verification(false);
  4088. return cli.Get("/test");
  4089. };
  4090. ASSERT_TRUE(get());
  4091. ASSERT_TRUE(replace_client_ca(svr));
  4092. EXPECT_FALSE(get());
  4093. }
  4094. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4095. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4097. ASSERT_TRUE(svr.is_valid());
  4098. tls::set_verify_callback(svr.tls_context(),
  4099. [](const tls::VerifyContext &) -> bool {
  4100. throw std::runtime_error("verify");
  4101. });
  4102. svr.Get("/test", [](const Request &, Response &res) {
  4103. res.set_content("ok", "text/plain");
  4104. });
  4105. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4106. auto se = detail::scope_exit([&] {
  4107. svr.stop();
  4108. t.join();
  4109. ASSERT_FALSE(svr.is_running());
  4110. });
  4111. svr.wait_until_ready();
  4112. auto get = [] {
  4113. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4114. cli.enable_server_certificate_verification(false);
  4115. return cli.Get("/test");
  4116. };
  4117. EXPECT_FALSE(get());
  4118. // The handshake is over, so an update does not wait for it.
  4119. std::string cert_pem, key_pem;
  4120. read_file(SERVER_CERT_FILE, cert_pem);
  4121. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4122. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4123. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4124. return v.preverify_ok;
  4125. });
  4126. auto res = get();
  4127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4128. EXPECT_EQ("ok", res->body);
  4129. }
  4130. #endif
  4131. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4132. // Sends each request over a new connection with a client certificate,
  4133. // resuming the session of the one before when there is one.
  4134. class ResumingClient {
  4135. public:
  4136. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4137. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4138. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4139. SSL_FILETYPE_PEM);
  4140. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4141. // callback, not through SSL_get1_session().
  4142. SSL_CTX_set_app_data(ctx_, this);
  4143. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4144. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4145. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4146. auto self = static_cast<ResumingClient *>(
  4147. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4148. SSL_SESSION_free(self->session_);
  4149. self->session_ = session;
  4150. return 1; // Keeps the reference
  4151. });
  4152. }
  4153. ~ResumingClient() {
  4154. SSL_SESSION_free(session_);
  4155. SSL_CTX_free(ctx_);
  4156. }
  4157. // Tells whether the request was answered.
  4158. bool get() {
  4159. auto error = Error::Success;
  4160. auto sock = detail::create_client_socket(
  4161. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4162. /*connection_timeout_sec=*/5, 0,
  4163. /*read_timeout_sec=*/5, 0,
  4164. /*write_timeout_sec=*/5, 0, std::string(), error);
  4165. if (sock == INVALID_SOCKET) { return false; }
  4166. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4167. auto ssl = SSL_new(ctx_);
  4168. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4169. SSL_set_fd(ssl, static_cast<int>(sock));
  4170. if (session_) { SSL_set_session(ssl, session_); }
  4171. if (SSL_connect(ssl) != 1) { return false; }
  4172. reused_ = SSL_session_reused(ssl) == 1;
  4173. // Reading the response also takes in a TLS 1.3 session ticket.
  4174. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4175. "Connection: close\r\n\r\n";
  4176. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4177. std::string res;
  4178. char buf[256];
  4179. int n;
  4180. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4181. res.append(buf, static_cast<size_t>(n));
  4182. }
  4183. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4184. SSL_shutdown(ssl);
  4185. return res.find("200 OK") != std::string::npos;
  4186. }
  4187. // Whether the last connection resumed a session
  4188. bool reused() const { return reused_; }
  4189. private:
  4190. SSL_CTX *ctx_;
  4191. SSL_SESSION *session_ = nullptr;
  4192. bool reused_ = false;
  4193. };
  4194. // A client that resumes its session gets through, but not once the client CA
  4195. // has changed, as a resumed session does not show the certificate again.
  4196. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4198. ASSERT_TRUE(svr.is_valid());
  4199. svr.Get("/test", [](const Request &, Response &res) {
  4200. res.set_content("ok", "text/plain");
  4201. });
  4202. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4203. auto se = detail::scope_exit([&] {
  4204. svr.stop();
  4205. t.join();
  4206. ASSERT_FALSE(svr.is_running());
  4207. });
  4208. svr.wait_until_ready();
  4209. ResumingClient cli;
  4210. ASSERT_TRUE(cli.get());
  4211. ASSERT_TRUE(cli.get());
  4212. EXPECT_TRUE(cli.reused());
  4213. ASSERT_TRUE(replace_client_ca(svr));
  4214. EXPECT_FALSE(cli.get());
  4215. }
  4216. // A resumed session does not show the certificate again, so the server does
  4217. // not resume one with a verify callback to run on it.
  4218. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4219. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4220. ASSERT_TRUE(svr.is_valid());
  4221. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4222. return v.preverify_ok;
  4223. });
  4224. svr.Get("/test", [](const Request &, Response &res) {
  4225. res.set_content("ok", "text/plain");
  4226. });
  4227. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4228. auto se = detail::scope_exit([&] {
  4229. svr.stop();
  4230. t.join();
  4231. ASSERT_FALSE(svr.is_running());
  4232. });
  4233. svr.wait_until_ready();
  4234. ResumingClient cli;
  4235. ASSERT_TRUE(cli.get());
  4236. ASSERT_TRUE(cli.get());
  4237. EXPECT_FALSE(cli.reused());
  4238. }
  4239. #endif
  4240. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4241. // wolfSSL shares its session cache between contexts, so a resumed session
  4242. // could carry a client certificate checked against another server's CA, or
  4243. // against a client CA since replaced.
  4244. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4246. ASSERT_TRUE(svr.is_valid());
  4247. // Trusts a CA that did not sign the client's certificate.
  4248. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4249. ASSERT_TRUE(other.is_valid());
  4250. for (auto s : {&svr, &other}) {
  4251. s->Get("/test", [](const Request &, Response &res) {
  4252. res.set_content("ok", "text/plain");
  4253. });
  4254. }
  4255. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4256. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4257. auto se = detail::scope_exit([&] {
  4258. other.stop();
  4259. svr.stop();
  4260. t2.join();
  4261. t.join();
  4262. });
  4263. svr.wait_until_ready();
  4264. other.wait_until_ready();
  4265. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4266. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4267. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4268. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4269. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4270. ASSERT_EQ(WOLFSSL_SUCCESS,
  4271. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4272. WOLFSSL_FILETYPE_PEM));
  4273. WOLFSSL_SESSION *session = nullptr;
  4274. auto session_se = detail::scope_exit([&] {
  4275. if (session) { wolfSSL_SESSION_free(session); }
  4276. });
  4277. // A request over a new connection, resuming `session` when there is one and
  4278. // keeping the connection's own in its place. Tells whether it was answered.
  4279. auto get = [&](int port) {
  4280. auto error = Error::Success;
  4281. auto sock = detail::create_client_socket(
  4282. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4283. /*connection_timeout_sec=*/5, 0,
  4284. /*read_timeout_sec=*/5, 0,
  4285. /*write_timeout_sec=*/5, 0, std::string(), error);
  4286. if (sock == INVALID_SOCKET) { return false; }
  4287. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4288. auto ssl = wolfSSL_new(ctx);
  4289. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4290. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4291. if (session) { wolfSSL_set_session(ssl, session); }
  4292. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4293. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4294. "Connection: close\r\n\r\n";
  4295. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4296. std::string res;
  4297. char buf[256];
  4298. int n;
  4299. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4300. res.append(buf, static_cast<size_t>(n));
  4301. }
  4302. wolfSSL_shutdown(ssl);
  4303. if (session) { wolfSSL_SESSION_free(session); }
  4304. session = wolfSSL_get1_session(ssl);
  4305. return res.find("200 OK") != std::string::npos;
  4306. };
  4307. ASSERT_TRUE(get(PORT));
  4308. EXPECT_FALSE(get(PORT + 1));
  4309. ASSERT_TRUE(get(PORT));
  4310. ASSERT_TRUE(replace_client_ca(svr));
  4311. EXPECT_FALSE(get(PORT));
  4312. }
  4313. #endif
  4314. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4315. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4316. ASSERT_TRUE(svr.is_valid());
  4317. svr.Get("/test", [](const Request &, Response &res) {
  4318. res.set_content("ok", "text/plain");
  4319. });
  4320. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4321. auto se = detail::scope_exit([&] {
  4322. svr.stop();
  4323. t.join();
  4324. ASSERT_FALSE(svr.is_running());
  4325. });
  4326. svr.wait_until_ready();
  4327. // A connection that sends no ClientHello keeps its handshake in progress,
  4328. // once the server has had a moment to start it.
  4329. auto error = Error::Success;
  4330. auto sock = detail::create_client_socket(
  4331. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4332. /*connection_timeout_sec=*/5, 0,
  4333. /*read_timeout_sec=*/5, 0,
  4334. /*write_timeout_sec=*/5, 0, std::string(), error);
  4335. ASSERT_NE(INVALID_SOCKET, sock);
  4336. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4337. std::string cert_pem, key_pem;
  4338. read_file(SERVER_CERT_FILE, cert_pem);
  4339. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4340. auto update = std::async(std::launch::async, [&]() {
  4341. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4342. });
  4343. EXPECT_EQ(std::future_status::timeout,
  4344. update.wait_for(std::chrono::milliseconds(200)));
  4345. detail::close_socket(sock);
  4346. EXPECT_TRUE(update.get());
  4347. SSLClient cli(HOST, PORT);
  4348. cli.enable_server_certificate_verification(false);
  4349. auto res = cli.Get("/test");
  4350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4351. EXPECT_EQ(StatusCode::OK_200, res->status);
  4352. }
  4353. #endif
  4354. TEST(ErrorHandlerTest, ContentLength) {
  4355. Server svr;
  4356. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4357. res.status = StatusCode::OK_200;
  4358. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4359. "text/html"); // <= Content-Length still 13
  4360. });
  4361. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4362. res.set_content("Hello World!\n", "text/plain");
  4363. res.status = 524;
  4364. });
  4365. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4366. auto se = detail::scope_exit([&] {
  4367. svr.stop();
  4368. thread.join();
  4369. ASSERT_FALSE(svr.is_running());
  4370. });
  4371. svr.wait_until_ready();
  4372. {
  4373. Client cli(HOST, PORT);
  4374. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4376. EXPECT_EQ(StatusCode::OK_200, res->status);
  4377. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4378. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4379. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4380. }
  4381. }
  4382. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4383. TEST(ExceptionTest, WithoutExceptionHandler) {
  4384. Server svr;
  4385. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4386. throw std::runtime_error("exception...");
  4387. });
  4388. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4389. throw std::runtime_error("exception\r\n...");
  4390. });
  4391. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4392. auto se = detail::scope_exit([&] {
  4393. svr.stop();
  4394. listen_thread.join();
  4395. ASSERT_FALSE(svr.is_running());
  4396. });
  4397. svr.wait_until_ready();
  4398. Client cli("localhost", PORT);
  4399. {
  4400. auto res = cli.Get("/exception");
  4401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4402. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4403. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4404. }
  4405. {
  4406. auto res = cli.Get("/unknown");
  4407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4408. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4409. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4410. }
  4411. }
  4412. TEST(ExceptionTest, WithExceptionHandler) {
  4413. Server svr;
  4414. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4415. std::exception_ptr ep) {
  4416. EXPECT_FALSE(ep == nullptr);
  4417. try {
  4418. std::rethrow_exception(ep);
  4419. } catch (std::exception &e) {
  4420. EXPECT_EQ("abc", std::string(e.what()));
  4421. } catch (...) {}
  4422. res.status = StatusCode::InternalServerError_500;
  4423. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4424. "text/html"); // <= Content-Length still 13 at this point
  4425. });
  4426. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4427. res.set_content("Hello World!\n", "text/plain");
  4428. throw std::runtime_error("abc");
  4429. });
  4430. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4431. auto se = detail::scope_exit([&] {
  4432. svr.stop();
  4433. thread.join();
  4434. ASSERT_FALSE(svr.is_running());
  4435. });
  4436. svr.wait_until_ready();
  4437. for (size_t i = 0; i < 10; i++) {
  4438. Client cli(HOST, PORT);
  4439. for (size_t j = 0; j < 100; j++) {
  4440. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4442. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4443. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4444. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4445. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4446. }
  4447. cli.set_keep_alive(true);
  4448. for (size_t j = 0; j < 100; j++) {
  4449. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4451. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4452. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4453. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4454. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4455. }
  4456. }
  4457. }
  4458. TEST(ExceptionTest, AndErrorHandler) {
  4459. Server svr;
  4460. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4461. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4462. });
  4463. svr.set_exception_handler(
  4464. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4465. EXPECT_FALSE(ep == nullptr);
  4466. try {
  4467. std::rethrow_exception(ep);
  4468. } catch (std::exception &e) {
  4469. res.set_content(e.what(), "text/html");
  4470. } catch (...) {}
  4471. res.status = StatusCode::InternalServerError_500;
  4472. });
  4473. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4474. throw std::runtime_error("EXCEPTION");
  4475. });
  4476. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4477. res.set_content("ERROR", "text/html");
  4478. res.status = StatusCode::InternalServerError_500;
  4479. });
  4480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4481. auto se = detail::scope_exit([&] {
  4482. svr.stop();
  4483. thread.join();
  4484. ASSERT_FALSE(svr.is_running());
  4485. });
  4486. svr.wait_until_ready();
  4487. Client cli(HOST, PORT);
  4488. {
  4489. auto res = cli.Get("/exception");
  4490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4491. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4492. EXPECT_EQ("EXCEPTION", res->body);
  4493. }
  4494. {
  4495. auto res = cli.Get("/error");
  4496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4497. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4498. EXPECT_EQ("ERROR", res->body);
  4499. }
  4500. {
  4501. auto res = cli.Get("/invalid");
  4502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4504. EXPECT_EQ("NOT_FOUND", res->body);
  4505. }
  4506. }
  4507. #endif
  4508. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4509. // process_request() wraps only routing() in a try/catch, so an exception from
  4510. // any other user callback used to unwind into the task queue - which does not
  4511. // catch - and terminate the process. Each test below runs the server on a
  4512. // single worker thread: a guard that catches the exception but still loses the
  4513. // thread would otherwise be hidden by a spare worker serving the follow-up
  4514. // request. Note that a regression here aborts the whole test binary rather
  4515. // than failing one test.
  4516. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4517. Server svr;
  4518. svr.new_task_queue = [] { return new ThreadPool(1); };
  4519. std::atomic<int> reported{0};
  4520. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4521. if (err == Error::UserCallbackException) { reported++; }
  4522. });
  4523. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4524. res.set_content_provider(
  4525. 1024, "text/plain",
  4526. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4527. sink.write("hello", 5);
  4528. throw std::runtime_error("from the content provider");
  4529. });
  4530. });
  4531. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4532. res.set_content("ok", "text/plain");
  4533. });
  4534. auto port = svr.bind_to_any_port(HOST);
  4535. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4536. auto se = detail::scope_exit([&] {
  4537. svr.stop();
  4538. listen_thread.join();
  4539. ASSERT_FALSE(svr.is_running());
  4540. });
  4541. svr.wait_until_ready();
  4542. {
  4543. Client cli(HOST, port);
  4544. cli.set_read_timeout(5, 0);
  4545. EXPECT_FALSE(cli.Get("/throw"));
  4546. }
  4547. EXPECT_TRUE(svr.is_running());
  4548. EXPECT_EQ(1, reported.load());
  4549. // A request on a fresh connection is still served.
  4550. {
  4551. Client cli(HOST, port);
  4552. auto res = cli.Get("/ok");
  4553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4554. EXPECT_EQ(StatusCode::OK_200, res->status);
  4555. EXPECT_EQ("ok", res->body);
  4556. }
  4557. }
  4558. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4559. Server svr;
  4560. svr.new_task_queue = [] { return new ThreadPool(1); };
  4561. std::atomic<bool> should_throw{true};
  4562. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4563. res.set_content("hi", "text/plain");
  4564. });
  4565. svr.set_post_routing_handler(
  4566. [&](const Request & /*req*/, Response & /*res*/) {
  4567. if (should_throw) {
  4568. throw std::runtime_error("from the post-routing handler");
  4569. }
  4570. });
  4571. auto port = svr.bind_to_any_port(HOST);
  4572. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4573. auto se = detail::scope_exit([&] {
  4574. svr.stop();
  4575. listen_thread.join();
  4576. ASSERT_FALSE(svr.is_running());
  4577. });
  4578. svr.wait_until_ready();
  4579. {
  4580. Client cli(HOST, port);
  4581. cli.set_read_timeout(5, 0);
  4582. EXPECT_FALSE(cli.Get("/hi"));
  4583. }
  4584. EXPECT_TRUE(svr.is_running());
  4585. should_throw = false;
  4586. {
  4587. Client cli(HOST, port);
  4588. auto res = cli.Get("/hi");
  4589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4590. EXPECT_EQ(StatusCode::OK_200, res->status);
  4591. EXPECT_EQ("hi", res->body);
  4592. }
  4593. }
  4594. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4595. // The guard reports the caught exception through the error logger, which is
  4596. // a user callback too. A logger that throws has to be contained as well, or
  4597. // the process would terminate from inside the catch.
  4598. Server svr;
  4599. svr.new_task_queue = [] { return new ThreadPool(1); };
  4600. std::atomic<int> reported{0};
  4601. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4602. if (err == Error::UserCallbackException) {
  4603. reported++;
  4604. throw std::runtime_error("from the error logger");
  4605. }
  4606. });
  4607. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4608. res.set_content_provider(
  4609. 1024, "text/plain",
  4610. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4611. sink.write("hello", 5);
  4612. throw std::runtime_error("from the content provider");
  4613. });
  4614. });
  4615. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4616. res.set_content("ok", "text/plain");
  4617. });
  4618. auto port = svr.bind_to_any_port(HOST);
  4619. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4620. auto se = detail::scope_exit([&] {
  4621. svr.stop();
  4622. listen_thread.join();
  4623. ASSERT_FALSE(svr.is_running());
  4624. });
  4625. svr.wait_until_ready();
  4626. {
  4627. Client cli(HOST, port);
  4628. cli.set_read_timeout(5, 0);
  4629. EXPECT_FALSE(cli.Get("/throw"));
  4630. }
  4631. EXPECT_TRUE(svr.is_running());
  4632. EXPECT_EQ(1, reported.load());
  4633. {
  4634. Client cli(HOST, port);
  4635. auto res = cli.Get("/ok");
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. EXPECT_EQ("ok", res->body);
  4639. }
  4640. }
  4641. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4642. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4643. // so the exception unwinds through the ws::WebSocket object on its way to
  4644. // the guard. None of the HTTP cases above cross that.
  4645. Server svr;
  4646. svr.new_task_queue = [] { return new ThreadPool(1); };
  4647. std::atomic<int> reported{0};
  4648. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4649. if (err == Error::UserCallbackException) { reported++; }
  4650. });
  4651. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4652. throw std::runtime_error("from the WebSocket handler");
  4653. });
  4654. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4655. res.set_content("ok", "text/plain");
  4656. });
  4657. auto port = svr.bind_to_any_port(HOST);
  4658. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4659. auto se = detail::scope_exit([&] {
  4660. svr.stop();
  4661. listen_thread.join();
  4662. ASSERT_FALSE(svr.is_running());
  4663. });
  4664. svr.wait_until_ready();
  4665. {
  4666. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4667. "/ws");
  4668. auto res = client.connect();
  4669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4670. // The server dropped the connection instead of dying.
  4671. std::string msg;
  4672. EXPECT_FALSE(client.read(msg));
  4673. client.close();
  4674. }
  4675. EXPECT_TRUE(svr.is_running());
  4676. EXPECT_EQ(1, reported.load());
  4677. {
  4678. Client cli(HOST, port);
  4679. auto res = cli.Get("/ok");
  4680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4681. EXPECT_EQ(StatusCode::OK_200, res->status);
  4682. EXPECT_EQ("ok", res->body);
  4683. }
  4684. }
  4685. #ifdef CPPHTTPLIB_SSL_ENABLED
  4686. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4687. // SSLServer::process_and_close_socket() is a separate overload with its own
  4688. // guard, so it is exercised on its own.
  4689. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4690. ASSERT_TRUE(svr.is_valid());
  4691. svr.new_task_queue = [] { return new ThreadPool(1); };
  4692. std::atomic<int> reported{0};
  4693. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4694. if (err == Error::UserCallbackException) { reported++; }
  4695. });
  4696. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4697. res.set_content_provider(
  4698. 1024, "text/plain",
  4699. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4700. sink.write("hello", 5);
  4701. throw std::runtime_error("from the content provider");
  4702. });
  4703. });
  4704. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4705. res.set_content("ok", "text/plain");
  4706. });
  4707. auto port = svr.bind_to_any_port(HOST);
  4708. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4709. auto se = detail::scope_exit([&] {
  4710. svr.stop();
  4711. listen_thread.join();
  4712. ASSERT_FALSE(svr.is_running());
  4713. });
  4714. svr.wait_until_ready();
  4715. {
  4716. SSLClient cli(HOST, port);
  4717. cli.enable_server_certificate_verification(false);
  4718. cli.set_read_timeout(5, 0);
  4719. EXPECT_FALSE(cli.Get("/throw"));
  4720. }
  4721. EXPECT_TRUE(svr.is_running());
  4722. EXPECT_EQ(1, reported.load());
  4723. {
  4724. SSLClient cli(HOST, port);
  4725. cli.enable_server_certificate_verification(false);
  4726. auto res = cli.Get("/ok");
  4727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4728. EXPECT_EQ(StatusCode::OK_200, res->status);
  4729. EXPECT_EQ("ok", res->body);
  4730. }
  4731. }
  4732. #endif
  4733. #endif
  4734. TEST(NoContentTest, ContentLength) {
  4735. Server svr;
  4736. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4737. res.status = StatusCode::NoContent_204;
  4738. });
  4739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4740. auto se = detail::scope_exit([&] {
  4741. svr.stop();
  4742. thread.join();
  4743. ASSERT_FALSE(svr.is_running());
  4744. });
  4745. svr.wait_until_ready();
  4746. {
  4747. Client cli(HOST, PORT);
  4748. auto res = cli.Get("/hi");
  4749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4750. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4751. // RFC 9110 8.6: none in a 204 response
  4752. EXPECT_FALSE(res->has_header("Content-Length"));
  4753. }
  4754. }
  4755. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4756. Server svr;
  4757. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4758. res.set_header("Content-Length", "5");
  4759. res.set_content("hello world", "text/plain");
  4760. });
  4761. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4762. // A body that reads as the last chunk, were it taken as chunked
  4763. res.set_header("Transfer-Encoding", "chunked");
  4764. res.set_content("0\r\n\r\n", "text/plain");
  4765. });
  4766. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4767. res.set_header("Content-Length", "2");
  4768. res.set_content_provider(5, "text/plain",
  4769. [](size_t offset, size_t length, DataSink &sink) {
  4770. sink.write(&"hello"[offset], length);
  4771. return true;
  4772. });
  4773. });
  4774. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4775. res.set_header("Content-Length", "1234");
  4776. });
  4777. thread t = thread([&] { svr.listen(HOST, PORT); });
  4778. auto se = detail::scope_exit([&] {
  4779. svr.stop();
  4780. t.join();
  4781. ASSERT_FALSE(svr.is_running());
  4782. });
  4783. svr.wait_until_ready();
  4784. Client cli(HOST, PORT);
  4785. cli.set_read_timeout(1, 0);
  4786. auto expect_body = [&](const Result &res, const std::string &body) {
  4787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4788. EXPECT_EQ(body, res->body);
  4789. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4790. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4791. };
  4792. Headers identity{{"Accept-Encoding", ""}};
  4793. expect_body(cli.Get("/body", identity), "hello world");
  4794. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4795. expect_body(cli.Get("/body",
  4796. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4797. "he");
  4798. expect_body(cli.Get("/provider", identity), "hello");
  4799. expect_body(cli.Get("/empty", identity), "");
  4800. // A HEAD response may give the length of the body a GET would get.
  4801. auto res = cli.Head("/empty");
  4802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4803. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4804. }
  4805. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4806. Server svr;
  4807. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4808. res.set_content("short", "text/plain");
  4809. });
  4810. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4811. res.body += " with a footer";
  4812. res.set_header("Transfer-Encoding", "chunked");
  4813. });
  4814. thread t = thread([&] { svr.listen(HOST, PORT); });
  4815. auto se = detail::scope_exit([&] {
  4816. svr.stop();
  4817. t.join();
  4818. ASSERT_FALSE(svr.is_running());
  4819. });
  4820. svr.wait_until_ready();
  4821. Client cli(HOST, PORT);
  4822. cli.set_read_timeout(1, 0);
  4823. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4825. EXPECT_EQ("short with a footer", res->body);
  4826. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4827. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4828. }
  4829. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4830. Server svr;
  4831. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4832. res.set_header("Content-Length", "3");
  4833. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4834. sink.write("abc", 3);
  4835. sink.done();
  4836. return true;
  4837. });
  4838. });
  4839. thread t = thread([&] { svr.listen(HOST, PORT); });
  4840. auto se = detail::scope_exit([&] {
  4841. svr.stop();
  4842. t.join();
  4843. ASSERT_FALSE(svr.is_running());
  4844. });
  4845. svr.wait_until_ready();
  4846. Client cli(HOST, PORT);
  4847. cli.set_keep_alive(true);
  4848. auto res = cli.Get("/");
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. EXPECT_EQ("abc", res->body);
  4851. EXPECT_FALSE(res->has_header("Content-Length"));
  4852. EXPECT_EQ("close", res->get_header_value("Connection"));
  4853. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4854. // No body to delimit
  4855. auto head = cli.Head("/");
  4856. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4857. EXPECT_FALSE(head->has_header("Connection"));
  4858. }
  4859. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4860. #ifdef CPPHTTPLIB_SSL_ENABLED
  4861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4862. ASSERT_TRUE(svr.is_valid());
  4863. #else
  4864. Server svr;
  4865. #endif
  4866. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4867. if (req.path == "/routing_handler") {
  4868. res.set_header("PRE_ROUTING", "on");
  4869. res.set_content("Routing Handler", "text/plain");
  4870. return httplib::Server::HandlerResponse::Handled;
  4871. }
  4872. return httplib::Server::HandlerResponse::Unhandled;
  4873. });
  4874. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4875. res.set_content("Error", "text/html");
  4876. });
  4877. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4878. if (req.path == "/routing_handler") {
  4879. res.set_header("POST_ROUTING", "on");
  4880. }
  4881. });
  4882. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4883. res.set_content("Hello World!\n", "text/plain");
  4884. });
  4885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4886. auto se = detail::scope_exit([&] {
  4887. svr.stop();
  4888. thread.join();
  4889. ASSERT_FALSE(svr.is_running());
  4890. });
  4891. svr.wait_until_ready();
  4892. {
  4893. #ifdef CPPHTTPLIB_SSL_ENABLED
  4894. SSLClient cli(HOST, PORT);
  4895. cli.enable_server_certificate_verification(false);
  4896. #else
  4897. Client cli(HOST, PORT);
  4898. #endif
  4899. auto res = cli.Get("/routing_handler");
  4900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4901. EXPECT_EQ(StatusCode::OK_200, res->status);
  4902. EXPECT_EQ("Routing Handler", res->body);
  4903. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4904. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4905. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4906. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4907. }
  4908. {
  4909. #ifdef CPPHTTPLIB_SSL_ENABLED
  4910. SSLClient cli(HOST, PORT);
  4911. cli.enable_server_certificate_verification(false);
  4912. #else
  4913. Client cli(HOST, PORT);
  4914. #endif
  4915. auto res = cli.Get("/hi");
  4916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4917. EXPECT_EQ(StatusCode::OK_200, res->status);
  4918. EXPECT_EQ("Hello World!\n", res->body);
  4919. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4920. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4921. }
  4922. {
  4923. #ifdef CPPHTTPLIB_SSL_ENABLED
  4924. SSLClient cli(HOST, PORT);
  4925. cli.enable_server_certificate_verification(false);
  4926. #else
  4927. Client cli(HOST, PORT);
  4928. #endif
  4929. auto res = cli.Get("/aaa");
  4930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4931. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4932. EXPECT_EQ("Error", res->body);
  4933. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4934. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4935. }
  4936. }
  4937. TEST(RequestHandlerTest, PreRequestHandler) {
  4938. auto route_path = "/user/:user";
  4939. Server svr;
  4940. svr.Get("/hi", [](const Request &, Response &res) {
  4941. res.set_content("hi", "text/plain");
  4942. });
  4943. svr.Get(route_path, [](const Request &req, Response &res) {
  4944. res.set_content(req.path_params.at("user"), "text/plain");
  4945. });
  4946. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4947. if (req.matched_route == route_path) {
  4948. auto user = req.path_params.at("user");
  4949. if (user != "john") {
  4950. res.status = StatusCode::Forbidden_403;
  4951. res.set_content("error", "text/html");
  4952. return Server::HandlerResponse::Handled;
  4953. }
  4954. }
  4955. return Server::HandlerResponse::Unhandled;
  4956. });
  4957. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4958. auto se = detail::scope_exit([&] {
  4959. svr.stop();
  4960. thread.join();
  4961. ASSERT_FALSE(svr.is_running());
  4962. });
  4963. svr.wait_until_ready();
  4964. Client cli(HOST, PORT);
  4965. {
  4966. auto res = cli.Get("/hi");
  4967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4968. EXPECT_EQ(StatusCode::OK_200, res->status);
  4969. EXPECT_EQ("hi", res->body);
  4970. }
  4971. {
  4972. auto res = cli.Get("/user/john");
  4973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4974. EXPECT_EQ(StatusCode::OK_200, res->status);
  4975. EXPECT_EQ("john", res->body);
  4976. }
  4977. {
  4978. auto res = cli.Get("/user/invalid-user");
  4979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4980. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4981. EXPECT_EQ("error", res->body);
  4982. }
  4983. }
  4984. // The pre-request handler must run before the request body is read, so a
  4985. // rejected request never forces the server to buffer a (potentially large)
  4986. // body. Here the posted body is larger than the payload limit: if the body
  4987. // were read first the server would answer 413, but because the pre-request
  4988. // handler runs first it answers 403 and the body is never read.
  4989. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4990. Server svr;
  4991. svr.set_payload_max_length(8);
  4992. auto handler_ran = false;
  4993. svr.Post("/reject", [&](const Request &req, Response &res) {
  4994. handler_ran = true;
  4995. res.set_content(req.body, "text/plain");
  4996. });
  4997. svr.Post("/accept", [](const Request &req, Response &res) {
  4998. res.set_content(req.body, "text/plain");
  4999. });
  5000. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5001. if (req.matched_route == "/reject") {
  5002. res.status = StatusCode::Forbidden_403;
  5003. res.set_content("denied", "text/plain");
  5004. return Server::HandlerResponse::Handled;
  5005. }
  5006. return Server::HandlerResponse::Unhandled;
  5007. });
  5008. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5009. auto se = detail::scope_exit([&] {
  5010. svr.stop();
  5011. thread.join();
  5012. ASSERT_FALSE(svr.is_running());
  5013. });
  5014. svr.wait_until_ready();
  5015. Client cli(HOST, PORT);
  5016. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5017. // rejects with 403 before the body is read, so 413 is never reached.
  5018. {
  5019. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5021. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5022. EXPECT_EQ("denied", res->body);
  5023. EXPECT_FALSE(handler_ran);
  5024. }
  5025. // An approved route still reads the body and enforces the payload limit.
  5026. {
  5027. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5029. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5030. }
  5031. }
  5032. TEST(UserDataTest, BasicOperations) {
  5033. httplib::UserData ud;
  5034. // Initially empty
  5035. EXPECT_FALSE(ud.has("key"));
  5036. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5037. // set and get
  5038. ud.set("key", 42);
  5039. EXPECT_TRUE(ud.has("key"));
  5040. auto *p = ud.get<int>("key");
  5041. ASSERT_NE(nullptr, p);
  5042. EXPECT_EQ(42, *p);
  5043. // Type mismatch → nullptr
  5044. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5045. // Overwrite with different type
  5046. ud.set("key", std::string("hello"));
  5047. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5048. auto *s = ud.get<std::string>("key");
  5049. ASSERT_NE(nullptr, s);
  5050. EXPECT_EQ("hello", *s);
  5051. // erase
  5052. ud.erase("key");
  5053. EXPECT_FALSE(ud.has("key"));
  5054. // clear
  5055. ud.set("a", 1);
  5056. ud.set("b", 2);
  5057. ud.clear();
  5058. EXPECT_FALSE(ud.has("a"));
  5059. EXPECT_FALSE(ud.has("b"));
  5060. }
  5061. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5062. struct AuthCtx {
  5063. std::string user_id;
  5064. };
  5065. Server svr;
  5066. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5067. res.user_data.set("auth", AuthCtx{"alice"});
  5068. return Server::HandlerResponse::Unhandled;
  5069. });
  5070. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5071. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5072. ASSERT_NE(nullptr, ctx);
  5073. res.set_content("Hello " + ctx->user_id, "text/plain");
  5074. });
  5075. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5076. auto se = detail::scope_exit([&] {
  5077. svr.stop();
  5078. thread.join();
  5079. ASSERT_FALSE(svr.is_running());
  5080. });
  5081. svr.wait_until_ready();
  5082. Client cli(HOST, PORT);
  5083. auto res = cli.Get("/me");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. EXPECT_EQ(StatusCode::OK_200, res->status);
  5086. EXPECT_EQ("Hello alice", res->body);
  5087. }
  5088. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5089. struct RoleCtx {
  5090. std::string role;
  5091. };
  5092. Server svr;
  5093. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5094. res.user_data.set("role", RoleCtx{"admin"});
  5095. return Server::HandlerResponse::Unhandled;
  5096. });
  5097. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5098. auto *ctx = res.user_data.get<RoleCtx>("role");
  5099. ASSERT_NE(nullptr, ctx);
  5100. res.set_content(ctx->role, "text/plain");
  5101. });
  5102. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5103. auto se = detail::scope_exit([&] {
  5104. svr.stop();
  5105. thread.join();
  5106. ASSERT_FALSE(svr.is_running());
  5107. });
  5108. svr.wait_until_ready();
  5109. Client cli(HOST, PORT);
  5110. auto res = cli.Get("/role");
  5111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5112. EXPECT_EQ(StatusCode::OK_200, res->status);
  5113. EXPECT_EQ("admin", res->body);
  5114. }
  5115. TEST(InvalidFormatTest, StatusCode) {
  5116. Server svr;
  5117. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5118. res.set_content("Hello World!\n", "text/plain");
  5119. res.status = 9999; // Status should be a three-digit code...
  5120. });
  5121. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5122. auto se = detail::scope_exit([&] {
  5123. svr.stop();
  5124. thread.join();
  5125. ASSERT_FALSE(svr.is_running());
  5126. });
  5127. svr.wait_until_ready();
  5128. {
  5129. Client cli(HOST, PORT);
  5130. auto res = cli.Get("/hi");
  5131. ASSERT_FALSE(res);
  5132. }
  5133. }
  5134. TEST(URLFragmentTest, WithFragment) {
  5135. Server svr;
  5136. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5137. EXPECT_TRUE(req.target == "/hi");
  5138. });
  5139. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5140. auto se = detail::scope_exit([&] {
  5141. svr.stop();
  5142. thread.join();
  5143. ASSERT_FALSE(svr.is_running());
  5144. });
  5145. svr.wait_until_ready();
  5146. {
  5147. Client cli(HOST, PORT);
  5148. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5149. EXPECT_TRUE(res);
  5150. EXPECT_EQ(StatusCode::OK_200, res->status);
  5151. res = cli.Get("/hi%23key1=val1=key2=val2");
  5152. EXPECT_TRUE(res);
  5153. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5154. }
  5155. }
  5156. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5157. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5158. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5159. Server svr;
  5160. std::vector<std::string> targets;
  5161. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5162. targets.push_back(req.target);
  5163. });
  5164. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5165. auto se = detail::scope_exit([&] {
  5166. svr.stop();
  5167. thread.join();
  5168. ASSERT_FALSE(svr.is_running());
  5169. });
  5170. svr.wait_until_ready();
  5171. Client cli(HOST, PORT);
  5172. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5173. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5174. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5175. // A '?' after the '#' belongs to the fragment, not to the query.
  5176. Request req;
  5177. req.method = "GET";
  5178. req.path = "/hi#f?x=1";
  5179. req.params.emplace("a", "1");
  5180. Response res;
  5181. auto error = Error::Success;
  5182. EXPECT_TRUE(cli.send(req, res, error));
  5183. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5184. "/hi?a=1"}),
  5185. targets);
  5186. }
  5187. TEST(HeaderWriter, SetHeaderWriter) {
  5188. Server svr;
  5189. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5190. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5191. return detail::write_headers(strm, hdrs);
  5192. });
  5193. svr.Get("/hi", [](const Request &req, Response &res) {
  5194. auto it = req.headers.find("CustomClientHeader");
  5195. EXPECT_TRUE(it != req.headers.end());
  5196. EXPECT_EQ(it->second, "CustomClientValue");
  5197. res.set_content("Hello World!\n", "text/plain");
  5198. });
  5199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5200. auto se = detail::scope_exit([&] {
  5201. svr.stop();
  5202. thread.join();
  5203. ASSERT_FALSE(svr.is_running());
  5204. });
  5205. svr.wait_until_ready();
  5206. {
  5207. Client cli(HOST, PORT);
  5208. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5209. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5210. return detail::write_headers(strm, hdrs);
  5211. });
  5212. auto res = cli.Get("/hi");
  5213. EXPECT_TRUE(res);
  5214. EXPECT_EQ(StatusCode::OK_200, res->status);
  5215. auto it = res->headers.find("CustomServerHeader");
  5216. EXPECT_TRUE(it != res->headers.end());
  5217. EXPECT_EQ(it->second, "CustomServerValue");
  5218. }
  5219. }
  5220. class ServerTest : public ::testing::Test {
  5221. protected:
  5222. ServerTest()
  5223. : cli_(HOST, PORT)
  5224. #ifdef CPPHTTPLIB_SSL_ENABLED
  5225. ,
  5226. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5227. #endif
  5228. {
  5229. #ifdef CPPHTTPLIB_SSL_ENABLED
  5230. cli_.enable_server_certificate_verification(false);
  5231. #endif
  5232. // Allow LARGE_DATA (100MB) responses
  5233. cli_.set_payload_max_length(200 * 1024 * 1024);
  5234. }
  5235. virtual void SetUp() {
  5236. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5237. svr_.set_payload_max_length(200 * 1024 * 1024);
  5238. svr_.set_mount_point("/", "./www");
  5239. svr_.set_mount_point("/mount", "./www2");
  5240. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5241. svr_.Get("/hi",
  5242. [&](const Request & /*req*/, Response &res) {
  5243. res.set_content("Hello World!", "text/plain");
  5244. })
  5245. .Get("/file_content",
  5246. [&](const Request & /*req*/, Response &res) {
  5247. res.set_file_content("./www/dir/test.html");
  5248. })
  5249. .Get("/file_content_with_content_type",
  5250. [&](const Request & /*req*/, Response &res) {
  5251. res.set_file_content("./www/file", "text/plain");
  5252. })
  5253. .Get("/invalid_file_content",
  5254. [&](const Request & /*req*/, Response &res) {
  5255. res.set_file_content("./www/dir/invalid_file_path");
  5256. })
  5257. .Get("/http_response_splitting",
  5258. [&](const Request & /*req*/, Response &res) {
  5259. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5260. EXPECT_EQ(0U, res.headers.size());
  5261. EXPECT_FALSE(res.has_header("a"));
  5262. res.set_header("a", "1\nSet-Cookie: a=1");
  5263. EXPECT_EQ(0U, res.headers.size());
  5264. EXPECT_FALSE(res.has_header("a"));
  5265. res.set_header("a", "1\rSet-Cookie: a=1");
  5266. EXPECT_EQ(0U, res.headers.size());
  5267. EXPECT_FALSE(res.has_header("a"));
  5268. res.set_header("a\r\nb", "0");
  5269. EXPECT_EQ(0U, res.headers.size());
  5270. EXPECT_FALSE(res.has_header("a"));
  5271. res.set_header("a\rb", "0");
  5272. EXPECT_EQ(0U, res.headers.size());
  5273. EXPECT_FALSE(res.has_header("a"));
  5274. res.set_header("a\nb", "0");
  5275. EXPECT_EQ(0U, res.headers.size());
  5276. EXPECT_FALSE(res.has_header("a"));
  5277. res.set_redirect("1\r\nSet-Cookie: a=1");
  5278. EXPECT_EQ(0U, res.headers.size());
  5279. EXPECT_FALSE(res.has_header("Location"));
  5280. })
  5281. .Get("/slow",
  5282. [&](const Request & /*req*/, Response &res) {
  5283. std::this_thread::sleep_for(std::chrono::seconds(4));
  5284. res.set_content("slow", "text/plain");
  5285. })
  5286. #if 0
  5287. .Post("/slowpost",
  5288. [&](const Request & /*req*/, Response &res) {
  5289. std::this_thread::sleep_for(std::chrono::seconds(2));
  5290. res.set_content("slow", "text/plain");
  5291. })
  5292. #endif
  5293. .Get("/remote_addr",
  5294. [&](const Request &req, Response &res) {
  5295. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5296. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5297. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5298. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5299. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5300. #endif
  5301. res.set_content(req.remote_addr, "text/plain");
  5302. })
  5303. .Get("/local_addr",
  5304. [&](const Request &req, Response &res) {
  5305. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5306. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5307. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5308. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5309. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5310. #endif
  5311. auto local_addr = req.local_addr;
  5312. auto local_port = std::to_string(req.local_port);
  5313. res.set_content(local_addr.append(":").append(local_port),
  5314. "text/plain");
  5315. })
  5316. .Get("/endwith%",
  5317. [&](const Request & /*req*/, Response &res) {
  5318. res.set_content("Hello World!", "text/plain");
  5319. })
  5320. .Get("/a\\+\\+b",
  5321. [&](const Request &req, Response &res) {
  5322. ASSERT_TRUE(req.has_param("a +b"));
  5323. auto val = req.get_param_value("a +b");
  5324. res.set_content(val, "text/plain");
  5325. })
  5326. .Get("/", [&](const Request & /*req*/,
  5327. Response &res) { res.set_redirect("/hi"); })
  5328. .Post("/1",
  5329. [](const Request & /*req*/, Response &res) {
  5330. res.set_redirect("/2", StatusCode::SeeOther_303);
  5331. })
  5332. .Get("/2",
  5333. [](const Request & /*req*/, Response &res) {
  5334. res.set_content("redirected.", "text/plain");
  5335. res.status = StatusCode::OK_200;
  5336. })
  5337. .Post("/person",
  5338. [&](const Request &req, Response &res) {
  5339. if (req.has_param("name") && req.has_param("note")) {
  5340. persons_[req.get_param_value("name")] =
  5341. req.get_param_value("note");
  5342. } else {
  5343. res.status = StatusCode::BadRequest_400;
  5344. }
  5345. })
  5346. .Put("/person",
  5347. [&](const Request &req, Response &res) {
  5348. if (req.has_param("name") && req.has_param("note")) {
  5349. persons_[req.get_param_value("name")] =
  5350. req.get_param_value("note");
  5351. } else {
  5352. res.status = StatusCode::BadRequest_400;
  5353. }
  5354. })
  5355. .Get("/person/(.*)",
  5356. [&](const Request &req, Response &res) {
  5357. string name = req.matches[1];
  5358. if (persons_.find(name) != persons_.end()) {
  5359. auto note = persons_[name];
  5360. res.set_content(note, "text/plain");
  5361. } else {
  5362. res.status = StatusCode::NotFound_404;
  5363. }
  5364. })
  5365. .Delete("/person",
  5366. [&](const Request &req, Response &res) {
  5367. if (req.has_param("name")) {
  5368. string name = req.get_param_value("name");
  5369. if (persons_.find(name) != persons_.end()) {
  5370. persons_.erase(name);
  5371. res.set_content("DELETED", "text/plain");
  5372. } else {
  5373. res.status = StatusCode::NotFound_404;
  5374. }
  5375. } else {
  5376. res.status = StatusCode::BadRequest_400;
  5377. }
  5378. })
  5379. .Post("/x-www-form-urlencoded-json",
  5380. [&](const Request &req, Response &res) {
  5381. auto json = req.get_param_value("json");
  5382. ASSERT_EQ(JSON_DATA, json);
  5383. res.set_content(json, "appliation/json");
  5384. res.status = StatusCode::OK_200;
  5385. })
  5386. .Get("/streamed-chunked",
  5387. [&](const Request & /*req*/, Response &res) {
  5388. res.set_chunked_content_provider(
  5389. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5390. sink.os << "123";
  5391. sink.os << "456";
  5392. sink.os << "789";
  5393. sink.done();
  5394. return true;
  5395. });
  5396. })
  5397. .Get("/streamed-chunked-with-prohibited-trailer",
  5398. [&](const Request & /*req*/, Response &res) {
  5399. auto i = new int(0);
  5400. // Declare both a prohibited trailer (Content-Length) and an
  5401. // allowed one
  5402. res.set_header("Trailer", "Content-Length, X-Allowed");
  5403. res.set_chunked_content_provider(
  5404. "text/plain",
  5405. [i](size_t /*offset*/, DataSink &sink) {
  5406. switch (*i) {
  5407. case 0: sink.os << "123"; break;
  5408. case 1: sink.os << "456"; break;
  5409. case 2: sink.os << "789"; break;
  5410. case 3: {
  5411. sink.done_with_trailer(
  5412. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5413. } break;
  5414. }
  5415. (*i)++;
  5416. return true;
  5417. },
  5418. [i](bool success) {
  5419. EXPECT_TRUE(success);
  5420. delete i;
  5421. });
  5422. })
  5423. .Get("/streamed-chunked2",
  5424. [&](const Request & /*req*/, Response &res) {
  5425. auto i = new int(0);
  5426. res.set_chunked_content_provider(
  5427. "text/plain",
  5428. [i](size_t /*offset*/, DataSink &sink) {
  5429. switch (*i) {
  5430. case 0: sink.os << "123"; break;
  5431. case 1: sink.os << "456"; break;
  5432. case 2: sink.os << "789"; break;
  5433. case 3: sink.done(); break;
  5434. }
  5435. (*i)++;
  5436. return true;
  5437. },
  5438. [i](bool success) {
  5439. EXPECT_TRUE(success);
  5440. delete i;
  5441. });
  5442. })
  5443. .Get("/streamed-chunked-with-trailer",
  5444. [&](const Request & /*req*/, Response &res) {
  5445. auto i = new int(0);
  5446. res.set_header("Trailer", "Dummy1, Dummy2");
  5447. res.set_chunked_content_provider(
  5448. "text/plain",
  5449. [i](size_t /*offset*/, DataSink &sink) {
  5450. switch (*i) {
  5451. case 0: sink.os << "123"; break;
  5452. case 1: sink.os << "456"; break;
  5453. case 2: sink.os << "789"; break;
  5454. case 3: {
  5455. sink.done_with_trailer(
  5456. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5457. } break;
  5458. }
  5459. (*i)++;
  5460. return true;
  5461. },
  5462. [i](bool success) {
  5463. EXPECT_TRUE(success);
  5464. delete i;
  5465. });
  5466. })
  5467. .Get("/streamed",
  5468. [&](const Request & /*req*/, Response &res) {
  5469. res.set_content_provider(
  5470. 6, "text/plain",
  5471. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5472. sink.os << (offset < 3 ? "a" : "b");
  5473. return true;
  5474. });
  5475. })
  5476. .Get("/streamed-without-length",
  5477. [&](const Request & /*req*/, Response &res) {
  5478. auto data = new std::string("abcdefg");
  5479. res.set_content_provider(
  5480. "text/plain",
  5481. [data](size_t offset, DataSink &sink) {
  5482. if (offset < data->size()) {
  5483. sink.os << data->substr(offset);
  5484. }
  5485. sink.done();
  5486. return true;
  5487. },
  5488. [data](bool success) {
  5489. EXPECT_TRUE(success);
  5490. delete data;
  5491. });
  5492. })
  5493. .Get("/streamed-with-range",
  5494. [&](const Request &req, Response &res) {
  5495. auto data = new std::string("abcdefg");
  5496. // An explicit status keeps the server from picking the 206 it
  5497. // would otherwise choose for a ranged request, so the response
  5498. // is not a partial representation.
  5499. auto status = req.get_param_value("status");
  5500. if (status == "200") {
  5501. res.status = StatusCode::OK_200;
  5502. } else if (status == "403") {
  5503. res.status = StatusCode::Forbidden_403;
  5504. }
  5505. res.set_content_provider(
  5506. data->size(), "text/plain",
  5507. [data](size_t offset, size_t length, DataSink &sink) {
  5508. size_t DATA_CHUNK_SIZE = 4;
  5509. const auto &d = *data;
  5510. auto out_len =
  5511. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5512. auto ret =
  5513. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5514. EXPECT_TRUE(ret);
  5515. return true;
  5516. },
  5517. [data, &req](bool success) {
  5518. EXPECT_EQ(success, !req.has_param("error"));
  5519. delete data;
  5520. });
  5521. })
  5522. .Get("/streamed-cancel",
  5523. [&](const Request & /*req*/, Response &res) {
  5524. res.set_content_provider(
  5525. size_t(-1), "text/plain",
  5526. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5527. sink.os << "data_chunk";
  5528. return true;
  5529. });
  5530. })
  5531. .Get("/regex-with-delimiter",
  5532. [&](const Request &req, Response & /*res*/) {
  5533. ASSERT_TRUE(req.has_param("key"));
  5534. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5535. })
  5536. .Get("/with-range",
  5537. [&](const Request & /*req*/, Response &res) {
  5538. res.set_content("abcdefg", "text/plain");
  5539. })
  5540. .Get("/test-start-time",
  5541. [&](const Request &req, Response & /*res*/) {
  5542. EXPECT_NE(req.start_time_,
  5543. std::chrono::steady_clock::time_point::min());
  5544. })
  5545. .Get("/with-range-customized-response",
  5546. [&](const Request & /*req*/, Response &res) {
  5547. res.status = StatusCode::BadRequest_400;
  5548. res.set_content(JSON_DATA, "application/json");
  5549. })
  5550. .Post("/chunked",
  5551. [&](const Request &req, Response & /*res*/) {
  5552. EXPECT_EQ(req.body, "dechunked post body");
  5553. })
  5554. .Post("/large-chunked",
  5555. [&](const Request &req, Response & /*res*/) {
  5556. std::string expected(6 * 30 * 1024u, 'a');
  5557. EXPECT_EQ(req.body, expected);
  5558. })
  5559. .Post("/multipart",
  5560. [&](const Request &req, Response & /*res*/) {
  5561. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5562. req.form.get_field_count("text2") +
  5563. req.form.get_field_count("file3") +
  5564. req.form.get_field_count("file4"));
  5565. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5566. req.form.get_file_count("file2"));
  5567. ASSERT_TRUE(!req.form.has_file("???"));
  5568. ASSERT_TRUE(!req.form.has_field("???"));
  5569. ASSERT_TRUE(req.body.empty());
  5570. {
  5571. const auto &text = req.form.get_field("text1");
  5572. EXPECT_EQ("text default", text);
  5573. }
  5574. {
  5575. const auto &text = req.form.get_field("text2");
  5576. EXPECT_EQ("aωb", text);
  5577. }
  5578. {
  5579. const auto &file = req.form.get_file("file1");
  5580. EXPECT_EQ("hello.txt", file.filename);
  5581. EXPECT_EQ("text/plain", file.content_type);
  5582. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5583. }
  5584. {
  5585. const auto &file = req.form.get_file("file2");
  5586. EXPECT_EQ("world.json", file.filename);
  5587. EXPECT_EQ("application/json", file.content_type);
  5588. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5589. }
  5590. {
  5591. const auto &text = req.form.get_field("file3");
  5592. EXPECT_EQ(0u, text.size());
  5593. }
  5594. {
  5595. const auto &text = req.form.get_field("file4");
  5596. EXPECT_EQ(0u, text.size());
  5597. }
  5598. })
  5599. .Post("/multipart/multi_file_values",
  5600. [&](const Request &req, Response & /*res*/) {
  5601. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5602. req.form.get_field_count("multi_text1"));
  5603. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5604. ASSERT_TRUE(!req.form.has_file("???"));
  5605. ASSERT_TRUE(!req.form.has_field("???"));
  5606. ASSERT_TRUE(req.body.empty());
  5607. {
  5608. const auto &text = req.form.get_field("text");
  5609. EXPECT_EQ("default text", text);
  5610. }
  5611. {
  5612. const auto &text1_values = req.form.get_fields("multi_text1");
  5613. EXPECT_EQ(2u, text1_values.size());
  5614. EXPECT_EQ("aaaaa", text1_values[0]);
  5615. EXPECT_EQ("bbbbb", text1_values[1]);
  5616. }
  5617. {
  5618. const auto &file1_values = req.form.get_files("multi_file1");
  5619. EXPECT_EQ(2u, file1_values.size());
  5620. auto file1 = file1_values[0];
  5621. EXPECT_EQ(file1.filename, "hello.txt");
  5622. EXPECT_EQ(file1.content_type, "text/plain");
  5623. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5624. auto file2 = file1_values[1];
  5625. EXPECT_EQ(file2.filename, "world.json");
  5626. EXPECT_EQ(file2.content_type, "application/json");
  5627. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5628. }
  5629. })
  5630. .Post("/empty",
  5631. [&](const Request &req, Response &res) {
  5632. EXPECT_EQ(req.body, "");
  5633. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5634. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5635. res.set_content("empty", "text/plain");
  5636. })
  5637. .Post("/empty-no-content-type",
  5638. [&](const Request &req, Response &res) {
  5639. EXPECT_EQ(req.body, "");
  5640. EXPECT_FALSE(req.has_header("Content-Type"));
  5641. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5642. res.set_content("empty-no-content-type", "text/plain");
  5643. })
  5644. .Post("/path-only",
  5645. [&](const Request &req, Response &res) {
  5646. EXPECT_EQ(req.body, "");
  5647. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5648. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5649. res.set_content("path-only", "text/plain");
  5650. })
  5651. .Post("/path-headers-only",
  5652. [&](const Request &req, Response &res) {
  5653. EXPECT_EQ(req.body, "");
  5654. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5655. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5656. EXPECT_EQ("world", req.get_header_value("hello"));
  5657. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5658. res.set_content("path-headers-only", "text/plain");
  5659. })
  5660. .Post("/post-large",
  5661. [&](const Request &req, Response &res) {
  5662. EXPECT_EQ(req.body, LARGE_DATA);
  5663. res.set_content(req.body, "text/plain");
  5664. })
  5665. .Post("/post-loopback",
  5666. [&](const Request &, Response &res,
  5667. ContentReader const &content_reader) {
  5668. std::string body;
  5669. content_reader([&](const char *data, size_t data_length) {
  5670. body.append(data, data_length);
  5671. return true;
  5672. });
  5673. res.set_content(body, "text/plain");
  5674. })
  5675. .Put("/put-loopback",
  5676. [&](const Request &, Response &res,
  5677. ContentReader const &content_reader) {
  5678. std::string body;
  5679. content_reader([&](const char *data, size_t data_length) {
  5680. body.append(data, data_length);
  5681. return true;
  5682. });
  5683. res.set_content(body, "text/plain");
  5684. })
  5685. .Patch("/patch-loopback",
  5686. [&](const Request &, Response &res,
  5687. ContentReader const &content_reader) {
  5688. std::string body;
  5689. content_reader([&](const char *data, size_t data_length) {
  5690. body.append(data, data_length);
  5691. return true;
  5692. });
  5693. res.set_content(body, "text/plain");
  5694. })
  5695. .Put("/empty-no-content-type",
  5696. [&](const Request &req, Response &res) {
  5697. EXPECT_EQ(req.body, "");
  5698. EXPECT_FALSE(req.has_header("Content-Type"));
  5699. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5700. res.set_content("empty-no-content-type", "text/plain");
  5701. })
  5702. .Put("/put",
  5703. [&](const Request &req, Response &res) {
  5704. EXPECT_EQ(req.body, "PUT");
  5705. res.set_content(req.body, "text/plain");
  5706. })
  5707. .Put("/put-large",
  5708. [&](const Request &req, Response &res) {
  5709. EXPECT_EQ(req.body, LARGE_DATA);
  5710. res.set_content(req.body, "text/plain");
  5711. })
  5712. .Patch("/patch",
  5713. [&](const Request &req, Response &res) {
  5714. EXPECT_EQ(req.body, "PATCH");
  5715. res.set_content(req.body, "text/plain");
  5716. })
  5717. .Delete("/delete",
  5718. [&](const Request & /*req*/, Response &res) {
  5719. res.set_content("DELETE", "text/plain");
  5720. })
  5721. .Delete("/delete-body",
  5722. [&](const Request &req, Response &res) {
  5723. EXPECT_EQ(req.body, "content");
  5724. res.set_content(req.body, "text/plain");
  5725. })
  5726. .Options(R"(\*)",
  5727. [&](const Request & /*req*/, Response &res) {
  5728. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5729. })
  5730. .CustomRoute("PROPFIND", "/dav/:id",
  5731. [&](const Request &req, Response &res) {
  5732. res.set_header("x-body-size",
  5733. std::to_string(req.body.size()));
  5734. res.set_header("x-matched-route", req.matched_route);
  5735. res.set_header("x-dav-id", req.path_params.at("id"));
  5736. res.status = StatusCode::MultiStatus_207;
  5737. res.set_content(req.body, "application/xml");
  5738. })
  5739. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5740. [&](const Request &req, Response &res) {
  5741. res.set_header("x-dav-match", req.matches[1]);
  5742. res.status = StatusCode::MultiStatus_207;
  5743. })
  5744. .CustomRoute("MKCOL", "/dav-mkcol",
  5745. [&](const Request &req, Response &res) {
  5746. EXPECT_TRUE(req.body.empty());
  5747. res.status = StatusCode::Created_201;
  5748. })
  5749. .CustomRoute(
  5750. "REPORT", "/dav-report",
  5751. [&](const Request & /*req*/, Response &res,
  5752. const ContentReader &content_reader) {
  5753. std::string body;
  5754. content_reader([&](const char *data, size_t data_length) {
  5755. body.append(data, data_length);
  5756. return true;
  5757. });
  5758. res.set_header("x-body-size", std::to_string(body.size()));
  5759. res.status = StatusCode::MultiStatus_207;
  5760. res.set_content(body, "application/xml");
  5761. })
  5762. .Get("/request-target",
  5763. [&](const Request &req, Response & /*res*/) {
  5764. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5765. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5766. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5767. })
  5768. .Get("/long-query-value",
  5769. [&](const Request &req, Response & /*res*/) {
  5770. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5771. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5772. })
  5773. .Get("/too-long-query-value",
  5774. [&](const Request &req, Response & /*res*/) {
  5775. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5776. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5777. })
  5778. .Get("/array-param",
  5779. [&](const Request &req, Response & /*res*/) {
  5780. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5781. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5782. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5783. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5784. })
  5785. .Get("/array-param-values",
  5786. [&](const Request &req, Response & /*res*/) {
  5787. auto values = req.get_param_values("array");
  5788. EXPECT_EQ(3u, values.size());
  5789. EXPECT_EQ("value1", values[0]);
  5790. EXPECT_EQ("value2", values[1]);
  5791. EXPECT_EQ("value3", values[2]);
  5792. auto empty = req.get_param_values("nonexistent");
  5793. EXPECT_TRUE(empty.empty());
  5794. })
  5795. .Post("/validate-no-multiple-headers",
  5796. [&](const Request &req, Response & /*res*/) {
  5797. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5798. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5799. })
  5800. .Post("/content_receiver",
  5801. [&](const Request &req, Response &res,
  5802. const ContentReader &content_reader) {
  5803. if (req.is_multipart_form_data()) {
  5804. std::vector<FormData> items;
  5805. content_reader(
  5806. [&](const FormData &file) {
  5807. items.push_back(file);
  5808. return true;
  5809. },
  5810. [&](const char *data, size_t data_length) {
  5811. items.back().content.append(data, data_length);
  5812. return true;
  5813. });
  5814. EXPECT_EQ(5u, items.size());
  5815. {
  5816. const auto &file = get_file_value(items, "text1");
  5817. EXPECT_TRUE(file.filename.empty());
  5818. EXPECT_EQ("text default", file.content);
  5819. }
  5820. {
  5821. const auto &file = get_file_value(items, "text2");
  5822. EXPECT_TRUE(file.filename.empty());
  5823. EXPECT_EQ("aωb", file.content);
  5824. }
  5825. {
  5826. const auto &file = get_file_value(items, "file1");
  5827. EXPECT_EQ("hello.txt", file.filename);
  5828. EXPECT_EQ("text/plain", file.content_type);
  5829. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5830. }
  5831. {
  5832. const auto &file = get_file_value(items, "file2");
  5833. EXPECT_EQ("world.json", file.filename);
  5834. EXPECT_EQ("application/json", file.content_type);
  5835. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5836. }
  5837. {
  5838. const auto &file = get_file_value(items, "file3");
  5839. EXPECT_TRUE(file.filename.empty());
  5840. EXPECT_EQ("application/octet-stream", file.content_type);
  5841. EXPECT_EQ(0u, file.content.size());
  5842. }
  5843. } else {
  5844. std::string body;
  5845. content_reader([&](const char *data, size_t data_length) {
  5846. EXPECT_EQ(7U, data_length);
  5847. body.append(data, data_length);
  5848. return true;
  5849. });
  5850. EXPECT_EQ(body, "content");
  5851. res.set_content(body, "text/plain");
  5852. }
  5853. })
  5854. .Put("/content_receiver",
  5855. [&](const Request & /*req*/, Response &res,
  5856. const ContentReader &content_reader) {
  5857. std::string body;
  5858. content_reader([&](const char *data, size_t data_length) {
  5859. body.append(data, data_length);
  5860. return true;
  5861. });
  5862. EXPECT_EQ(body, "content");
  5863. res.set_content(body, "text/plain");
  5864. })
  5865. .Patch("/content_receiver",
  5866. [&](const Request & /*req*/, Response &res,
  5867. const ContentReader &content_reader) {
  5868. std::string body;
  5869. content_reader([&](const char *data, size_t data_length) {
  5870. body.append(data, data_length);
  5871. return true;
  5872. });
  5873. EXPECT_EQ(body, "content");
  5874. res.set_content(body, "text/plain");
  5875. })
  5876. .Post("/query-string-and-body",
  5877. [&](const Request &req, Response & /*res*/) {
  5878. ASSERT_TRUE(req.has_param("key"));
  5879. EXPECT_EQ(req.get_param_value("key"), "value");
  5880. EXPECT_EQ(req.body, "content");
  5881. })
  5882. .Get("/last-request",
  5883. [&](const Request &req, Response & /*res*/) {
  5884. EXPECT_EQ("close", req.get_header_value("Connection"));
  5885. })
  5886. .Get(R"(/redirect/(\d+))",
  5887. [&](const Request &req, Response &res) {
  5888. auto num = std::stoi(req.matches[1]) + 1;
  5889. std::string url = "/redirect/" + std::to_string(num);
  5890. res.set_redirect(url);
  5891. })
  5892. .Post("/binary",
  5893. [&](const Request &req, Response &res) {
  5894. EXPECT_EQ(4U, req.body.size());
  5895. EXPECT_EQ("application/octet-stream",
  5896. req.get_header_value("Content-Type"));
  5897. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5898. res.set_content(req.body, "application/octet-stream");
  5899. })
  5900. .Put("/binary",
  5901. [&](const Request &req, Response &res) {
  5902. EXPECT_EQ(4U, req.body.size());
  5903. EXPECT_EQ("application/octet-stream",
  5904. req.get_header_value("Content-Type"));
  5905. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5906. res.set_content(req.body, "application/octet-stream");
  5907. })
  5908. .Patch("/binary",
  5909. [&](const Request &req, Response &res) {
  5910. EXPECT_EQ(4U, req.body.size());
  5911. EXPECT_EQ("application/octet-stream",
  5912. req.get_header_value("Content-Type"));
  5913. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5914. res.set_content(req.body, "application/octet-stream");
  5915. })
  5916. .Delete("/binary",
  5917. [&](const Request &req, Response &res) {
  5918. EXPECT_EQ(4U, req.body.size());
  5919. EXPECT_EQ("application/octet-stream",
  5920. req.get_header_value("Content-Type"));
  5921. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5922. res.set_content(req.body, "application/octet-stream");
  5923. })
  5924. .Get("/issue1772",
  5925. [&](const Request & /*req*/, Response &res) {
  5926. res.status = 401;
  5927. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5928. })
  5929. .Delete("/issue609",
  5930. [](const httplib::Request &, httplib::Response &res,
  5931. const httplib::ContentReader &) {
  5932. res.set_content("ok", "text/plain");
  5933. })
  5934. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5935. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5936. .Get("/compress",
  5937. [&](const Request & /*req*/, Response &res) {
  5938. res.set_content(
  5939. "12345678901234567890123456789012345678901234567890123456789"
  5940. "01234567890123456789012345678901234567890",
  5941. "text/plain");
  5942. })
  5943. .Get("/compress-with-charset",
  5944. [&](const Request & /*req*/, Response &res) {
  5945. res.set_content(
  5946. "12345678901234567890123456789012345678901234567890123456789"
  5947. "01234567890123456789012345678901234567890",
  5948. "application/json; charset=utf-8");
  5949. })
  5950. .Get("/nocompress",
  5951. [&](const Request & /*req*/, Response &res) {
  5952. res.set_content(
  5953. "12345678901234567890123456789012345678901234567890123456789"
  5954. "01234567890123456789012345678901234567890",
  5955. "application/octet-stream");
  5956. })
  5957. .Post("/compress-multipart",
  5958. [&](const Request &req, Response & /*res*/) {
  5959. EXPECT_EQ(2u, req.form.fields.size());
  5960. ASSERT_TRUE(!req.form.has_field("???"));
  5961. {
  5962. const auto &text = req.form.get_field("key1");
  5963. EXPECT_EQ("test", text);
  5964. }
  5965. {
  5966. const auto &text = req.form.get_field("key2");
  5967. EXPECT_EQ("--abcdefg123", text);
  5968. }
  5969. })
  5970. #endif
  5971. ;
  5972. persons_["john"] = "programmer";
  5973. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5974. svr_.wait_until_ready();
  5975. }
  5976. virtual void TearDown() {
  5977. svr_.stop();
  5978. if (!request_threads_.empty()) {
  5979. std::this_thread::sleep_for(std::chrono::seconds(1));
  5980. for (auto &t : request_threads_) {
  5981. t.join();
  5982. }
  5983. }
  5984. t_.join();
  5985. }
  5986. map<string, string> persons_;
  5987. #ifdef CPPHTTPLIB_SSL_ENABLED
  5988. SSLClient cli_;
  5989. SSLServer svr_;
  5990. #else
  5991. Client cli_;
  5992. Server svr_;
  5993. #endif
  5994. thread t_;
  5995. std::vector<thread> request_threads_;
  5996. };
  5997. TEST_F(ServerTest, GetMethod200) {
  5998. auto res = cli_.Get("/hi");
  5999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6000. EXPECT_EQ("HTTP/1.1", res->version);
  6001. EXPECT_EQ(StatusCode::OK_200, res->status);
  6002. EXPECT_EQ("OK", res->reason);
  6003. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6004. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6005. EXPECT_EQ("Hello World!", res->body);
  6006. }
  6007. TEST_F(ServerTest, GetEmptyFile) {
  6008. auto res = cli_.Get("/empty_file");
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. EXPECT_EQ(StatusCode::OK_200, res->status);
  6011. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6012. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6013. EXPECT_EQ("", res->body);
  6014. }
  6015. TEST_F(ServerTest, GetFileContent) {
  6016. auto res = cli_.Get("/file_content");
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6020. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6021. EXPECT_EQ("test.html", res->body);
  6022. }
  6023. TEST_F(ServerTest, GetFileContentWithRange) {
  6024. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6027. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6028. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6029. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6030. EXPECT_EQ("est", res->body);
  6031. }
  6032. TEST_F(ServerTest, GetFileContentWithContentType) {
  6033. auto res = cli_.Get("/file_content_with_content_type");
  6034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6035. EXPECT_EQ(StatusCode::OK_200, res->status);
  6036. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6037. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6038. EXPECT_EQ("file\n", res->body);
  6039. }
  6040. TEST_F(ServerTest, GetInvalidFileContent) {
  6041. auto res = cli_.Get("/invalid_file_content");
  6042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6043. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6044. }
  6045. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6046. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. EXPECT_EQ("HTTP/1.1", res->version);
  6049. EXPECT_EQ(StatusCode::OK_200, res->status);
  6050. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6051. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6052. EXPECT_EQ("Hello World!", res->body);
  6053. }
  6054. TEST_F(ServerTest, GetMethod302) {
  6055. auto res = cli_.Get("/");
  6056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6057. EXPECT_EQ(StatusCode::Found_302, res->status);
  6058. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6059. }
  6060. TEST_F(ServerTest, GetMethod302Redirect) {
  6061. cli_.set_follow_location(true);
  6062. auto res = cli_.Get("/");
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ(StatusCode::OK_200, res->status);
  6065. EXPECT_EQ("Hello World!", res->body);
  6066. EXPECT_EQ("/hi", res->location);
  6067. }
  6068. TEST_F(ServerTest, GetMethod404) {
  6069. auto res = cli_.Get("/invalid");
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6072. }
  6073. TEST_F(ServerTest, HeadMethod200) {
  6074. auto res = cli_.Head("/hi");
  6075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6076. EXPECT_EQ(StatusCode::OK_200, res->status);
  6077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6078. EXPECT_TRUE(res->body.empty());
  6079. }
  6080. TEST_F(ServerTest, HeadMethod200Static) {
  6081. auto res = cli_.Head("/mount/dir/index.html");
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. EXPECT_EQ(StatusCode::OK_200, res->status);
  6084. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6085. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6086. EXPECT_TRUE(res->body.empty());
  6087. }
  6088. TEST_F(ServerTest, HeadMethod404) {
  6089. auto res = cli_.Head("/invalid");
  6090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6091. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6092. EXPECT_TRUE(res->body.empty());
  6093. }
  6094. TEST_F(ServerTest, GetMethodPersonJohn) {
  6095. auto res = cli_.Get("/person/john");
  6096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6097. EXPECT_EQ(StatusCode::OK_200, res->status);
  6098. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6099. EXPECT_EQ("programmer", res->body);
  6100. }
  6101. TEST_F(ServerTest, PostMethod1) {
  6102. auto res = cli_.Get("/person/john1");
  6103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6104. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6105. res = cli_.Post("/person", "name=john1&note=coder",
  6106. "application/x-www-form-urlencoded");
  6107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6108. ASSERT_EQ(StatusCode::OK_200, res->status);
  6109. res = cli_.Get("/person/john1");
  6110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6111. ASSERT_EQ(StatusCode::OK_200, res->status);
  6112. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6113. ASSERT_EQ("coder", res->body);
  6114. }
  6115. TEST_F(ServerTest, PostMethod2) {
  6116. auto res = cli_.Get("/person/john2");
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6119. Params params;
  6120. params.emplace("name", "john2");
  6121. params.emplace("note", "coder");
  6122. res = cli_.Post("/person", params);
  6123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6124. ASSERT_EQ(StatusCode::OK_200, res->status);
  6125. res = cli_.Get("/person/john2");
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. ASSERT_EQ(StatusCode::OK_200, res->status);
  6128. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6129. ASSERT_EQ("coder", res->body);
  6130. }
  6131. TEST_F(ServerTest, PutMethod3) {
  6132. auto res = cli_.Get("/person/john3");
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6135. Params params;
  6136. params.emplace("name", "john3");
  6137. params.emplace("note", "coder");
  6138. res = cli_.Put("/person", params);
  6139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6140. ASSERT_EQ(StatusCode::OK_200, res->status);
  6141. res = cli_.Get("/person/john3");
  6142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6143. ASSERT_EQ(StatusCode::OK_200, res->status);
  6144. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6145. ASSERT_EQ("coder", res->body);
  6146. }
  6147. TEST_F(ServerTest, DeleteMethod1) {
  6148. auto res = cli_.Get("/person/john4");
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6151. Params params;
  6152. params.emplace("name", "john4");
  6153. params.emplace("note", "coder");
  6154. res = cli_.Post("/person", params);
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. ASSERT_EQ(StatusCode::OK_200, res->status);
  6157. res = cli_.Get("/person/john4");
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. ASSERT_EQ(StatusCode::OK_200, res->status);
  6160. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6161. ASSERT_EQ("coder", res->body);
  6162. Params delete_params;
  6163. delete_params.emplace("name", "john4");
  6164. res = cli_.Delete("/person", delete_params);
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. ASSERT_EQ(StatusCode::OK_200, res->status);
  6167. ASSERT_EQ("DELETED", res->body);
  6168. res = cli_.Get("/person/john4");
  6169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6170. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6171. }
  6172. TEST_F(ServerTest, DeleteMethod2) {
  6173. auto res = cli_.Get("/person/john5");
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6176. Params params;
  6177. params.emplace("name", "john5");
  6178. params.emplace("note", "developer");
  6179. res = cli_.Post("/person", params);
  6180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6181. ASSERT_EQ(StatusCode::OK_200, res->status);
  6182. res = cli_.Get("/person/john5");
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. ASSERT_EQ(StatusCode::OK_200, res->status);
  6185. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6186. ASSERT_EQ("developer", res->body);
  6187. Params delete_params;
  6188. delete_params.emplace("name", "john5");
  6189. Headers headers;
  6190. headers.emplace("Custom-Header", "test-value");
  6191. res = cli_.Delete("/person", headers, delete_params);
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. ASSERT_EQ(StatusCode::OK_200, res->status);
  6194. ASSERT_EQ("DELETED", res->body);
  6195. res = cli_.Get("/person/john5");
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6198. }
  6199. TEST_F(ServerTest, DeleteMethod3) {
  6200. auto res = cli_.Get("/person/john6");
  6201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6202. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6203. Params params;
  6204. params.emplace("name", "john6");
  6205. params.emplace("note", "tester");
  6206. res = cli_.Post("/person", params);
  6207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6208. ASSERT_EQ(StatusCode::OK_200, res->status);
  6209. res = cli_.Get("/person/john6");
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. ASSERT_EQ(StatusCode::OK_200, res->status);
  6212. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6213. ASSERT_EQ("tester", res->body);
  6214. Params delete_params;
  6215. delete_params.emplace("name", "john6");
  6216. Headers headers;
  6217. headers.emplace("Custom-Header", "test-value");
  6218. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. ASSERT_EQ(StatusCode::OK_200, res->status);
  6221. ASSERT_EQ("DELETED", res->body);
  6222. res = cli_.Get("/person/john6");
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6225. }
  6226. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6227. Params params;
  6228. params.emplace("json", JSON_DATA);
  6229. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. ASSERT_EQ(StatusCode::OK_200, res->status);
  6232. ASSERT_EQ(JSON_DATA, res->body);
  6233. }
  6234. TEST_F(ServerTest, PostEmptyContent) {
  6235. auto res = cli_.Post("/empty", "", "text/plain");
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. ASSERT_EQ(StatusCode::OK_200, res->status);
  6238. ASSERT_EQ("empty", res->body);
  6239. }
  6240. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6241. auto res = cli_.Post("/empty-no-content-type");
  6242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6243. ASSERT_EQ(StatusCode::OK_200, res->status);
  6244. ASSERT_EQ("empty-no-content-type", res->body);
  6245. }
  6246. TEST_F(ServerTest, PostPathOnly) {
  6247. auto res = cli_.Post("/path-only");
  6248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6249. ASSERT_EQ(StatusCode::OK_200, res->status);
  6250. ASSERT_EQ("path-only", res->body);
  6251. }
  6252. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6253. auto res = cli_.Post("/path-headers-only",
  6254. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. ASSERT_EQ(StatusCode::OK_200, res->status);
  6257. ASSERT_EQ("path-headers-only", res->body);
  6258. }
  6259. TEST_F(ServerTest, PostLarge) {
  6260. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6262. ASSERT_EQ(StatusCode::OK_200, res->status);
  6263. EXPECT_EQ(LARGE_DATA, res->body);
  6264. }
  6265. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6266. auto res = cli_.Put("/empty-no-content-type");
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. ASSERT_EQ(StatusCode::OK_200, res->status);
  6269. ASSERT_EQ("empty-no-content-type", res->body);
  6270. }
  6271. TEST_F(ServerTest, GetMethodDir) {
  6272. auto res = cli_.Get("/dir/");
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6276. auto body = R"(<html>
  6277. <head>
  6278. </head>
  6279. <body>
  6280. <a href="/dir/test.html">Test</a>
  6281. <a href="/hi">hi</a>
  6282. </body>
  6283. </html>
  6284. )";
  6285. EXPECT_EQ(body, res->body);
  6286. }
  6287. TEST_F(ServerTest, GetMethodDirTest) {
  6288. auto res = cli_.Get("/dir/test.html");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. EXPECT_EQ(StatusCode::OK_200, res->status);
  6291. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6292. EXPECT_EQ("test.html", res->body);
  6293. }
  6294. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6295. auto res = cli_.Get("/dir/../dir/test.html");
  6296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6297. EXPECT_EQ(StatusCode::OK_200, res->status);
  6298. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6299. EXPECT_EQ("test.html", res->body);
  6300. }
  6301. TEST_F(ServerTest, GetMethodInvalidPath) {
  6302. auto res = cli_.Get("/dir/../test.html");
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6305. }
  6306. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6307. auto res = cli_.Get("/../www/dir/test.html");
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6310. }
  6311. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6312. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6315. }
  6316. TEST_F(ServerTest, GetMethodDirMountTest) {
  6317. auto res = cli_.Get("/mount/dir/test.html");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. EXPECT_EQ(StatusCode::OK_200, res->status);
  6320. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6321. EXPECT_EQ("test.html", res->body);
  6322. }
  6323. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6324. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. EXPECT_EQ(StatusCode::OK_200, res->status);
  6327. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6328. EXPECT_EQ("test.html", res->body);
  6329. }
  6330. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6331. auto res = cli_.Get("/mount/dir/../test.html");
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6334. }
  6335. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6336. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6338. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6339. }
  6340. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6341. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6343. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6344. }
  6345. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6346. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6349. }
  6350. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6351. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6354. }
  6355. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6356. auto res = cli_.Get("/mount/dir");
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6359. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6360. }
  6361. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6362. auto res = cli_.Get("//dir");
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6365. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6366. }
  6367. TEST_F(ServerTest, PostMethod303) {
  6368. auto res = cli_.Post("/1", "body", "text/plain");
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6371. EXPECT_EQ("/2", res->get_header_value("Location"));
  6372. }
  6373. TEST_F(ServerTest, PostMethod303Redirect) {
  6374. cli_.set_follow_location(true);
  6375. auto res = cli_.Post("/1", "body", "text/plain");
  6376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6377. EXPECT_EQ(StatusCode::OK_200, res->status);
  6378. EXPECT_EQ("redirected.", res->body);
  6379. EXPECT_EQ("/2", res->location);
  6380. }
  6381. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6382. auto res = cli_.Get("/dir/test.abcde");
  6383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6384. EXPECT_EQ(StatusCode::OK_200, res->status);
  6385. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6386. EXPECT_EQ("abcde", res->body);
  6387. }
  6388. TEST_F(ServerTest, StaticFileRange) {
  6389. auto res =
  6390. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6393. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6394. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6395. EXPECT_EQ(true, res->has_header("Content-Range"));
  6396. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6397. EXPECT_EQ(std::string("cd"), res->body);
  6398. }
  6399. TEST_F(ServerTest, StaticFileRanges) {
  6400. auto res = cli_.Get("/dir/test.abcde",
  6401. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6404. EXPECT_TRUE(
  6405. res->get_header_value("Content-Type")
  6406. .find(
  6407. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6408. 0);
  6409. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6410. }
  6411. TEST_F(ServerTest, StaticFileRangeHead) {
  6412. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6414. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6415. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6416. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6417. EXPECT_EQ(true, res->has_header("Content-Range"));
  6418. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6419. }
  6420. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6421. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6423. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6424. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6425. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6426. EXPECT_EQ(true, res->has_header("Content-Range"));
  6427. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6428. res->get_header_value("Content-Range"));
  6429. EXPECT_EQ("LAST\n", res->body);
  6430. }
  6431. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6432. auto res =
  6433. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6435. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6436. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6437. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6438. EXPECT_EQ(true, res->has_header("Content-Range"));
  6439. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6440. }
  6441. TEST_F(ServerTest, StaticFileBigFile) {
  6442. auto res = cli_.Get("/dir/1MB.txt");
  6443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6444. EXPECT_EQ(StatusCode::OK_200, res->status);
  6445. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6446. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6447. }
  6448. TEST_F(ServerTest, InvalidBaseDirMount) {
  6449. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6450. }
  6451. TEST_F(ServerTest, Binary) {
  6452. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6453. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6454. "application/octet-stream");
  6455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6456. ASSERT_EQ(StatusCode::OK_200, res->status);
  6457. ASSERT_EQ(4U, res->body.size());
  6458. res = cli_.Put("/binary", binary.data(), binary.size(),
  6459. "application/octet-stream");
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. ASSERT_EQ(StatusCode::OK_200, res->status);
  6462. ASSERT_EQ(4U, res->body.size());
  6463. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6464. "application/octet-stream");
  6465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6466. ASSERT_EQ(StatusCode::OK_200, res->status);
  6467. ASSERT_EQ(4U, res->body.size());
  6468. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6469. "application/octet-stream");
  6470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6471. ASSERT_EQ(StatusCode::OK_200, res->status);
  6472. ASSERT_EQ(4U, res->body.size());
  6473. }
  6474. TEST_F(ServerTest, BinaryString) {
  6475. auto binary = std::string("\x00\x01\x02\x03", 4);
  6476. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6478. ASSERT_EQ(StatusCode::OK_200, res->status);
  6479. ASSERT_EQ(4U, res->body.size());
  6480. res = cli_.Put("/binary", binary, "application/octet-stream");
  6481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6482. ASSERT_EQ(StatusCode::OK_200, res->status);
  6483. ASSERT_EQ(4U, res->body.size());
  6484. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. ASSERT_EQ(StatusCode::OK_200, res->status);
  6487. ASSERT_EQ(4U, res->body.size());
  6488. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. ASSERT_EQ(StatusCode::OK_200, res->status);
  6491. ASSERT_EQ(4U, res->body.size());
  6492. }
  6493. TEST_F(ServerTest, EmptyRequest) {
  6494. auto res = cli_.Get("");
  6495. ASSERT_TRUE(!res);
  6496. EXPECT_EQ(Error::Connection, res.error());
  6497. }
  6498. TEST_F(ServerTest, LongRequest) {
  6499. std::string request;
  6500. for (size_t i = 0; i < 545; i++) {
  6501. request += "/TooLongRequest";
  6502. }
  6503. request += "OK";
  6504. auto res = cli_.Get(request.c_str());
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6507. }
  6508. TEST_F(ServerTest, TooLongRequest) {
  6509. std::string request;
  6510. for (size_t i = 0; i < 546; i++) {
  6511. request += "/TooLongRequest";
  6512. }
  6513. request += "_NG";
  6514. auto start = std::chrono::high_resolution_clock::now();
  6515. cli_.set_keep_alive(true);
  6516. auto res = cli_.Get(request.c_str());
  6517. auto end = std::chrono::high_resolution_clock::now();
  6518. auto elapsed =
  6519. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6520. .count();
  6521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6522. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6523. EXPECT_LE(elapsed, 1000);
  6524. EXPECT_EQ("close", res->get_header_value("Connection"));
  6525. EXPECT_FALSE(cli_.is_socket_open());
  6526. }
  6527. TEST_F(ServerTest, AlmostTooLongRequest) {
  6528. // test for #2046 - URI length check shouldn't include other content on req
  6529. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6530. // leading /, space, HTTP/1.1)
  6531. std::string request =
  6532. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6533. auto res = cli_.Get(request.c_str());
  6534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6536. }
  6537. TEST_F(ServerTest, LongHeader) {
  6538. Request req;
  6539. req.method = "GET";
  6540. req.path = "/hi";
  6541. std::string host_and_port;
  6542. host_and_port += HOST;
  6543. host_and_port += ":";
  6544. host_and_port += std::to_string(PORT);
  6545. req.headers.emplace("Host", host_and_port.c_str());
  6546. req.headers.emplace("Accept", "*/*");
  6547. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6548. req.headers.emplace(
  6549. "Header-Name",
  6550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6578. "@@@@@@@@@@@@@@@@");
  6579. auto res = std::make_shared<Response>();
  6580. auto error = Error::Success;
  6581. auto ret = cli_.send(req, *res, error);
  6582. ASSERT_TRUE(ret);
  6583. EXPECT_EQ(StatusCode::OK_200, res->status);
  6584. }
  6585. TEST_F(ServerTest, LongQueryValue) {
  6586. auto start = std::chrono::high_resolution_clock::now();
  6587. cli_.set_keep_alive(true);
  6588. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6589. auto end = std::chrono::high_resolution_clock::now();
  6590. auto elapsed =
  6591. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6592. .count();
  6593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6594. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6595. EXPECT_LE(elapsed, 1000);
  6596. EXPECT_EQ("close", res->get_header_value("Connection"));
  6597. EXPECT_FALSE(cli_.is_socket_open());
  6598. }
  6599. TEST_F(ServerTest, TooLongQueryValue) {
  6600. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6601. ASSERT_FALSE(res);
  6602. EXPECT_EQ(Error::Read, res.error());
  6603. }
  6604. TEST_F(ServerTest, TooLongHeader) {
  6605. Request req;
  6606. req.method = "GET";
  6607. req.path = "/hi";
  6608. std::string host_and_port;
  6609. host_and_port += HOST;
  6610. host_and_port += ":";
  6611. host_and_port += std::to_string(PORT);
  6612. req.headers.emplace("Host", host_and_port.c_str());
  6613. req.headers.emplace("Accept", "*/*");
  6614. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6615. req.headers.emplace(
  6616. "Header-Name",
  6617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6645. "@@@@@@@@@@@@@@@@@");
  6646. auto res = std::make_shared<Response>();
  6647. auto error = Error::Success;
  6648. auto ret = cli_.send(req, *res, error);
  6649. ASSERT_TRUE(ret);
  6650. EXPECT_EQ(StatusCode::OK_200, res->status);
  6651. }
  6652. TEST_F(ServerTest, HeaderCountAtLimit) {
  6653. // Test with headers just under the 100 limit
  6654. httplib::Headers headers;
  6655. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6656. // This should keep us just under the 100 header limit
  6657. for (int i = 0; i < 95; i++) {
  6658. std::string name = "X-Test-Header-" + std::to_string(i);
  6659. std::string value = "value" + std::to_string(i);
  6660. headers.emplace(name, value);
  6661. }
  6662. // This should work fine as we're under the limit
  6663. auto res = cli_.Get("/hi", headers);
  6664. EXPECT_TRUE(res);
  6665. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6666. }
  6667. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6668. // Test with many headers to exceed the 100 limit
  6669. httplib::Headers headers;
  6670. // Add 150 headers to definitely exceed the 100 limit
  6671. for (int i = 0; i < 150; i++) {
  6672. std::string name = "X-Test-Header-" + std::to_string(i);
  6673. std::string value = "value" + std::to_string(i);
  6674. headers.emplace(name, value);
  6675. }
  6676. // This should fail due to exceeding header count limit
  6677. cli_.set_keep_alive(true);
  6678. auto res = cli_.Get("/hi", headers);
  6679. // The server should respond with 400 Bad Request
  6680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6681. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6682. EXPECT_EQ("close", res->get_header_value("Connection"));
  6683. EXPECT_FALSE(cli_.is_socket_open());
  6684. }
  6685. TEST_F(ServerTest, PercentEncoding) {
  6686. auto res = cli_.Get("/e%6edwith%");
  6687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6688. EXPECT_EQ(StatusCode::OK_200, res->status);
  6689. }
  6690. TEST_F(ServerTest, PercentEncodingUnicode) {
  6691. auto res = cli_.Get("/e%u006edwith%");
  6692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6693. EXPECT_EQ(StatusCode::OK_200, res->status);
  6694. }
  6695. TEST_F(ServerTest, InvalidPercentEncoding) {
  6696. auto res = cli_.Get("/%endwith%");
  6697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6698. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6699. }
  6700. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6701. auto res = cli_.Get("/%uendwith%");
  6702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6703. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6704. }
  6705. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6706. auto res = cli_.Get("/hello?aaa=bbb%");
  6707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6709. }
  6710. TEST_F(ServerTest, PlusSignEncoding) {
  6711. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_EQ(StatusCode::OK_200, res->status);
  6714. EXPECT_EQ("a +b", res->body);
  6715. }
  6716. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6717. // This test simulates a potential DoS attack using many headers
  6718. // to verify our security fix prevents memory exhaustion
  6719. httplib::Headers attack_headers;
  6720. // Attempt to add many headers like an attacker would (200 headers to far
  6721. // exceed limit)
  6722. for (int i = 0; i < 200; i++) {
  6723. std::string name = "X-Attack-Header-" + std::to_string(i);
  6724. std::string value = "attack_payload_" + std::to_string(i);
  6725. attack_headers.emplace(name, value);
  6726. }
  6727. // Try to POST with excessive headers
  6728. cli_.set_keep_alive(true);
  6729. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6730. // Should either fail or return 400 Bad Request due to security limit
  6731. if (res) {
  6732. // If we get a response, it should be 400 Bad Request
  6733. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6734. EXPECT_EQ("close", res->get_header_value("Connection"));
  6735. }
  6736. EXPECT_FALSE(cli_.is_socket_open());
  6737. }
  6738. TEST_F(ServerTest, MultipartFormData) {
  6739. UploadFormDataItems items = {
  6740. {"text1", "text default", "", ""},
  6741. {"text2", "aωb", "", ""},
  6742. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6743. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6744. {"file3", "", "", "application/octet-stream"},
  6745. {"file4", "", "", " application/json tmp-string "}};
  6746. auto res = cli_.Post("/multipart", items);
  6747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6748. EXPECT_EQ(StatusCode::OK_200, res->status);
  6749. }
  6750. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6751. UploadFormDataItems items = {
  6752. {"text", "default text", "", ""},
  6753. {"multi_text1", "aaaaa", "", ""},
  6754. {"multi_text1", "bbbbb", "", ""},
  6755. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6756. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6757. "application/json"},
  6758. };
  6759. auto res = cli_.Post("/multipart/multi_file_values", items);
  6760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6761. EXPECT_EQ(StatusCode::OK_200, res->status);
  6762. }
  6763. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6764. auto res = cli_.Get("/hi");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6768. EXPECT_EQ("Hello World!", res->body);
  6769. }
  6770. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6771. Request req;
  6772. req.method = "POST";
  6773. req.path = "/chunked";
  6774. std::string host_and_port;
  6775. host_and_port += HOST;
  6776. host_and_port += ":";
  6777. host_and_port += std::to_string(PORT);
  6778. req.headers.emplace("Host", host_and_port.c_str());
  6779. req.headers.emplace("Accept", "*/*");
  6780. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6781. req.headers.emplace("Content-Type", "text/plain");
  6782. req.headers.emplace("Content-Length", "0");
  6783. req.headers.emplace(
  6784. "Transfer-Encoding",
  6785. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6786. // Client does not chunk, so make a chunked body manually.
  6787. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6788. auto res = std::make_shared<Response>();
  6789. auto error = Error::Success;
  6790. auto ret = cli_.send(req, *res, error);
  6791. ASSERT_TRUE(ret);
  6792. EXPECT_EQ(StatusCode::OK_200, res->status);
  6793. }
  6794. template <typename ClientT>
  6795. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6796. int expected_status) {
  6797. Request req;
  6798. req.method = "POST";
  6799. req.path = "/chunked";
  6800. std::string host_and_port;
  6801. host_and_port += HOST;
  6802. host_and_port += ":";
  6803. host_and_port += std::to_string(PORT);
  6804. req.headers.emplace("Host", host_and_port.c_str());
  6805. req.headers.emplace("Content-Length", "0");
  6806. req.headers.emplace("Transfer-Encoding", "chunked");
  6807. req.body = body;
  6808. auto res = std::make_shared<Response>();
  6809. auto error = Error::Success;
  6810. ASSERT_TRUE(cli.send(req, *res, error));
  6811. EXPECT_EQ(expected_status, res->status);
  6812. }
  6813. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6814. // rather than treat them as valid lengths.
  6815. template <typename ClientT>
  6816. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6817. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6818. }
  6819. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6820. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6821. }
  6822. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6823. expect_chunked_body_rejected(
  6824. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6825. }
  6826. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6827. // chunk-size line carries no CR, LF or other control character ahead of its
  6828. // terminator. Such a line must be refused rather than read as extension text.
  6829. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6830. expect_chunked_body_rejected(
  6831. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6832. }
  6833. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6834. expect_chunked_body_rejected(
  6835. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6836. }
  6837. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6838. expect_chunked_body_rejected(
  6839. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6840. }
  6841. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6842. // The literal stays split: a hex escape consumes every hex digit that
  6843. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6844. expect_chunked_body_rejected(
  6845. cli_, "4;a\x01"
  6846. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6847. }
  6848. TEST_F(ServerTest, AcceptsChunkExtension) {
  6849. expect_chunked_body_status(cli_,
  6850. "4;name=value\r\ndech\r\n"
  6851. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6852. "0;last\r\n\r\n",
  6853. StatusCode::OK_200);
  6854. }
  6855. TEST_F(ServerTest, GetStreamed2) {
  6856. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6858. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6859. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6860. EXPECT_EQ(true, res->has_header("Content-Range"));
  6861. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6862. EXPECT_EQ(std::string("ab"), res->body);
  6863. }
  6864. TEST_F(ServerTest, GetStreamed) {
  6865. auto res = cli_.Get("/streamed");
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6869. EXPECT_EQ(std::string("aaabbb"), res->body);
  6870. }
  6871. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6872. auto res = cli_.Get("/streamed-without-length",
  6873. Headers{make_range_header({{0, -1}})});
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. EXPECT_EQ(false, res->has_header("Content-Length"));
  6877. EXPECT_EQ(false, res->has_header("Content-Range"));
  6878. EXPECT_EQ(std::string("abcdefg"), res->body);
  6879. }
  6880. TEST_F(ServerTest, GetStreamedWithRange1) {
  6881. auto res =
  6882. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6884. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6885. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6886. EXPECT_EQ(true, res->has_header("Content-Range"));
  6887. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6888. EXPECT_EQ(std::string("def"), res->body);
  6889. }
  6890. TEST_F(ServerTest, GetStreamedWithRange2) {
  6891. auto res =
  6892. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6895. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6896. EXPECT_EQ(true, res->has_header("Content-Range"));
  6897. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6898. EXPECT_EQ(std::string("bcdefg"), res->body);
  6899. }
  6900. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6901. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6904. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6905. EXPECT_EQ(true, res->has_header("Content-Range"));
  6906. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6907. EXPECT_EQ(std::string("efg"), res->body);
  6908. }
  6909. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6910. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6911. // the entire representation.
  6912. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6913. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6915. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6916. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6917. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6918. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6919. }
  6920. }
  6921. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6922. auto res =
  6923. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6925. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6926. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6927. EXPECT_EQ(false, res->has_header("Content-Range"));
  6928. EXPECT_EQ(0U, res->body.size());
  6929. }
  6930. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6931. // Only a 206 is served as a partial representation. Under any other status
  6932. // `apply_ranges()` reported the full content length, so the body must match
  6933. // that header, and the content provider must never be asked for an offset
  6934. // outside the representation.
  6935. auto check = [&](int status, const char *range) {
  6936. auto path =
  6937. std::string("/streamed-with-range?status=") + std::to_string(status);
  6938. auto ctx = path + " Range: " + range;
  6939. auto res = cli_.Get(path, Headers{{"Range", range}});
  6940. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6941. EXPECT_EQ(status, res->status) << ctx;
  6942. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6944. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6945. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6946. };
  6947. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6948. check(403, "bytes=3-5");
  6949. // The offset is far past the representation.
  6950. check(403, "bytes=100000-100200");
  6951. // `first_pos` is still -1 here, and the bounds asserts in
  6952. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6953. check(403, "bytes=-3");
  6954. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6955. // multipart branch would have written one that is empty.
  6956. check(403, "bytes=1-2, 4-5");
  6957. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6958. // covers the whole representation.
  6959. check(200, "bytes=3-5");
  6960. check(200, "bytes=1-2, 4-5");
  6961. }
  6962. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6963. auto res =
  6964. cli_.Get("/streamed-with-range",
  6965. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6966. "92233720368547758079223372036854775807"}});
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6969. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6970. EXPECT_EQ(false, res->has_header("Content-Range"));
  6971. EXPECT_EQ(0U, res->body.size());
  6972. }
  6973. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6974. auto res = cli_.Get(
  6975. "/with-range",
  6976. Headers{{"Range",
  6977. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6978. {"Accept-Encoding", ""}});
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6981. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6982. EXPECT_EQ(true, res->has_header("Content-Range"));
  6983. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6984. EXPECT_EQ(std::string("abcdefg"), res->body);
  6985. }
  6986. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6987. auto res = cli_.Get("/with-range", Headers{
  6988. {"Range", "bytes=0-"},
  6989. {"Accept-Encoding", ""},
  6990. });
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6993. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6994. EXPECT_EQ(true, res->has_header("Content-Range"));
  6995. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6996. EXPECT_EQ(std::string("abcdefg"), res->body);
  6997. }
  6998. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6999. auto res = cli_.Get("/streamed-with-range",
  7000. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7003. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7004. EXPECT_EQ(false, res->has_header("Content-Range"));
  7005. EXPECT_EQ(267U, res->body.size());
  7006. // Check that both range contents are present
  7007. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7008. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7009. // Check that Content-Range headers are present for both ranges
  7010. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7011. std::string::npos);
  7012. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7013. std::string::npos);
  7014. }
  7015. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7016. Ranges ranges;
  7017. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7018. ranges.emplace_back(0, -1);
  7019. }
  7020. auto res = cli_.Get("/streamed-with-range?error",
  7021. Headers{{make_range_header(ranges)}});
  7022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7023. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7024. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7025. EXPECT_EQ(false, res->has_header("Content-Range"));
  7026. EXPECT_EQ(0U, res->body.size());
  7027. }
  7028. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7029. auto res = cli_.Get("/streamed-with-range",
  7030. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7033. EXPECT_EQ(5U, res->body.size());
  7034. // Check that overlapping ranges are coalesced into a single range
  7035. EXPECT_EQ("bcdef", res->body);
  7036. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7037. // Should be single range, not multipart
  7038. EXPECT_TRUE(res->has_header("Content-Range"));
  7039. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7040. }
  7041. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7042. auto res = cli_.Get("/streamed-with-range",
  7043. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7046. EXPECT_EQ(268U, res->body.size());
  7047. // Check that both range contents are present
  7048. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7049. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7050. // Check that Content-Range headers are present for both ranges
  7051. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7052. std::string::npos);
  7053. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7054. std::string::npos);
  7055. }
  7056. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7057. auto res = cli_.Get("/streamed-with-range",
  7058. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7061. EXPECT_EQ(269U, res->body.size());
  7062. // Check that both duplicate range contents are present
  7063. size_t first_abc = res->body.find("abc\r\n");
  7064. EXPECT_TRUE(first_abc != std::string::npos);
  7065. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7066. EXPECT_TRUE(second_abc != std::string::npos);
  7067. // Check that Content-Range headers are present for both ranges
  7068. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7069. EXPECT_TRUE(first_range != std::string::npos);
  7070. size_t second_range =
  7071. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7072. EXPECT_TRUE(second_range != std::string::npos);
  7073. }
  7074. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7075. auto res =
  7076. cli_.Get("/streamed-with-range?error",
  7077. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7079. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7080. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7081. EXPECT_EQ(false, res->has_header("Content-Range"));
  7082. EXPECT_EQ(0U, res->body.size());
  7083. }
  7084. TEST_F(ServerTest, GetStreamedEndless) {
  7085. uint64_t offset = 0;
  7086. auto res = cli_.Get("/streamed-cancel",
  7087. [&](const char * /*data*/, uint64_t data_length) {
  7088. if (offset < 100) {
  7089. offset += data_length;
  7090. return true;
  7091. }
  7092. return false;
  7093. });
  7094. ASSERT_TRUE(!res);
  7095. EXPECT_EQ(Error::Canceled, res.error());
  7096. }
  7097. TEST_F(ServerTest, ClientStop) {
  7098. std::atomic_size_t count{4};
  7099. std::vector<std::thread> threads;
  7100. for (auto i = count.load(); i != 0; --i) {
  7101. threads.emplace_back([&]() {
  7102. auto res = cli_.Get("/streamed-cancel",
  7103. [&](const char *, uint64_t) { return true; });
  7104. --count;
  7105. ASSERT_TRUE(!res);
  7106. EXPECT_TRUE(res.error() == Error::Canceled ||
  7107. res.error() == Error::Read || res.error() == Error::Write);
  7108. });
  7109. }
  7110. std::this_thread::sleep_for(std::chrono::seconds(2));
  7111. while (count != 0) {
  7112. cli_.stop();
  7113. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7114. }
  7115. for (auto &t : threads) {
  7116. t.join();
  7117. }
  7118. }
  7119. TEST_F(ServerTest, GetWithRange1) {
  7120. auto res = cli_.Get("/with-range", Headers{
  7121. make_range_header({{3, 5}}),
  7122. {"Accept-Encoding", ""},
  7123. });
  7124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7125. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7126. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7127. EXPECT_EQ(true, res->has_header("Content-Range"));
  7128. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7129. EXPECT_EQ(std::string("def"), res->body);
  7130. }
  7131. TEST_F(ServerTest, GetWithRange2) {
  7132. auto res = cli_.Get("/with-range", Headers{
  7133. make_range_header({{1, -1}}),
  7134. {"Accept-Encoding", ""},
  7135. });
  7136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7137. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7138. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7139. EXPECT_EQ(true, res->has_header("Content-Range"));
  7140. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7141. EXPECT_EQ(std::string("bcdefg"), res->body);
  7142. }
  7143. TEST_F(ServerTest, GetWithRange3) {
  7144. auto res = cli_.Get("/with-range", Headers{
  7145. make_range_header({{0, 0}}),
  7146. {"Accept-Encoding", ""},
  7147. });
  7148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7149. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7150. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7151. EXPECT_EQ(true, res->has_header("Content-Range"));
  7152. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7153. EXPECT_EQ(std::string("a"), res->body);
  7154. }
  7155. TEST_F(ServerTest, GetWithRange4) {
  7156. auto res = cli_.Get("/with-range", Headers{
  7157. make_range_header({{-1, 2}}),
  7158. {"Accept-Encoding", ""},
  7159. });
  7160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7161. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7162. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7163. EXPECT_EQ(true, res->has_header("Content-Range"));
  7164. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7165. EXPECT_EQ(std::string("fg"), res->body);
  7166. }
  7167. TEST_F(ServerTest, GetWithRange5) {
  7168. auto res = cli_.Get("/with-range", Headers{
  7169. make_range_header({{0, 5}}),
  7170. {"Accept-Encoding", ""},
  7171. });
  7172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7174. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7175. EXPECT_EQ(true, res->has_header("Content-Range"));
  7176. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7177. EXPECT_EQ(std::string("abcdef"), res->body);
  7178. }
  7179. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7180. auto res =
  7181. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7183. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7184. }
  7185. TEST_F(ServerTest, GetWithRangeMultipart) {
  7186. auto res =
  7187. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7189. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7190. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7191. EXPECT_EQ(false, res->has_header("Content-Range"));
  7192. EXPECT_EQ(267U, res->body.size());
  7193. }
  7194. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7195. auto res = cli_.Get("/with-range",
  7196. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7198. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7199. }
  7200. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7201. auto res = cli_.Get("/with-range-customized-response",
  7202. Headers{{make_range_header({{1, 2}})}});
  7203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7204. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7205. EXPECT_EQ(true, res->has_header("Content-Length"));
  7206. EXPECT_EQ(false, res->has_header("Content-Range"));
  7207. EXPECT_EQ(JSON_DATA, res->body);
  7208. }
  7209. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7210. auto res = cli_.Get("/with-range-customized-response",
  7211. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7213. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7214. EXPECT_EQ(true, res->has_header("Content-Length"));
  7215. EXPECT_EQ(false, res->has_header("Content-Range"));
  7216. EXPECT_EQ(JSON_DATA, res->body);
  7217. }
  7218. TEST_F(ServerTest, Issue1772) {
  7219. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7221. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7222. }
  7223. TEST_F(ServerTest, Issue609) {
  7224. auto res = cli_.Delete("/issue609");
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::OK_200, res->status);
  7227. EXPECT_EQ(std::string("ok"), res->body);
  7228. }
  7229. TEST_F(ServerTest, GetStreamedChunked) {
  7230. auto res = cli_.Get("/streamed-chunked");
  7231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7232. EXPECT_EQ(StatusCode::OK_200, res->status);
  7233. EXPECT_EQ(std::string("123456789"), res->body);
  7234. }
  7235. TEST_F(ServerTest, GetStreamedChunked2) {
  7236. auto res = cli_.Get("/streamed-chunked2");
  7237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7238. EXPECT_EQ(StatusCode::OK_200, res->status);
  7239. EXPECT_EQ(std::string("123456789"), res->body);
  7240. }
  7241. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7242. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ(std::string("123456789"), res->body);
  7246. EXPECT_TRUE(res->has_header("Trailer"));
  7247. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7248. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7249. // Trailers are now stored separately from headers (security fix)
  7250. EXPECT_EQ(2U, res->trailers.size());
  7251. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7252. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7253. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7254. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7255. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7256. // Verify trailers are NOT in headers (security verification)
  7257. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7258. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7259. }
  7260. TEST_F(ServerTest, LargeChunkedPost) {
  7261. Request req;
  7262. req.method = "POST";
  7263. req.path = "/large-chunked";
  7264. std::string host_and_port;
  7265. host_and_port += HOST;
  7266. host_and_port += ":";
  7267. host_and_port += std::to_string(PORT);
  7268. req.headers.emplace("Host", host_and_port.c_str());
  7269. req.headers.emplace("Accept", "*/*");
  7270. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7271. req.headers.emplace("Content-Type", "text/plain");
  7272. req.headers.emplace("Content-Length", "0");
  7273. req.headers.emplace("Transfer-Encoding", "chunked");
  7274. std::string long_string(30 * 1024u, 'a');
  7275. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7276. // Attempt to make a large enough post to exceed OS buffers, to test that
  7277. // the server handles short reads if the full chunk data isn't available.
  7278. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7279. auto res = std::make_shared<Response>();
  7280. auto error = Error::Success;
  7281. auto ret = cli_.send(req, *res, error);
  7282. ASSERT_TRUE(ret);
  7283. EXPECT_EQ(StatusCode::OK_200, res->status);
  7284. }
  7285. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7286. auto res = cli_.Get("/remote_addr");
  7287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7288. EXPECT_EQ(StatusCode::OK_200, res->status);
  7289. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7290. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7291. }
  7292. TEST_F(ServerTest, GetMethodLocalAddr) {
  7293. auto res = cli_.Get("/local_addr");
  7294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7295. EXPECT_EQ(StatusCode::OK_200, res->status);
  7296. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7297. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7298. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7299. }
  7300. TEST_F(ServerTest, HTTPResponseSplitting) {
  7301. auto res = cli_.Get("/http_response_splitting");
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. }
  7305. TEST_F(ServerTest, SlowRequest) {
  7306. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7307. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7308. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7309. }
  7310. #if 0
  7311. TEST_F(ServerTest, SlowPost) {
  7312. char buffer[64 * 1024];
  7313. memset(buffer, 0x42, sizeof(buffer));
  7314. auto res = cli_.Post(
  7315. "/slowpost", 64 * 1024 * 1024,
  7316. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7317. auto ret = sink.write(buffer, sizeof(buffer));
  7318. EXPECT_TRUE(ret);
  7319. return true;
  7320. },
  7321. "text/plain");
  7322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7323. EXPECT_EQ(StatusCode::OK_200, res->status);
  7324. }
  7325. TEST_F(ServerTest, SlowPostFail) {
  7326. char buffer[64 * 1024];
  7327. memset(buffer, 0x42, sizeof(buffer));
  7328. cli_.set_write_timeout(std::chrono::seconds(0));
  7329. auto res = cli_.Post(
  7330. "/slowpost", 64 * 1024 * 1024,
  7331. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7332. sink.write(buffer, sizeof(buffer));
  7333. return true;
  7334. },
  7335. "text/plain");
  7336. ASSERT_TRUE(!res);
  7337. EXPECT_EQ(Error::Write, res.error());
  7338. }
  7339. #endif
  7340. TEST_F(ServerTest, Put) {
  7341. auto res = cli_.Put("/put", "PUT", "text/plain");
  7342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7343. EXPECT_EQ(StatusCode::OK_200, res->status);
  7344. EXPECT_EQ("PUT", res->body);
  7345. }
  7346. TEST_F(ServerTest, PutWithContentProvider) {
  7347. auto res = cli_.Put(
  7348. "/put", 3,
  7349. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7350. sink.os << "PUT";
  7351. return true;
  7352. },
  7353. "text/plain");
  7354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7355. EXPECT_EQ(StatusCode::OK_200, res->status);
  7356. EXPECT_EQ("PUT", res->body);
  7357. }
  7358. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7359. auto res = cli_.Post(
  7360. "/post", 42,
  7361. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7362. return false;
  7363. },
  7364. "text/plain");
  7365. ASSERT_TRUE(!res);
  7366. EXPECT_EQ(Error::Canceled, res.error());
  7367. }
  7368. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7369. auto res = cli_.Put(
  7370. "/put",
  7371. [](size_t /*offset*/, DataSink &sink) {
  7372. sink.os << "PUT";
  7373. sink.done();
  7374. return true;
  7375. },
  7376. "text/plain");
  7377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7378. EXPECT_EQ(StatusCode::OK_200, res->status);
  7379. EXPECT_EQ("PUT", res->body);
  7380. }
  7381. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7382. auto res = cli_.Post(
  7383. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7384. "text/plain");
  7385. ASSERT_TRUE(!res);
  7386. EXPECT_EQ(Error::Canceled, res.error());
  7387. }
  7388. TEST_F(ServerTest, PostLoopBack) {
  7389. std::string body;
  7390. auto res = cli_.Post(
  7391. "/post-loopback", 9,
  7392. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7393. EXPECT_EQ(9u, length);
  7394. sink.write("123", 3);
  7395. sink.write("456", 3);
  7396. sink.write("789", 3);
  7397. return true;
  7398. },
  7399. "text/plain",
  7400. [&body](const char *data, size_t data_length) {
  7401. body.append(data, data_length);
  7402. return true;
  7403. });
  7404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7405. EXPECT_EQ(StatusCode::OK_200, res->status);
  7406. EXPECT_EQ("123456789", body);
  7407. }
  7408. TEST_F(ServerTest, PutLoopBack) {
  7409. std::string body;
  7410. auto res = cli_.Put(
  7411. "/put-loopback", 9,
  7412. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7413. EXPECT_EQ(9u, length);
  7414. sink.write("123", 3);
  7415. sink.write("456", 3);
  7416. sink.write("789", 3);
  7417. return true;
  7418. },
  7419. "text/plain",
  7420. [&body](const char *data, size_t data_length) {
  7421. body.append(data, data_length);
  7422. return true;
  7423. });
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. EXPECT_EQ("123456789", body);
  7427. }
  7428. TEST_F(ServerTest, PatchLoopBack) {
  7429. std::string body;
  7430. auto res = cli_.Patch(
  7431. "/patch-loopback", 9,
  7432. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7433. EXPECT_EQ(9u, length);
  7434. sink.write("123", 3);
  7435. sink.write("456", 3);
  7436. sink.write("789", 3);
  7437. return true;
  7438. },
  7439. "text/plain",
  7440. [&body](const char *data, size_t data_length) {
  7441. body.append(data, data_length);
  7442. return true;
  7443. });
  7444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7445. EXPECT_EQ(StatusCode::OK_200, res->status);
  7446. EXPECT_EQ("123456789", body);
  7447. }
  7448. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7449. std::string body;
  7450. auto res = cli_.Post(
  7451. "/post-loopback",
  7452. [](size_t /*offset*/, DataSink &sink) {
  7453. sink.write("123", 3);
  7454. sink.write("456", 3);
  7455. sink.write("789", 3);
  7456. sink.done();
  7457. return true;
  7458. },
  7459. "text/plain",
  7460. [&body](const char *data, size_t data_length) {
  7461. body.append(data, data_length);
  7462. return true;
  7463. });
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ(StatusCode::OK_200, res->status);
  7466. EXPECT_EQ("123456789", body);
  7467. }
  7468. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7469. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7470. cli_.set_compress(true);
  7471. auto res = cli_.Put(
  7472. "/put", 3,
  7473. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7474. sink.os << "PUT";
  7475. return true;
  7476. },
  7477. "text/plain");
  7478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7479. EXPECT_EQ(StatusCode::OK_200, res->status);
  7480. EXPECT_EQ("PUT", res->body);
  7481. }
  7482. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7483. cli_.set_compress(true);
  7484. auto res = cli_.Post(
  7485. "/post", 42,
  7486. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7487. return false;
  7488. },
  7489. "text/plain");
  7490. ASSERT_TRUE(!res);
  7491. EXPECT_EQ(Error::Canceled, res.error());
  7492. }
  7493. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7494. cli_.set_compress(true);
  7495. auto res = cli_.Put(
  7496. "/put",
  7497. [](size_t /*offset*/, DataSink &sink) {
  7498. sink.os << "PUT";
  7499. sink.done();
  7500. return true;
  7501. },
  7502. "text/plain");
  7503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. EXPECT_EQ("PUT", res->body);
  7506. }
  7507. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7508. cli_.set_compress(true);
  7509. auto res = cli_.Post(
  7510. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7511. "text/plain");
  7512. ASSERT_TRUE(!res);
  7513. EXPECT_EQ(Error::Canceled, res.error());
  7514. }
  7515. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7516. cli_.set_compress(true);
  7517. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7519. EXPECT_EQ(StatusCode::OK_200, res->status);
  7520. EXPECT_EQ(LARGE_DATA, res->body);
  7521. }
  7522. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7523. #ifdef CPPHTTPLIB_SSL_ENABLED
  7524. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7525. Client cli(s.c_str());
  7526. cli.enable_server_certificate_verification(false);
  7527. #else
  7528. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7529. Client cli(s.c_str());
  7530. #endif
  7531. cli.set_compress(true);
  7532. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. EXPECT_EQ(StatusCode::OK_200, res->status);
  7535. EXPECT_EQ(LARGE_DATA, res->body);
  7536. // The compressed size should be less than a 10th of the original. May vary
  7537. // depending on the zlib library.
  7538. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7539. static_cast<uint64_t>(10 * 1024 * 1024));
  7540. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7541. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7542. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7543. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7544. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7545. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7546. #endif
  7547. }
  7548. TEST_F(ServerTest, PutContentWithDeflate) {
  7549. cli_.set_compress(false);
  7550. Headers headers;
  7551. headers.emplace("Content-Encoding", "deflate");
  7552. // PUT in deflate format:
  7553. auto res = cli_.Put("/put", headers,
  7554. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7556. EXPECT_EQ(StatusCode::OK_200, res->status);
  7557. EXPECT_EQ("PUT", res->body);
  7558. }
  7559. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7560. Headers headers;
  7561. headers.emplace("Accept-Encoding", "gzip, deflate");
  7562. auto res = cli_.Get("/streamed-chunked", headers);
  7563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7564. EXPECT_EQ(StatusCode::OK_200, res->status);
  7565. EXPECT_EQ(std::string("123456789"), res->body);
  7566. }
  7567. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7568. Headers headers;
  7569. headers.emplace("Accept-Encoding", "gzip, deflate");
  7570. auto res = cli_.Get("/streamed-chunked2", headers);
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. EXPECT_EQ(std::string("123456789"), res->body);
  7574. }
  7575. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7576. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7578. EXPECT_EQ(StatusCode::OK_200, res->status);
  7579. }
  7580. TEST(GzipDecompressor, ChunkedDecompression) {
  7581. std::string data;
  7582. for (size_t i = 0; i < 32 * 1024; ++i) {
  7583. data.push_back(static_cast<char>('a' + i % 26));
  7584. }
  7585. std::string compressed_data;
  7586. {
  7587. httplib::detail::gzip_compressor compressor;
  7588. bool result = compressor.compress(
  7589. data.data(), data.size(),
  7590. /*last=*/true,
  7591. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7592. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7593. compressed_data_size);
  7594. return true;
  7595. });
  7596. ASSERT_TRUE(result);
  7597. }
  7598. std::string decompressed_data;
  7599. {
  7600. httplib::detail::gzip_decompressor decompressor;
  7601. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7602. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7603. size_t chunk_size = 130;
  7604. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7605. chunk_begin += chunk_size) {
  7606. size_t current_chunk_size =
  7607. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7608. bool result = decompressor.decompress(
  7609. compressed_data.data() + chunk_begin, current_chunk_size,
  7610. [&](const char *decompressed_data_chunk,
  7611. size_t decompressed_data_chunk_size) {
  7612. decompressed_data.insert(decompressed_data.size(),
  7613. decompressed_data_chunk,
  7614. decompressed_data_chunk_size);
  7615. return true;
  7616. });
  7617. ASSERT_TRUE(result);
  7618. }
  7619. }
  7620. ASSERT_EQ(data, decompressed_data);
  7621. }
  7622. TEST(GzipDecompressor, DeflateDecompression) {
  7623. std::string original_text = "Raw deflate without gzip";
  7624. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7625. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7626. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7627. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7628. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7629. std::string decompressed_data;
  7630. {
  7631. httplib::detail::gzip_decompressor decompressor;
  7632. bool result = decompressor.decompress(
  7633. compressed_data.data(), compressed_data.size(),
  7634. [&](const char *decompressed_data_chunk,
  7635. size_t decompressed_data_chunk_size) {
  7636. decompressed_data.insert(decompressed_data.size(),
  7637. decompressed_data_chunk,
  7638. decompressed_data_chunk_size);
  7639. return true;
  7640. });
  7641. ASSERT_TRUE(result);
  7642. }
  7643. ASSERT_EQ(original_text, decompressed_data);
  7644. }
  7645. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7646. std::string original_text = "Raw deflate without gzip";
  7647. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7648. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7649. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7650. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7651. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7652. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7653. std::string decompressed_data;
  7654. {
  7655. httplib::detail::gzip_decompressor decompressor;
  7656. bool result = decompressor.decompress(
  7657. compressed_data.data(), compressed_data.size(),
  7658. [&](const char *decompressed_data_chunk,
  7659. size_t decompressed_data_chunk_size) {
  7660. decompressed_data.insert(decompressed_data.size(),
  7661. decompressed_data_chunk,
  7662. decompressed_data_chunk_size);
  7663. return true;
  7664. });
  7665. ASSERT_TRUE(result);
  7666. }
  7667. ASSERT_EQ(original_text, decompressed_data);
  7668. }
  7669. #endif
  7670. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7671. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7672. Headers headers;
  7673. headers.emplace("Accept-Encoding", "br");
  7674. auto res = cli_.Get("/streamed-chunked", headers);
  7675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7676. EXPECT_EQ(StatusCode::OK_200, res->status);
  7677. EXPECT_EQ(std::string("123456789"), res->body);
  7678. }
  7679. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7680. Headers headers;
  7681. headers.emplace("Accept-Encoding", "br");
  7682. auto res = cli_.Get("/streamed-chunked2", headers);
  7683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7684. EXPECT_EQ(StatusCode::OK_200, res->status);
  7685. EXPECT_EQ(std::string("123456789"), res->body);
  7686. }
  7687. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7688. cli_.set_compress(true);
  7689. auto res = cli_.Put(
  7690. "/put", 3,
  7691. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7692. sink.os << "PUT";
  7693. return true;
  7694. },
  7695. "text/plain");
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. EXPECT_EQ("PUT", res->body);
  7699. }
  7700. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7701. cli_.set_compress(true);
  7702. auto res = cli_.Put(
  7703. "/put",
  7704. [](size_t /*offset*/, DataSink &sink) {
  7705. sink.os << "PUT";
  7706. sink.done();
  7707. return true;
  7708. },
  7709. "text/plain");
  7710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7711. EXPECT_EQ(StatusCode::OK_200, res->status);
  7712. EXPECT_EQ("PUT", res->body);
  7713. }
  7714. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7715. cli_.set_compress(true);
  7716. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7718. EXPECT_EQ(StatusCode::OK_200, res->status);
  7719. EXPECT_EQ(LARGE_DATA, res->body);
  7720. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7721. }
  7722. #endif
  7723. TEST_F(ServerTest, Patch) {
  7724. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("PATCH", res->body);
  7728. }
  7729. TEST_F(ServerTest, Delete) {
  7730. auto res = cli_.Delete("/delete");
  7731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7732. EXPECT_EQ(StatusCode::OK_200, res->status);
  7733. EXPECT_EQ("DELETE", res->body);
  7734. }
  7735. TEST_F(ServerTest, DeleteContentReceiver) {
  7736. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7738. EXPECT_EQ(StatusCode::OK_200, res->status);
  7739. EXPECT_EQ("content", res->body);
  7740. }
  7741. TEST_F(ServerTest, Options) {
  7742. auto res = cli_.Options("*");
  7743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7744. EXPECT_EQ(StatusCode::OK_200, res->status);
  7745. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7746. EXPECT_TRUE(res->body.empty());
  7747. }
  7748. TEST_F(ServerTest, URL) {
  7749. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7751. EXPECT_EQ(StatusCode::OK_200, res->status);
  7752. }
  7753. TEST_F(ServerTest, ArrayParam) {
  7754. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7756. EXPECT_EQ(StatusCode::OK_200, res->status);
  7757. }
  7758. TEST_F(ServerTest, ArrayParamValues) {
  7759. auto res =
  7760. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. }
  7764. TEST_F(ServerTest, NoMultipleHeaders) {
  7765. Headers headers = {{"Content-Length", "5"}};
  7766. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7767. "text/plain");
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::OK_200, res->status);
  7770. }
  7771. TEST_F(ServerTest, PostContentReceiver) {
  7772. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7774. ASSERT_EQ(StatusCode::OK_200, res->status);
  7775. ASSERT_EQ("content", res->body);
  7776. }
  7777. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7778. UploadFormDataItems items = {
  7779. {"text1", "text default", "", ""},
  7780. {"text2", "aωb", "", ""},
  7781. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7782. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7783. {"file3", "", "", "application/octet-stream"},
  7784. };
  7785. auto res = cli_.Post("/content_receiver", items);
  7786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7787. EXPECT_EQ(StatusCode::OK_200, res->status);
  7788. }
  7789. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7790. UploadFormDataItems items = {
  7791. {"text1", "text default", "", ""},
  7792. {"text2", "aωb", "", ""},
  7793. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7794. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7795. {"file3", "", "", "application/octet-stream"},
  7796. };
  7797. auto boundary = std::string("+++++");
  7798. std::string body;
  7799. for (const auto &item : items) {
  7800. body += "--" + boundary + "\r\n";
  7801. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7802. if (!item.filename.empty()) {
  7803. body += "; filename=\"" + item.filename + "\"";
  7804. }
  7805. body += "\r\n";
  7806. if (!item.content_type.empty()) {
  7807. body += "Content-Type: " + item.content_type + "\r\n";
  7808. }
  7809. body += "\r\n";
  7810. body += item.content + "\r\n";
  7811. }
  7812. body += "--" + boundary + "--\r\n";
  7813. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7814. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7816. EXPECT_EQ(StatusCode::OK_200, res->status);
  7817. }
  7818. TEST(MultipartFormDataTest, FieldEscaping) {
  7819. Server svr;
  7820. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7821. const ContentReader &content_reader) {
  7822. ASSERT_TRUE(req.is_multipart_form_data());
  7823. std::vector<FormData> received;
  7824. content_reader(
  7825. [&](const FormData &file) {
  7826. received.push_back(file);
  7827. return true;
  7828. },
  7829. [&](const char *data, size_t data_length) {
  7830. received.back().content.append(data, data_length);
  7831. return true;
  7832. });
  7833. // '"', CR and LF in names and filenames are escaped following the
  7834. // WHATWG HTML standard, so each part still parses as a single part
  7835. // with no injected headers. Content types get CR/LF escaped too,
  7836. // while '"' (legal there, e.g. quoted charset) is preserved.
  7837. ASSERT_EQ(4U, received.size());
  7838. EXPECT_EQ("na%22me", received[0].name);
  7839. EXPECT_EQ("quoted name", received[0].content);
  7840. EXPECT_EQ("file", received[1].name);
  7841. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7842. received[1].filename);
  7843. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7844. EXPECT_EQ("injected", received[1].content);
  7845. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7846. EXPECT_EQ("my%22file.txt", received[2].filename);
  7847. EXPECT_EQ("cr lf name", received[2].content);
  7848. EXPECT_EQ("typed", received[3].name);
  7849. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7850. received[3].content_type);
  7851. EXPECT_EQ("typed content", received[3].content);
  7852. });
  7853. auto port = svr.bind_to_any_port("localhost");
  7854. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7855. auto se = detail::scope_exit([&] {
  7856. svr.stop();
  7857. t.join();
  7858. ASSERT_FALSE(svr.is_running());
  7859. });
  7860. svr.wait_until_ready();
  7861. Client cli("localhost", port);
  7862. UploadFormDataItems items = {
  7863. {"na\"me", "quoted name", "", ""},
  7864. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7865. "application/octet-stream"},
  7866. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7867. {"typed", "typed content", "",
  7868. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7869. };
  7870. auto res = cli.Post("/post", items);
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::OK_200, res->status);
  7873. }
  7874. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7875. const UploadFormDataItems items = {
  7876. {"name1", "Content 1", "", ""},
  7877. {"name2", "Content 2", "file2.txt", "text/plain"},
  7878. };
  7879. Server svr;
  7880. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7881. const ContentReader &content_reader) {
  7882. ASSERT_TRUE(req.is_multipart_form_data());
  7883. std::vector<FormData> received;
  7884. content_reader(
  7885. [&](const FormData &file) {
  7886. received.push_back(file);
  7887. return true;
  7888. },
  7889. [&](const char *data, size_t data_length) {
  7890. received.back().content.append(data, data_length);
  7891. return true;
  7892. });
  7893. ASSERT_EQ(2U, received.size());
  7894. EXPECT_EQ("name1", received[0].name);
  7895. EXPECT_EQ("Content 1", received[0].content);
  7896. EXPECT_EQ("name2", received[1].name);
  7897. EXPECT_EQ("Content 2", received[1].content);
  7898. EXPECT_EQ("file2.txt", received[1].filename);
  7899. EXPECT_EQ("text/plain", received[1].content_type);
  7900. });
  7901. auto port = svr.bind_to_any_port("localhost");
  7902. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7903. auto se = detail::scope_exit([&] {
  7904. svr.stop();
  7905. t.join();
  7906. ASSERT_FALSE(svr.is_running());
  7907. });
  7908. svr.wait_until_ready();
  7909. Client cli("localhost", port);
  7910. // Whole-body serialization with a generated boundary
  7911. {
  7912. MultipartFormDataWriter writer;
  7913. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7914. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7915. writer.content_type());
  7916. auto body = writer.serialize(items);
  7917. EXPECT_EQ(body.size(), writer.content_length(items));
  7918. auto res = cli.Post("/post", body, writer.content_type());
  7919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7920. EXPECT_EQ(StatusCode::OK_200, res->status);
  7921. }
  7922. // Per-part framing with a custom boundary via a content provider
  7923. {
  7924. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7925. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7926. MultipartFormDataWriter writer("custom-boundary_123");
  7927. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7928. std::string body;
  7929. for (const auto &item : items) {
  7930. body += writer.item_begin(item);
  7931. body += item.content;
  7932. body += MultipartFormDataWriter::item_end();
  7933. }
  7934. body += writer.finish();
  7935. EXPECT_EQ(body.size(), writer.content_length(items));
  7936. auto res = cli.Post(
  7937. "/post", body.size(),
  7938. [&](size_t offset, size_t length, DataSink &sink) {
  7939. sink.write(body.data() + offset, length);
  7940. return true;
  7941. },
  7942. writer.content_type());
  7943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7944. EXPECT_EQ(StatusCode::OK_200, res->status);
  7945. }
  7946. }
  7947. TEST_F(ServerTest, PostContentReceiverGzip) {
  7948. cli_.set_compress(true);
  7949. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7951. ASSERT_EQ(StatusCode::OK_200, res->status);
  7952. ASSERT_EQ("content", res->body);
  7953. }
  7954. TEST_F(ServerTest, PutContentReceiver) {
  7955. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. ASSERT_EQ(StatusCode::OK_200, res->status);
  7958. ASSERT_EQ("content", res->body);
  7959. }
  7960. TEST_F(ServerTest, PatchContentReceiver) {
  7961. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7963. ASSERT_EQ(StatusCode::OK_200, res->status);
  7964. ASSERT_EQ("content", res->body);
  7965. }
  7966. template <typename ClientType>
  7967. void TestWithHeadersAndContentReceiver(
  7968. ClientType &cli,
  7969. std::function<Result(ClientType &, const std::string &, const Headers &,
  7970. const std::string &, const std::string &,
  7971. ContentReceiver, DownloadProgress)>
  7972. request_func) {
  7973. Headers headers;
  7974. headers.emplace("X-Custom-Header", "test-value");
  7975. std::string received_body;
  7976. auto res = request_func(
  7977. cli, "/content_receiver", headers, "content", "application/json",
  7978. [&](const char *data, size_t data_length) {
  7979. received_body.append(data, data_length);
  7980. return true;
  7981. },
  7982. nullptr);
  7983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. EXPECT_EQ("content", received_body);
  7986. }
  7987. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7988. #ifdef CPPHTTPLIB_SSL_ENABLED
  7989. using ClientT = SSLClient;
  7990. #else
  7991. using ClientT = Client;
  7992. #endif
  7993. TestWithHeadersAndContentReceiver<ClientT>(
  7994. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7995. const std::string &body, const std::string &content_type,
  7996. ContentReceiver receiver, DownloadProgress progress) {
  7997. return cli.Post(path, headers, body, content_type, receiver, progress);
  7998. });
  7999. }
  8000. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8001. #ifdef CPPHTTPLIB_SSL_ENABLED
  8002. using ClientT = SSLClient;
  8003. #else
  8004. using ClientT = Client;
  8005. #endif
  8006. TestWithHeadersAndContentReceiver<ClientT>(
  8007. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8008. const std::string &body, const std::string &content_type,
  8009. ContentReceiver receiver, DownloadProgress progress) {
  8010. return cli.Put(path, headers, body, content_type, receiver, progress);
  8011. });
  8012. }
  8013. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8014. #ifdef CPPHTTPLIB_SSL_ENABLED
  8015. using ClientT = SSLClient;
  8016. #else
  8017. using ClientT = Client;
  8018. #endif
  8019. TestWithHeadersAndContentReceiver<ClientT>(
  8020. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8021. const std::string &body, const std::string &content_type,
  8022. ContentReceiver receiver, DownloadProgress progress) {
  8023. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8024. });
  8025. }
  8026. template <typename ClientType>
  8027. void TestWithHeadersAndContentReceiverWithProgress(
  8028. ClientType &cli,
  8029. std::function<Result(ClientType &, const std::string &, const Headers &,
  8030. const std::string &, const std::string &,
  8031. ContentReceiver, DownloadProgress)>
  8032. request_func) {
  8033. Headers headers;
  8034. headers.emplace("X-Test-Header", "progress-test");
  8035. std::string received_body;
  8036. auto progress_called = false;
  8037. auto res = request_func(
  8038. cli, "/content_receiver", headers, "content", "text/plain",
  8039. [&](const char *data, size_t data_length) {
  8040. received_body.append(data, data_length);
  8041. return true;
  8042. },
  8043. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8044. progress_called = true;
  8045. return true;
  8046. });
  8047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8048. EXPECT_EQ(StatusCode::OK_200, res->status);
  8049. EXPECT_EQ("content", received_body);
  8050. EXPECT_TRUE(progress_called);
  8051. }
  8052. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8053. #ifdef CPPHTTPLIB_SSL_ENABLED
  8054. using ClientT = SSLClient;
  8055. #else
  8056. using ClientT = Client;
  8057. #endif
  8058. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8059. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8060. const std::string &body, const std::string &content_type,
  8061. ContentReceiver receiver, DownloadProgress progress) {
  8062. return cli.Post(path, headers, body, content_type, receiver, progress);
  8063. });
  8064. }
  8065. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8066. #ifdef CPPHTTPLIB_SSL_ENABLED
  8067. using ClientT = SSLClient;
  8068. #else
  8069. using ClientT = Client;
  8070. #endif
  8071. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8072. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8073. const std::string &body, const std::string &content_type,
  8074. ContentReceiver receiver, DownloadProgress progress) {
  8075. return cli.Put(path, headers, body, content_type, receiver, progress);
  8076. });
  8077. }
  8078. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8079. #ifdef CPPHTTPLIB_SSL_ENABLED
  8080. using ClientT = SSLClient;
  8081. #else
  8082. using ClientT = Client;
  8083. #endif
  8084. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8085. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8086. const std::string &body, const std::string &content_type,
  8087. ContentReceiver receiver, DownloadProgress progress) {
  8088. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8089. });
  8090. }
  8091. template <typename ClientType>
  8092. void TestWithHeadersAndContentReceiverError(
  8093. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8094. const Headers &, const std::string &,
  8095. const std::string &, ContentReceiver)>
  8096. request_func) {
  8097. Headers headers;
  8098. headers.emplace("X-Error-Test", "true");
  8099. std::string received_body;
  8100. auto receiver_failed = false;
  8101. auto res =
  8102. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8103. [&](const char *data, size_t data_length) {
  8104. received_body.append(data, data_length);
  8105. receiver_failed = true;
  8106. return false;
  8107. });
  8108. ASSERT_FALSE(res);
  8109. EXPECT_TRUE(receiver_failed);
  8110. }
  8111. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8112. #ifdef CPPHTTPLIB_SSL_ENABLED
  8113. using ClientT = SSLClient;
  8114. #else
  8115. using ClientT = Client;
  8116. #endif
  8117. TestWithHeadersAndContentReceiverError<ClientT>(
  8118. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8119. const std::string &body, const std::string &content_type,
  8120. ContentReceiver receiver) {
  8121. return cli.Post(path, headers, body, content_type, receiver);
  8122. });
  8123. }
  8124. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8125. #ifdef CPPHTTPLIB_SSL_ENABLED
  8126. using ClientT = SSLClient;
  8127. #else
  8128. using ClientT = Client;
  8129. #endif
  8130. TestWithHeadersAndContentReceiverError<ClientT>(
  8131. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8132. const std::string &body, const std::string &content_type,
  8133. ContentReceiver receiver) {
  8134. return cli.Put(path, headers, body, content_type, receiver);
  8135. });
  8136. }
  8137. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8138. #ifdef CPPHTTPLIB_SSL_ENABLED
  8139. using ClientT = SSLClient;
  8140. #else
  8141. using ClientT = Client;
  8142. #endif
  8143. TestWithHeadersAndContentReceiverError<ClientT>(
  8144. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8145. const std::string &body, const std::string &content_type,
  8146. ContentReceiver receiver) {
  8147. return cli.Patch(path, headers, body, content_type, receiver);
  8148. });
  8149. }
  8150. TEST_F(ServerTest, PostQueryStringAndBody) {
  8151. auto res =
  8152. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8154. ASSERT_EQ(StatusCode::OK_200, res->status);
  8155. }
  8156. TEST_F(ServerTest, HTTP2Magic) {
  8157. Request req;
  8158. req.method = "PRI";
  8159. req.path = "*";
  8160. req.body = "SM";
  8161. auto res = std::make_shared<Response>();
  8162. auto error = Error::Success;
  8163. auto ret = cli_.send(req, *res, error);
  8164. ASSERT_TRUE(ret);
  8165. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8166. }
  8167. TEST_F(ServerTest, KeepAlive) {
  8168. auto res = cli_.Get("/hi");
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. EXPECT_EQ(StatusCode::OK_200, res->status);
  8171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8172. EXPECT_EQ("Hello World!", res->body);
  8173. res = cli_.Get("/hi");
  8174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8175. EXPECT_EQ(StatusCode::OK_200, res->status);
  8176. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8177. EXPECT_EQ("Hello World!", res->body);
  8178. res = cli_.Get("/hi");
  8179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8180. EXPECT_EQ(StatusCode::OK_200, res->status);
  8181. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8182. EXPECT_EQ("Hello World!", res->body);
  8183. res = cli_.Get("/not-exist");
  8184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8185. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8186. res = cli_.Post("/empty", "", "text/plain");
  8187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8188. EXPECT_EQ(StatusCode::OK_200, res->status);
  8189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8190. EXPECT_EQ("empty", res->body);
  8191. EXPECT_EQ("close", res->get_header_value("Connection"));
  8192. res = cli_.Post(
  8193. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8194. "text/plain");
  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_EQ("empty", res->body);
  8199. cli_.set_keep_alive(false);
  8200. res = cli_.Get("/last-request");
  8201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8202. EXPECT_EQ(StatusCode::OK_200, res->status);
  8203. EXPECT_EQ("close", res->get_header_value("Connection"));
  8204. }
  8205. TEST_F(ServerTest, TooManyRedirect) {
  8206. cli_.set_follow_location(true);
  8207. auto res = cli_.Get("/redirect/0");
  8208. ASSERT_TRUE(!res);
  8209. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8210. }
  8211. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8212. Request req;
  8213. req.method = "FOOBAR";
  8214. req.path = "/hi";
  8215. cli_.set_keep_alive(true);
  8216. auto res = cli_.send(req);
  8217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8218. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8219. EXPECT_EQ("close", res->get_header_value("Connection"));
  8220. EXPECT_FALSE(cli_.is_socket_open());
  8221. }
  8222. TEST_F(ServerTest, CustomRouteReadsBody) {
  8223. const std::string xml =
  8224. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8225. Request req;
  8226. req.method = "PROPFIND";
  8227. req.path = "/dav/dir";
  8228. req.set_header("Depth", "1");
  8229. req.body = xml;
  8230. auto res = cli_.send(req);
  8231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8232. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8233. EXPECT_EQ(xml, res->body);
  8234. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8235. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8236. }
  8237. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8238. Request req;
  8239. req.method = "PROPFIND";
  8240. req.path = "/dav/42";
  8241. auto res = cli_.send(req);
  8242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8243. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8244. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8245. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8246. }
  8247. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8248. Request req;
  8249. req.method = "PROPFIND";
  8250. req.path = "/dav-re/123";
  8251. auto res = cli_.send(req);
  8252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8253. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8254. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8255. }
  8256. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8257. Request req;
  8258. req.method = "MKCOL";
  8259. req.path = "/dav-mkcol";
  8260. auto res = cli_.send(req);
  8261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8262. EXPECT_EQ(StatusCode::Created_201, res->status);
  8263. }
  8264. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8265. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8266. Request req;
  8267. req.method = "REPORT";
  8268. req.path = "/dav-report";
  8269. req.body = xml;
  8270. auto res = cli_.send(req);
  8271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8272. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8273. EXPECT_EQ(xml, res->body);
  8274. }
  8275. // A content reader route must fire even when the request carries no body,
  8276. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8277. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8278. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8279. Request req;
  8280. req.method = "REPORT";
  8281. req.path = "/dav-report";
  8282. auto res = cli_.send(req);
  8283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8284. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8285. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8286. }
  8287. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8288. Request req;
  8289. req.method = "PROPFIND";
  8290. req.path = "/not-dav";
  8291. auto res = cli_.send(req);
  8292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8294. }
  8295. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8296. Request req;
  8297. req.method = "UNLOCK";
  8298. req.path = "/dav/dir";
  8299. cli_.set_keep_alive(true);
  8300. auto res = cli_.send(req);
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8303. EXPECT_EQ("close", res->get_header_value("Connection"));
  8304. EXPECT_FALSE(cli_.is_socket_open());
  8305. }
  8306. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8307. // The mount point serves this path, but only for GET and HEAD.
  8308. auto get_res = cli_.Get("/dir/index.html");
  8309. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8310. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8311. Request req;
  8312. req.method = "PROPFIND";
  8313. req.path = "/dir/index.html";
  8314. auto res = cli_.send(req);
  8315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8316. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8317. }
  8318. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8319. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8320. cli_.set_keep_alive(true);
  8321. for (auto i = 0; i < 2; i++) {
  8322. Request req;
  8323. req.method = "PROPFIND";
  8324. req.path = "/dav/dir";
  8325. req.body = xml;
  8326. auto res = cli_.send(req);
  8327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8328. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8329. EXPECT_EQ(xml, res->body);
  8330. EXPECT_TRUE(cli_.is_socket_open());
  8331. }
  8332. // A built-in method must still be served on the same connection.
  8333. cli_.set_keep_alive(false);
  8334. auto res = cli_.Get("/hi");
  8335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8336. EXPECT_EQ(StatusCode::OK_200, res->status);
  8337. EXPECT_EQ("close", res->get_header_value("Connection"));
  8338. }
  8339. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8340. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8341. Request req;
  8342. req.method = "PROPFIND";
  8343. req.path = "/dav/dir";
  8344. req.set_header("Expect", "100-continue");
  8345. req.body = xml;
  8346. auto res = cli_.send(req);
  8347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8348. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8349. EXPECT_EQ(xml, res->body);
  8350. }
  8351. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8352. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8353. TEST_F(ServerTest, Gzip) {
  8354. Headers headers;
  8355. headers.emplace("Accept-Encoding", "gzip, deflate");
  8356. auto res = cli_.Get("/compress", headers);
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8359. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8360. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8361. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8362. "7890123456789012345678901234567890",
  8363. res->body);
  8364. EXPECT_EQ(StatusCode::OK_200, res->status);
  8365. }
  8366. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8367. Headers headers;
  8368. headers.emplace("Accept-Encoding", "gzip, deflate");
  8369. auto res = cli_.Get("/compress-with-charset", headers);
  8370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8371. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8372. EXPECT_EQ("application/json; charset=utf-8",
  8373. res->get_header_value("Content-Type"));
  8374. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8375. "7890123456789012345678901234567890",
  8376. res->body);
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. }
  8379. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8380. Headers headers;
  8381. headers.emplace("Accept-Encoding", "");
  8382. auto res = cli_.Get("/compress", headers);
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8386. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8387. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8388. "7890123456789012345678901234567890",
  8389. res->body);
  8390. EXPECT_EQ(StatusCode::OK_200, res->status);
  8391. }
  8392. TEST_F(ServerTest, GzipWithContentReceiver) {
  8393. Headers headers;
  8394. headers.emplace("Accept-Encoding", "gzip, deflate");
  8395. std::string body;
  8396. auto res =
  8397. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8398. EXPECT_EQ(100U, data_length);
  8399. body.append(data, data_length);
  8400. return true;
  8401. });
  8402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8403. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8404. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8405. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8406. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8407. "7890123456789012345678901234567890",
  8408. body);
  8409. EXPECT_EQ(StatusCode::OK_200, res->status);
  8410. }
  8411. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8412. Headers headers;
  8413. headers.emplace("Accept-Encoding", "gzip, deflate");
  8414. cli_.set_decompress(false);
  8415. auto res = cli_.Get("/compress", headers);
  8416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8417. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8418. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8419. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8420. EXPECT_EQ(33U, res->body.size());
  8421. EXPECT_EQ(StatusCode::OK_200, res->status);
  8422. }
  8423. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8424. Headers headers;
  8425. headers.emplace("Accept-Encoding", "");
  8426. std::string body;
  8427. auto res =
  8428. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8429. EXPECT_EQ(100U, data_length);
  8430. body.append(data, data_length);
  8431. return true;
  8432. });
  8433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8434. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8435. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8436. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8437. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8438. "7890123456789012345678901234567890",
  8439. body);
  8440. EXPECT_EQ(StatusCode::OK_200, res->status);
  8441. }
  8442. TEST_F(ServerTest, NoGzip) {
  8443. Headers headers;
  8444. headers.emplace("Accept-Encoding", "gzip, deflate");
  8445. auto res = cli_.Get("/nocompress", headers);
  8446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8447. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8448. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8449. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8450. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8451. "7890123456789012345678901234567890",
  8452. res->body);
  8453. EXPECT_EQ(StatusCode::OK_200, res->status);
  8454. }
  8455. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8456. Headers headers;
  8457. headers.emplace("Accept-Encoding", "gzip, deflate");
  8458. std::string body;
  8459. auto res = cli_.Get("/nocompress", headers,
  8460. [&](const char *data, size_t data_length) {
  8461. EXPECT_EQ(100U, data_length);
  8462. body.append(data, data_length);
  8463. return true;
  8464. });
  8465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8466. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8467. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8468. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8469. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8470. "7890123456789012345678901234567890",
  8471. body);
  8472. EXPECT_EQ(StatusCode::OK_200, res->status);
  8473. }
  8474. TEST_F(ServerTest, MultipartFormDataGzip) {
  8475. UploadFormDataItems items = {
  8476. {"key1", "test", "", ""},
  8477. {"key2", "--abcdefg123", "", ""},
  8478. };
  8479. cli_.set_compress(true);
  8480. auto res = cli_.Post("/compress-multipart", items);
  8481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8482. EXPECT_EQ(StatusCode::OK_200, res->status);
  8483. }
  8484. #endif
  8485. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8486. // Static file compression is opt-in, so these run their own server rather than
  8487. // flipping it on for the shared ServerTest fixture, which would silently
  8488. // rewrite what every other static file test is asserting.
  8489. class StaticFileCompressionTest : public ::testing::Test {
  8490. protected:
  8491. void TearDown() override {
  8492. if (t_.joinable()) {
  8493. svr_.stop();
  8494. t_.join();
  8495. }
  8496. }
  8497. int start(const std::function<void(Server &)> &configure = nullptr) {
  8498. // Serves the same tree as a directory of build-time compressed assets
  8499. // would be served: the mount point names the coding the files are already
  8500. // stored in. Registered before "/" so it is the one that matches.
  8501. svr_.set_mount_point("/pre-encoded", "./www",
  8502. {{"Content-Encoding", "gzip"}});
  8503. svr_.set_mount_point("/", "./www");
  8504. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8505. res.set_file_content("./www/dir/index.html", "text/html");
  8506. });
  8507. svr_.Get("/pre-encoded-file-content",
  8508. [](const Request & /*req*/, Response &res) {
  8509. res.set_header("Content-Encoding", "gzip");
  8510. res.set_file_content("./www/dir/index.html", "text/html");
  8511. });
  8512. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8513. res.set_content_provider(
  8514. 6, "text/plain",
  8515. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8516. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8517. return true;
  8518. });
  8519. });
  8520. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8521. res.set_content_provider(
  8522. 1000, "text/plain",
  8523. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8524. if (offset < 100) {
  8525. std::string data(100, 'A');
  8526. sink.write(data.data(), data.size());
  8527. return true;
  8528. }
  8529. std::this_thread::sleep_for(std::chrono::seconds(2));
  8530. std::string data(900, 'B');
  8531. sink.write(data.data(), data.size());
  8532. return true;
  8533. });
  8534. });
  8535. if (configure) { configure(svr_); }
  8536. auto port = svr_.bind_to_any_port(HOST);
  8537. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8538. svr_.wait_until_ready();
  8539. return port;
  8540. }
  8541. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8542. // Every file under ./www except 1MB.txt is smaller than the default
  8543. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8544. // it out of the way.
  8545. static void enable_without_floor(Server &svr) {
  8546. svr.set_static_file_compression(true);
  8547. svr.set_static_file_compression_min_length(0);
  8548. }
  8549. Server svr_;
  8550. std::thread t_;
  8551. };
  8552. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8553. auto port = start();
  8554. Client cli(HOST, port);
  8555. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8557. EXPECT_EQ(StatusCode::OK_200, res->status);
  8558. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8559. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8560. EXPECT_EQ(1048576U, res->body.size());
  8561. }
  8562. TEST_F(StaticFileCompressionTest, MountPoint) {
  8563. auto port = start(enable);
  8564. Client cli(HOST, port);
  8565. cli.set_decompress(false);
  8566. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8568. EXPECT_EQ(StatusCode::OK_200, res->status);
  8569. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8570. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8571. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8572. // The response stays self-delimiting: a length, not a chunked body.
  8573. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8574. EXPECT_EQ(std::to_string(res->body.size()),
  8575. res->get_header_value("Content-Length"));
  8576. EXPECT_LT(res->body.size(), 1048576U);
  8577. EXPECT_FALSE(res->body.empty());
  8578. }
  8579. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8580. auto port = start(enable);
  8581. Client cli(HOST, port);
  8582. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8584. EXPECT_EQ(StatusCode::OK_200, res->status);
  8585. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8586. EXPECT_EQ(1048576U, res->body.size());
  8587. }
  8588. TEST_F(StaticFileCompressionTest, FileContent) {
  8589. auto port = start(enable_without_floor);
  8590. Client cli(HOST, port);
  8591. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8593. EXPECT_EQ(StatusCode::OK_200, res->status);
  8594. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8595. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8596. EXPECT_EQ(104U, res->body.size());
  8597. }
  8598. // A handler that serves an already-encoded file names the coding itself. The
  8599. // file-backed path decided its coding from Accept-Encoding and the content
  8600. // type alone, so it compressed the stored bytes a second time and appended a
  8601. // second Content-Encoding field line.
  8602. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8603. auto port = start(enable_without_floor);
  8604. Client cli(HOST, port);
  8605. cli.set_decompress(false);
  8606. auto res = cli.Get("/pre-encoded-file-content",
  8607. Headers{{"Accept-Encoding", "gzip"}});
  8608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8609. EXPECT_EQ(StatusCode::OK_200, res->status);
  8610. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8611. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8612. // Vary belongs to a coding the server chose, and it chose none here.
  8613. EXPECT_FALSE(res->has_header("Vary"));
  8614. // The file travels exactly as it is stored on disk.
  8615. EXPECT_EQ(104U, res->body.size());
  8616. }
  8617. // The 1MB file clears the default floor, so this one runs the configuration a
  8618. // deployment would actually have.
  8619. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8620. auto port = start(enable);
  8621. Client cli(HOST, port);
  8622. cli.set_decompress(false);
  8623. auto res =
  8624. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8626. EXPECT_EQ(StatusCode::OK_200, res->status);
  8627. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8628. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8629. EXPECT_FALSE(res->has_header("Vary"));
  8630. EXPECT_EQ(1048576U, res->body.size());
  8631. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8632. }
  8633. TEST_F(StaticFileCompressionTest, Head) {
  8634. auto port = start(enable);
  8635. Client cli(HOST, port);
  8636. cli.set_decompress(false);
  8637. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8638. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8639. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8641. EXPECT_EQ(StatusCode::OK_200, res->status);
  8642. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8643. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8644. // HEAD still reports the size a GET would return.
  8645. EXPECT_EQ(get->get_header_value("Content-Length"),
  8646. res->get_header_value("Content-Length"));
  8647. EXPECT_TRUE(res->body.empty());
  8648. }
  8649. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8650. auto port = start(enable);
  8651. Client cli(HOST, port);
  8652. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8653. {"Accept-Encoding", "gzip"}});
  8654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8655. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8656. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8657. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8658. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8659. EXPECT_EQ("cd", res->body);
  8660. }
  8661. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8662. auto port = start(enable);
  8663. Client cli(HOST, port);
  8664. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8666. EXPECT_EQ(StatusCode::OK_200, res->status);
  8667. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8668. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8669. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8670. }
  8671. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8672. auto port = start(enable);
  8673. Client cli(HOST, port);
  8674. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8676. EXPECT_EQ(StatusCode::OK_200, res->status);
  8677. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8678. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8679. EXPECT_TRUE(res->body.empty());
  8680. }
  8681. TEST_F(StaticFileCompressionTest, MinLength) {
  8682. auto port = start(enable);
  8683. Client cli(HOST, port);
  8684. // 104 bytes, well under the default floor. Compressing it would add the
  8685. // gzip header and trailer to a body that already fits in one packet.
  8686. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8688. EXPECT_EQ(StatusCode::OK_200, res->status);
  8689. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8690. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8691. }
  8692. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8693. auto port = start([](Server &svr) {
  8694. svr.set_static_file_compression(true);
  8695. svr.set_static_file_compression_min_length(1);
  8696. });
  8697. Client cli(HOST, port);
  8698. cli.set_decompress(false);
  8699. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8701. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8702. // A 9-byte file comes back larger than it went in, because gzip's header and
  8703. // trailer outweigh anything deflate can save. That is the end of the range
  8704. // the floor exists to keep out.
  8705. EXPECT_GT(res->body.size(), 9U);
  8706. }
  8707. TEST_F(StaticFileCompressionTest, MaxLength) {
  8708. auto port = start([](Server &svr) {
  8709. svr.set_static_file_compression(true);
  8710. svr.set_static_file_compression_min_length(0);
  8711. svr.set_static_file_compression_max_length(1024);
  8712. });
  8713. Client cli(HOST, port);
  8714. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8715. // defines `small` as a macro on Windows.
  8716. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8717. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8718. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8719. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8720. // Under it: compressed.
  8721. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8722. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8723. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8724. }
  8725. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8726. auto port = start(enable_without_floor);
  8727. Client cli(HOST, port);
  8728. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8729. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8730. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8731. auto identity_etag = identity->get_header_value("ETag");
  8732. ASSERT_FALSE(identity_etag.empty());
  8733. auto gzipped =
  8734. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8735. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8736. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8737. auto gzip_etag = gzipped->get_header_value("ETag");
  8738. ASSERT_FALSE(gzip_etag.empty());
  8739. // Two representations, two validators.
  8740. EXPECT_NE(identity_etag, gzip_etag);
  8741. // Each one revalidates against the request that would produce it...
  8742. auto fresh =
  8743. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8744. {"If-None-Match", gzip_etag}});
  8745. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8746. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8747. auto fresh_identity =
  8748. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8749. {"If-None-Match", identity_etag}});
  8750. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8751. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8752. // ...and not against the other representation.
  8753. auto crossed =
  8754. cli.Get("/dir/index.html",
  8755. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8756. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8757. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8758. }
  8759. // The opt-in covers responses the server reads off disk itself. A caller's own
  8760. // known-length provider keeps its Content-Length and, more importantly, keeps
  8761. // delivering incrementally: routing it through a compressor would hold every
  8762. // write back until zlib's window filled.
  8763. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8764. auto port = start(enable);
  8765. Client cli(HOST, port);
  8766. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8768. EXPECT_EQ(StatusCode::OK_200, res->status);
  8769. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8770. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8771. EXPECT_EQ("aaabbb", res->body);
  8772. }
  8773. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8774. auto port = start(enable);
  8775. Client cli(HOST, port);
  8776. cli.set_read_timeout(1, 0);
  8777. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8778. Headers{{"Accept-Encoding", "gzip"}});
  8779. ASSERT_TRUE(handle.is_valid());
  8780. // The provider writes 100 bytes and then stalls for longer than the read
  8781. // timeout. Those first bytes have to arrive anyway: run the response through
  8782. // a compressor and zlib holds them until its window fills, so the read would
  8783. // come back empty instead.
  8784. char buf[256];
  8785. auto n = handle.read(buf, sizeof(buf));
  8786. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8787. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8788. }
  8789. #endif
  8790. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8791. TEST_F(ServerTest, Brotli) {
  8792. Headers headers;
  8793. headers.emplace("Accept-Encoding", "br");
  8794. auto res = cli_.Get("/compress", headers);
  8795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8796. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8797. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8798. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8799. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8800. "7890123456789012345678901234567890",
  8801. res->body);
  8802. EXPECT_EQ(StatusCode::OK_200, res->status);
  8803. }
  8804. #endif
  8805. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8806. TEST_F(ServerTest, Zstd) {
  8807. Headers headers;
  8808. headers.emplace("Accept-Encoding", "zstd");
  8809. auto res = cli_.Get("/compress", headers);
  8810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8811. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8812. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8813. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8814. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8815. "7890123456789012345678901234567890",
  8816. res->body);
  8817. EXPECT_EQ(StatusCode::OK_200, res->status);
  8818. }
  8819. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8820. Headers headers;
  8821. headers.emplace("Accept-Encoding", "");
  8822. auto res = cli_.Get("/compress", headers);
  8823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8824. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8826. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8827. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8828. "7890123456789012345678901234567890",
  8829. res->body);
  8830. EXPECT_EQ(StatusCode::OK_200, res->status);
  8831. }
  8832. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8833. Headers headers;
  8834. headers.emplace("Accept-Encoding", "zstd");
  8835. std::string body;
  8836. auto res =
  8837. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8838. EXPECT_EQ(100U, data_length);
  8839. body.append(data, data_length);
  8840. return true;
  8841. });
  8842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8843. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8844. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8845. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8846. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8847. "7890123456789012345678901234567890",
  8848. body);
  8849. EXPECT_EQ(StatusCode::OK_200, res->status);
  8850. }
  8851. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8852. Headers headers;
  8853. headers.emplace("Accept-Encoding", "zstd");
  8854. cli_.set_decompress(false);
  8855. auto res = cli_.Get("/compress", headers);
  8856. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8857. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8858. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8859. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8861. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8862. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8863. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8864. EXPECT_EQ(StatusCode::OK_200, res->status);
  8865. ASSERT_EQ(26U, res->body.size());
  8866. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8867. 0);
  8868. }
  8869. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8870. Headers headers;
  8871. headers.emplace("Accept-Encoding", "");
  8872. std::string body;
  8873. auto res =
  8874. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8875. EXPECT_EQ(100U, data_length);
  8876. body.append(data, data_length);
  8877. return true;
  8878. });
  8879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8880. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8881. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8882. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8883. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8884. "7890123456789012345678901234567890",
  8885. body);
  8886. EXPECT_EQ(StatusCode::OK_200, res->status);
  8887. }
  8888. TEST_F(ServerTest, NoZstd) {
  8889. Headers headers;
  8890. headers.emplace("Accept-Encoding", "zstd");
  8891. auto res = cli_.Get("/nocompress", headers);
  8892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8893. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8894. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8895. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8896. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8897. "7890123456789012345678901234567890",
  8898. res->body);
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. }
  8901. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8902. Headers headers;
  8903. headers.emplace("Accept-Encoding", "zstd");
  8904. std::string body;
  8905. auto res = cli_.Get("/nocompress", headers,
  8906. [&](const char *data, size_t data_length) {
  8907. EXPECT_EQ(100U, data_length);
  8908. body.append(data, data_length);
  8909. return true;
  8910. });
  8911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8912. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8913. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8914. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8915. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8916. "7890123456789012345678901234567890",
  8917. body);
  8918. EXPECT_EQ(StatusCode::OK_200, res->status);
  8919. }
  8920. // TODO: How to enable zstd ??
  8921. TEST_F(ServerTest, MultipartFormDataZstd) {
  8922. UploadFormDataItems items = {
  8923. {"key1", "test", "", ""},
  8924. {"key2", "--abcdefg123", "", ""},
  8925. };
  8926. Headers headers;
  8927. headers.emplace("Accept-Encoding", "zstd");
  8928. cli_.set_compress(true);
  8929. auto res = cli_.Post("/compress-multipart", headers, items);
  8930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8931. EXPECT_EQ(StatusCode::OK_200, res->status);
  8932. }
  8933. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8934. Headers headers;
  8935. headers.emplace("Accept-Encoding", "zstd");
  8936. cli_.set_compress(true);
  8937. auto res = cli_.Put(
  8938. "/put", headers, 3,
  8939. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8940. sink.os << "PUT";
  8941. return true;
  8942. },
  8943. "text/plain");
  8944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8945. EXPECT_EQ(StatusCode::OK_200, res->status);
  8946. EXPECT_EQ("PUT", res->body);
  8947. }
  8948. // Pre-compression logging tests
  8949. TEST_F(ServerTest, PreCompressionLogging) {
  8950. // Test data for compression (matches the actual /compress endpoint content)
  8951. const std::string test_content =
  8952. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8953. "3456789012345678901234567890";
  8954. // Variables to capture logging data
  8955. std::string pre_compression_body;
  8956. std::string pre_compression_content_type;
  8957. std::string pre_compression_content_encoding;
  8958. std::string post_compression_body;
  8959. std::string post_compression_content_type;
  8960. std::string post_compression_content_encoding;
  8961. // Set up pre-compression logger
  8962. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8963. const Response &res) {
  8964. pre_compression_body = res.body;
  8965. pre_compression_content_type = res.get_header_value("Content-Type");
  8966. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8967. });
  8968. // Set up post-compression logger
  8969. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8970. post_compression_body = res.body;
  8971. post_compression_content_type = res.get_header_value("Content-Type");
  8972. post_compression_content_encoding =
  8973. res.get_header_value("Content-Encoding");
  8974. });
  8975. // Test with gzip compression
  8976. Headers headers;
  8977. headers.emplace("Accept-Encoding", "gzip");
  8978. auto res = cli_.Get("/compress", headers);
  8979. // Verify response was compressed
  8980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8981. EXPECT_EQ(StatusCode::OK_200, res->status);
  8982. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8983. // Verify pre-compression logger captured uncompressed content
  8984. EXPECT_EQ(test_content, pre_compression_body);
  8985. EXPECT_EQ("text/plain", pre_compression_content_type);
  8986. EXPECT_TRUE(pre_compression_content_encoding
  8987. .empty()); // No encoding header before compression
  8988. // Verify post-compression logger captured compressed content
  8989. EXPECT_NE(test_content,
  8990. post_compression_body); // Should be different after compression
  8991. EXPECT_EQ("text/plain", post_compression_content_type);
  8992. EXPECT_EQ("gzip", post_compression_content_encoding);
  8993. // Verify compressed content is smaller
  8994. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8995. }
  8996. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8997. const std::string test_content =
  8998. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8999. "3456789012345678901234567890";
  9000. std::string pre_compression_body;
  9001. std::string post_compression_body;
  9002. svr_.set_pre_compression_logger(
  9003. [&](const Request & /*req*/, const Response &res) {
  9004. pre_compression_body = res.body;
  9005. });
  9006. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9007. post_compression_body = res.body;
  9008. });
  9009. Headers headers;
  9010. headers.emplace("Accept-Encoding", "br");
  9011. auto res = cli_.Get("/compress", headers);
  9012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9013. EXPECT_EQ(StatusCode::OK_200, res->status);
  9014. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9015. // Verify pre-compression content is uncompressed
  9016. EXPECT_EQ(test_content, pre_compression_body);
  9017. // Verify post-compression content is compressed
  9018. EXPECT_NE(test_content, post_compression_body);
  9019. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9020. }
  9021. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9022. const std::string test_content =
  9023. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9024. "3456789012345678901234567890";
  9025. std::string pre_compression_body;
  9026. std::string post_compression_body;
  9027. svr_.set_pre_compression_logger(
  9028. [&](const Request & /*req*/, const Response &res) {
  9029. pre_compression_body = res.body;
  9030. });
  9031. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9032. post_compression_body = res.body;
  9033. });
  9034. // Request without compression (use /nocompress endpoint)
  9035. Headers headers;
  9036. auto res = cli_.Get("/nocompress", headers);
  9037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9038. EXPECT_EQ(StatusCode::OK_200, res->status);
  9039. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9040. // Pre-compression logger should not be called when no compression is applied
  9041. EXPECT_TRUE(
  9042. pre_compression_body.empty()); // Pre-compression logger not called
  9043. EXPECT_EQ(
  9044. test_content,
  9045. post_compression_body); // Post-compression logger captures final content
  9046. }
  9047. TEST_F(ServerTest, LoggerSeesContentLength) {
  9048. size_t logged_content_length = 0;
  9049. std::string logged_content_length_header;
  9050. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9051. logged_content_length = res.content_length_;
  9052. logged_content_length_header = res.get_header_value("Content-Length");
  9053. });
  9054. auto res = cli_.Get("/nocompress");
  9055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9056. EXPECT_EQ(StatusCode::OK_200, res->status);
  9057. EXPECT_EQ(res->body.size(), logged_content_length);
  9058. EXPECT_EQ(std::to_string(logged_content_length),
  9059. logged_content_length_header);
  9060. }
  9061. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9062. const std::string test_content =
  9063. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9064. "3456789012345678901234567890";
  9065. std::string pre_compression_body;
  9066. bool pre_logger_called = false;
  9067. // Set only pre-compression logger
  9068. svr_.set_pre_compression_logger(
  9069. [&](const Request & /*req*/, const Response &res) {
  9070. pre_compression_body = res.body;
  9071. pre_logger_called = true;
  9072. });
  9073. Headers headers;
  9074. headers.emplace("Accept-Encoding", "gzip");
  9075. auto res = cli_.Get("/compress", headers);
  9076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9077. EXPECT_EQ(StatusCode::OK_200, res->status);
  9078. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9079. // Verify pre-compression logger was called
  9080. EXPECT_TRUE(pre_logger_called);
  9081. EXPECT_EQ(test_content, pre_compression_body);
  9082. }
  9083. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9084. {
  9085. // Test with Expect: 100-continue header - success case
  9086. // Server returns 100 Continue, client sends body, server returns 200 OK
  9087. Request req;
  9088. req.method = "POST";
  9089. req.path = "/post-large";
  9090. req.set_header("Expect", "100-continue");
  9091. req.body = LARGE_DATA;
  9092. Response res;
  9093. auto error = Error::Success;
  9094. cli_.set_keep_alive(true);
  9095. auto ret = cli_.send(req, res, error);
  9096. EXPECT_TRUE(ret);
  9097. EXPECT_EQ(StatusCode::OK_200, res.status);
  9098. EXPECT_EQ(LARGE_DATA, res.body);
  9099. }
  9100. {
  9101. // Test with Expect: 100-continue header - error case
  9102. // Client should not send the body when server returns an error
  9103. Request req;
  9104. req.method = "POST";
  9105. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9106. req.set_header("Expect", "100-continue");
  9107. req.body = LARGE_DATA;
  9108. Response res;
  9109. auto error = Error::Success;
  9110. auto start = std::chrono::high_resolution_clock::now();
  9111. cli_.set_keep_alive(true);
  9112. auto ret = cli_.send(req, res, error);
  9113. auto end = std::chrono::high_resolution_clock::now();
  9114. auto elapsed =
  9115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9116. .count();
  9117. // With Expect: 100-continue, request completes successfully but with error
  9118. EXPECT_TRUE(ret);
  9119. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9120. EXPECT_EQ("close", res.get_header_value("Connection"));
  9121. EXPECT_FALSE(cli_.is_socket_open());
  9122. EXPECT_LE(elapsed, 2000);
  9123. }
  9124. {
  9125. // Send an extra GET request to ensure error recovery without hanging
  9126. Request req;
  9127. req.method = "GET";
  9128. req.path = "/hi";
  9129. auto start = std::chrono::high_resolution_clock::now();
  9130. auto res = cli_.send(req);
  9131. auto end = std::chrono::high_resolution_clock::now();
  9132. auto elapsed =
  9133. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9134. .count();
  9135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9136. EXPECT_EQ(StatusCode::OK_200, res->status);
  9137. EXPECT_EQ("Hello World!", res->body);
  9138. EXPECT_LE(elapsed, 500);
  9139. }
  9140. }
  9141. TEST(ZstdDecompressor, ChunkedDecompression) {
  9142. std::string data;
  9143. for (size_t i = 0; i < 32 * 1024; ++i) {
  9144. data.push_back(static_cast<char>('a' + i % 26));
  9145. }
  9146. std::string compressed_data;
  9147. {
  9148. httplib::detail::zstd_compressor compressor;
  9149. bool result = compressor.compress(
  9150. data.data(), data.size(),
  9151. /*last=*/true,
  9152. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9153. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9154. compressed_data_size);
  9155. return true;
  9156. });
  9157. ASSERT_TRUE(result);
  9158. }
  9159. std::string decompressed_data;
  9160. {
  9161. httplib::detail::zstd_decompressor decompressor;
  9162. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9163. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9164. size_t chunk_size = 130;
  9165. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9166. chunk_begin += chunk_size) {
  9167. size_t current_chunk_size =
  9168. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9169. bool result = decompressor.decompress(
  9170. compressed_data.data() + chunk_begin, current_chunk_size,
  9171. [&](const char *decompressed_data_chunk,
  9172. size_t decompressed_data_chunk_size) {
  9173. decompressed_data.insert(decompressed_data.size(),
  9174. decompressed_data_chunk,
  9175. decompressed_data_chunk_size);
  9176. return true;
  9177. });
  9178. ASSERT_TRUE(result);
  9179. }
  9180. }
  9181. ASSERT_EQ(data, decompressed_data);
  9182. }
  9183. TEST(ZstdDecompressor, Decompress) {
  9184. std::string original_text = "Compressed with ZSTD";
  9185. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9186. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9187. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9188. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9189. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9190. std::string decompressed_data;
  9191. {
  9192. httplib::detail::zstd_decompressor decompressor;
  9193. bool result = decompressor.decompress(
  9194. compressed_data.data(), compressed_data.size(),
  9195. [&](const char *decompressed_data_chunk,
  9196. size_t decompressed_data_chunk_size) {
  9197. decompressed_data.insert(decompressed_data.size(),
  9198. decompressed_data_chunk,
  9199. decompressed_data_chunk_size);
  9200. return true;
  9201. });
  9202. ASSERT_TRUE(result);
  9203. }
  9204. ASSERT_EQ(original_text, decompressed_data);
  9205. }
  9206. #endif
  9207. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9208. // separate chunks so that the server sees each part in its own read(). Used to
  9209. // place a read boundary at a specific offset of a request body.
  9210. static bool send_request_in_parts(time_t read_timeout_sec,
  9211. const std::vector<std::string> &parts,
  9212. std::string *resp = nullptr,
  9213. int port = PORT) {
  9214. auto error = Error::Success;
  9215. auto client_sock = detail::create_client_socket(
  9216. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9217. /*connection_timeout_sec=*/5, 0,
  9218. /*read_timeout_sec=*/5, 0,
  9219. /*write_timeout_sec=*/5, 0, std::string(), error);
  9220. if (client_sock == INVALID_SOCKET) { return false; }
  9221. auto ret = detail::process_client_socket(
  9222. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9223. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9224. for (size_t i = 0; i < parts.size(); i++) {
  9225. const auto &part = parts[i];
  9226. if (part.size() !=
  9227. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9228. return false;
  9229. }
  9230. if (i + 1 < parts.size()) {
  9231. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9232. }
  9233. }
  9234. char buf[512];
  9235. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9236. while (line_reader.getline()) {
  9237. if (resp) { *resp += line_reader.ptr(); }
  9238. }
  9239. return true;
  9240. });
  9241. detail::close_socket(client_sock);
  9242. return ret;
  9243. }
  9244. // Sends a raw request to a server listening at HOST:PORT.
  9245. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9246. std::string *resp = nullptr, int port = PORT) {
  9247. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9248. }
  9249. #ifdef CPPHTTPLIB_SSL_ENABLED
  9250. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9251. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9252. ASSERT_TRUE(svr.is_valid());
  9253. svr.set_read_timeout(1, 0);
  9254. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9255. auto se = detail::scope_exit([&] {
  9256. svr.stop();
  9257. t.join();
  9258. ASSERT_FALSE(svr.is_running());
  9259. });
  9260. svr.wait_until_ready();
  9261. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9262. // keeps each wait well within the read timeout. The server gives up a
  9263. // second in, so the bytes sent after that fail.
  9264. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9265. parts.resize(26, std::string(1, '\0'));
  9266. EXPECT_FALSE(send_request_in_parts(5, parts));
  9267. }
  9268. #endif
  9269. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9270. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9271. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9272. const std::vector<std::string> &parts,
  9273. std::string *resp = nullptr,
  9274. int port = PORT) {
  9275. auto error = Error::Success;
  9276. auto sock = detail::create_client_socket(
  9277. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9278. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9279. /*write_timeout_sec=*/5, 0, std::string(), error);
  9280. if (sock == INVALID_SOCKET) { return false; }
  9281. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9282. auto ctx = SSL_CTX_new(TLS_client_method());
  9283. auto ssl = SSL_new(ctx);
  9284. auto ssl_se = detail::scope_exit([&] {
  9285. SSL_free(ssl);
  9286. SSL_CTX_free(ctx);
  9287. });
  9288. SSL_set_fd(ssl, static_cast<int>(sock));
  9289. if (SSL_connect(ssl) != 1) { return false; }
  9290. for (size_t i = 0; i < parts.size(); i++) {
  9291. const auto &part = parts[i];
  9292. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9293. static_cast<int>(part.size())) {
  9294. return false;
  9295. }
  9296. if (i + 1 < parts.size()) {
  9297. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9298. }
  9299. }
  9300. char buf[512];
  9301. int n;
  9302. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9303. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9304. }
  9305. return true;
  9306. }
  9307. #endif
  9308. // The request line, then a header value a byte at a time.
  9309. static std::vector<std::string> slow_request_head_parts() {
  9310. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9311. parts.resize(26, "a");
  9312. parts.emplace_back("\r\n\r\n");
  9313. return parts;
  9314. }
  9315. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9316. // within the one-second read timeout. The server gives up a second in, before
  9317. // the head is complete.
  9318. static void
  9319. expect_slow_request_head_dropped(Server &svr,
  9320. const std::function<std::string()> &send) {
  9321. std::atomic<bool> handled(false);
  9322. svr.Get("/", [&](const Request &, Response &res) {
  9323. handled = true;
  9324. res.set_content("ok", "text/plain");
  9325. });
  9326. svr.set_read_timeout(1, 0);
  9327. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9328. auto se = detail::scope_exit([&] {
  9329. svr.stop();
  9330. t.join();
  9331. ASSERT_FALSE(svr.is_running());
  9332. });
  9333. svr.wait_until_ready();
  9334. auto resp = send();
  9335. EXPECT_FALSE(handled);
  9336. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9337. }
  9338. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9339. Server svr;
  9340. expect_slow_request_head_dropped(svr, [] {
  9341. std::string resp;
  9342. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9343. return resp;
  9344. });
  9345. }
  9346. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9347. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9349. ASSERT_TRUE(svr.is_valid());
  9350. expect_slow_request_head_dropped(svr, [] {
  9351. std::string resp;
  9352. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9353. return resp;
  9354. });
  9355. }
  9356. #endif
  9357. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9358. Server svr;
  9359. std::string header_value;
  9360. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9361. header_value = req.get_header_value("foo");
  9362. res.set_content("ok", "text/plain");
  9363. });
  9364. thread t = thread([&] { svr.listen(HOST, PORT); });
  9365. auto se = detail::scope_exit([&] {
  9366. svr.stop();
  9367. t.join();
  9368. ASSERT_FALSE(svr.is_running());
  9369. });
  9370. svr.wait_until_ready();
  9371. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9372. // like characters are not treated the same - use vertical tab and escape.
  9373. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9374. "foo: \t \v bar \x1B\t \r\n"
  9375. "Connection: close\r\n"
  9376. "\r\n";
  9377. std::string res;
  9378. ASSERT_TRUE(send_request(5, req, &res));
  9379. EXPECT_EQ(header_value, "");
  9380. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9381. }
  9382. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9383. Server svr;
  9384. std::string received;
  9385. svr.Get("/order", [&](const Request &req, Response &res) {
  9386. received = entries_to_string(req.headers);
  9387. res.set_content("ok", "text/plain");
  9388. });
  9389. auto port = svr.bind_to_any_port(HOST);
  9390. thread t = thread([&] { svr.listen_after_bind(); });
  9391. auto se = detail::scope_exit([&] {
  9392. svr.stop();
  9393. t.join();
  9394. ASSERT_FALSE(svr.is_running());
  9395. });
  9396. svr.wait_until_ready();
  9397. const std::string req = "GET /order HTTP/1.1\r\n"
  9398. "Host: localhost\r\n"
  9399. "X-First: 1\r\n"
  9400. "X-Dup: a\r\n"
  9401. "X-Second: 2\r\n"
  9402. "X-Dup: b\r\n"
  9403. "Connection: close\r\n"
  9404. "\r\n";
  9405. std::string res;
  9406. ASSERT_TRUE(send_request(5, req, &res, port));
  9407. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9408. EXPECT_EQ(
  9409. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9410. received);
  9411. }
  9412. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9413. Server svr;
  9414. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9415. res.set_header("Set-Cookie", "first=1");
  9416. res.set_header("X-Between", "y");
  9417. res.set_header("Set-Cookie", "second=2");
  9418. res.set_content("ok", "text/plain");
  9419. });
  9420. auto port = svr.bind_to_any_port(HOST);
  9421. thread t = thread([&] { svr.listen_after_bind(); });
  9422. auto se = detail::scope_exit([&] {
  9423. svr.stop();
  9424. t.join();
  9425. ASSERT_FALSE(svr.is_running());
  9426. });
  9427. svr.wait_until_ready();
  9428. Client cli(HOST, port);
  9429. auto res = cli.Get("/cookies");
  9430. ASSERT_TRUE(res);
  9431. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9432. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9433. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9434. }
  9435. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9436. Server svr;
  9437. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9438. auto i = new int(0);
  9439. res.set_header("Trailer", "X-Safe, X-Reflected");
  9440. res.set_chunked_content_provider(
  9441. "text/plain",
  9442. [i](size_t /*offset*/, DataSink &sink) {
  9443. if (*i == 0) {
  9444. sink.os << "body";
  9445. } else {
  9446. Headers trailer;
  9447. // A valid trailer that must survive.
  9448. trailer.emplace("X-Safe", "safe");
  9449. // Attacker-controlled value carrying CR/LF (response splitting).
  9450. trailer.emplace("X-Reflected",
  9451. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9452. // Attacker-controlled name carrying CR/LF.
  9453. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9454. sink.done_with_trailer(trailer);
  9455. }
  9456. (*i)++;
  9457. return true;
  9458. },
  9459. [i](bool /*success*/) { delete i; });
  9460. });
  9461. thread t = thread([&] { svr.listen(HOST, PORT); });
  9462. auto se = detail::scope_exit([&] {
  9463. svr.stop();
  9464. t.join();
  9465. ASSERT_FALSE(svr.is_running());
  9466. });
  9467. svr.wait_until_ready();
  9468. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9469. "Host: " + HOST +
  9470. "\r\n"
  9471. "Connection: close\r\n"
  9472. "\r\n";
  9473. std::string res;
  9474. ASSERT_TRUE(send_request(5, req, &res));
  9475. // The injected fields must not appear anywhere in the raw response.
  9476. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9477. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9478. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9479. // Invalid trailers are dropped entirely, matching set_header().
  9480. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9481. // The valid trailer still passes through.
  9482. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9483. }
  9484. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9485. Server svr;
  9486. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9487. // res.headers is a public field an application can populate directly,
  9488. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9489. // A valid header that must survive.
  9490. res.headers.emplace("X-Safe", "safe");
  9491. // Attacker-controlled value carrying CR/LF (response splitting).
  9492. res.headers.emplace("X-Reflected",
  9493. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9494. // Attacker-controlled name carrying CR/LF.
  9495. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9496. res.set_content("body", "text/plain");
  9497. });
  9498. thread t = thread([&] { svr.listen(HOST, PORT); });
  9499. auto se = detail::scope_exit([&] {
  9500. svr.stop();
  9501. t.join();
  9502. ASSERT_FALSE(svr.is_running());
  9503. });
  9504. svr.wait_until_ready();
  9505. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9506. "Host: " + HOST +
  9507. "\r\n"
  9508. "Connection: close\r\n"
  9509. "\r\n";
  9510. std::string res;
  9511. ASSERT_TRUE(send_request(5, req, &res));
  9512. // The injected fields must not appear anywhere in the raw response.
  9513. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9514. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9515. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9516. // Invalid headers are dropped entirely, matching set_header().
  9517. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9518. // The valid header still passes through.
  9519. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9520. }
  9521. // Forward declaration: in split builds split.py strips `inline` and moves the
  9522. // definition into httplib.cc, so detail::write_request_line is not visible from
  9523. // the public httplib.h. Re-declaring it here lets the tests link against the
  9524. // symbol in both header-only and split builds.
  9525. namespace httplib {
  9526. namespace detail {
  9527. ssize_t write_request_line(Stream &strm, const std::string &method,
  9528. const std::string &path);
  9529. } // namespace detail
  9530. } // namespace httplib
  9531. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9532. // A well-formed target is written verbatim.
  9533. {
  9534. detail::BufferStream strm;
  9535. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9536. EXPECT_GT(n, 0);
  9537. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9538. }
  9539. // A target carrying CR/LF, SP or other control octets must be rejected
  9540. // before anything reaches the wire, otherwise it splits the request line and
  9541. // injects a header or a whole request.
  9542. const std::string evil_targets[] = {
  9543. "/a\r\nInjected: pwned",
  9544. "/a\rInjected",
  9545. "/a\nInjected",
  9546. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9547. "/a b",
  9548. "/a\tb",
  9549. "/a\x7f",
  9550. };
  9551. for (const auto &evil : evil_targets) {
  9552. detail::BufferStream strm;
  9553. auto n = detail::write_request_line(strm, "GET", evil);
  9554. EXPECT_LT(n, 0);
  9555. EXPECT_TRUE(strm.get_buffer().empty());
  9556. }
  9557. }
  9558. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9559. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9560. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9561. // target reaches write_request. The client must fail cleanly with
  9562. // Error::Write instead of putting a request-line-less, header-injecting
  9563. // request on the wire.
  9564. Server svr;
  9565. svr.Get("/a", [](const Request &, Response &res) {
  9566. res.set_content("ok", "text/plain");
  9567. });
  9568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9569. auto se = detail::scope_exit([&] {
  9570. svr.stop();
  9571. thread.join();
  9572. ASSERT_FALSE(svr.is_running());
  9573. });
  9574. svr.wait_until_ready();
  9575. {
  9576. Client cli(HOST, PORT);
  9577. cli.set_path_encode(false);
  9578. // The request is rejected before anything is written, so the connection
  9579. // stays silent and the subsequent response read would otherwise block for
  9580. // the full default read timeout. Shorten it -- the assertion is on the
  9581. // error, not the timeout.
  9582. cli.set_read_timeout(1, 0);
  9583. auto res = cli.Get("/a\r\nInjected: pwned");
  9584. EXPECT_FALSE(res);
  9585. EXPECT_EQ(Error::Write, res.error());
  9586. }
  9587. }
  9588. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9589. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9590. // including extension methods.
  9591. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9592. for (const auto &method : good_methods) {
  9593. detail::BufferStream strm;
  9594. auto n = detail::write_request_line(strm, method, "/");
  9595. EXPECT_GT(n, 0);
  9596. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9597. }
  9598. // A method carrying CR/LF would split the request line and smuggle a whole
  9599. // request ahead of the real one. A space or an empty method corrupts the
  9600. // request line. All must be rejected before anything reaches the wire.
  9601. const std::string evil_methods[] = {
  9602. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9603. "GET\r\nInjected: pwned",
  9604. "GET\r",
  9605. "GET\n",
  9606. "GE T",
  9607. "",
  9608. };
  9609. for (const auto &evil : evil_methods) {
  9610. detail::BufferStream strm;
  9611. auto n = detail::write_request_line(strm, evil, "/");
  9612. EXPECT_LT(n, 0);
  9613. EXPECT_TRUE(strm.get_buffer().empty());
  9614. }
  9615. }
  9616. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9617. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9618. // through Client::send must fail with Error::Write and no request, neither
  9619. // the smuggled one nor the real one, may reach the server.
  9620. Server svr;
  9621. std::atomic<int> request_count(0);
  9622. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9623. request_count++;
  9624. res.status = StatusCode::OK_200;
  9625. return Server::HandlerResponse::Handled;
  9626. });
  9627. auto port = svr.bind_to_any_port(HOST);
  9628. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9629. auto se = detail::scope_exit([&] {
  9630. svr.stop();
  9631. thread.join();
  9632. ASSERT_FALSE(svr.is_running());
  9633. });
  9634. svr.wait_until_ready();
  9635. {
  9636. Client cli(HOST, port);
  9637. const std::string evil_methods[] = {
  9638. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9639. "GE T",
  9640. "",
  9641. };
  9642. for (const auto &evil : evil_methods) {
  9643. Request req;
  9644. req.method = evil;
  9645. req.path = "/";
  9646. auto res = cli.send(req);
  9647. EXPECT_FALSE(res);
  9648. EXPECT_EQ(Error::Write, res.error());
  9649. }
  9650. auto handle =
  9651. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9652. EXPECT_FALSE(handle.is_valid());
  9653. EXPECT_EQ(Error::Write, handle.error);
  9654. // A valid request on the same client still goes through.
  9655. auto res = cli.Get("/");
  9656. ASSERT_TRUE(res);
  9657. EXPECT_EQ(StatusCode::OK_200, res->status);
  9658. }
  9659. EXPECT_EQ(1, request_count.load());
  9660. }
  9661. // Sends a raw request and verifies that there isn't a crash or exception.
  9662. static void test_raw_request(const std::string &req,
  9663. std::string *out = nullptr) {
  9664. Server svr;
  9665. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9666. res.set_content("ok", "text/plain");
  9667. });
  9668. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9669. res.set_content("ok", "text/plain");
  9670. });
  9671. svr.Get("/header_field_value_check",
  9672. [&](const Request & /*req*/, Response &res) {
  9673. res.set_content("ok", "text/plain");
  9674. });
  9675. svr.CustomRoute("PROPFIND", "/dav",
  9676. [&](const Request & /*req*/, Response &res) {
  9677. res.status = StatusCode::MultiStatus_207;
  9678. });
  9679. // Server read timeout must be longer than the client read timeout for the
  9680. // bug to reproduce, probably to force the server to process a request
  9681. // without a trailing blank line.
  9682. const time_t client_read_timeout_sec = 1;
  9683. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9684. bool listen_thread_ok = false;
  9685. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9686. auto se = detail::scope_exit([&] {
  9687. svr.stop();
  9688. t.join();
  9689. ASSERT_FALSE(svr.is_running());
  9690. EXPECT_TRUE(listen_thread_ok);
  9691. });
  9692. svr.wait_until_ready();
  9693. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9694. }
  9695. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9696. // A certain header line causes an exception if the header property is parsed
  9697. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9698. test_raw_request(
  9699. "GET /hi HTTP/1.1\r\n"
  9700. " : "
  9701. " "
  9702. " ");
  9703. }
  9704. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9705. // A certain header line causes an exception if the header property *name* is
  9706. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9707. // greedy matcher and requires backtracking when there are a lot of ":"
  9708. // characters.
  9709. // This occurs with libc++ but not libstdc++.
  9710. test_raw_request(
  9711. "GET /hi HTTP/1.1\r\n"
  9712. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9713. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9714. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9715. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9716. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9717. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9718. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9719. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9720. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9721. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9722. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9723. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9724. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9725. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9726. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9727. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9728. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9729. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9730. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9731. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9732. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9733. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9734. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9735. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9736. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9737. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9738. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9739. "&&&%%%");
  9740. }
  9741. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9742. // Make sure this doesn't crash the server.
  9743. // In a previous version of the header line regex, the "\r" rendered the line
  9744. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9745. // a new position where the leading white space ended and the field value
  9746. // began.
  9747. // The crash occurs with libc++ but not libstdc++.
  9748. test_raw_request("GET /hi HTTP/1.1\r\n"
  9749. "a:" +
  9750. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9751. "\r\n"
  9752. "\r\n");
  9753. }
  9754. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9755. const char *rejected[] = {
  9756. // RFC 9112 §3: one SP between the parts, and nothing else
  9757. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9758. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9759. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9760. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9761. // A request-target has no fragment
  9762. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9763. // An HTTP/1.1 request needs a Host
  9764. "GET /hi HTTP/1.1\r\n\r\n",
  9765. };
  9766. for (auto request : rejected) {
  9767. std::string out;
  9768. test_raw_request(request, &out);
  9769. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9770. }
  9771. std::string out;
  9772. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9773. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9774. }
  9775. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9776. // RFC 9112 §6.1
  9777. const char *requests[] = {
  9778. "PUT /put_hi HTTP/1.1\r\n"
  9779. "Host: localhost\r\n"
  9780. "Content-Length: 0\r\n"
  9781. "Transfer-Encoding: chunked\r\n"
  9782. "\r\n"
  9783. "0\r\n\r\n",
  9784. "PUT /put_hi HTTP/1.0\r\n"
  9785. "Connection: keep-alive\r\n"
  9786. "Transfer-Encoding: chunked\r\n"
  9787. "\r\n"
  9788. "0\r\n\r\n",
  9789. };
  9790. for (auto request : requests) {
  9791. std::string out;
  9792. test_raw_request(request, &out);
  9793. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9794. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9795. }
  9796. }
  9797. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9798. std::string out;
  9799. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9800. "Content-Type: text/plain\r\n"
  9801. "Transfer-Encoding: chunked\r\n"
  9802. "\r\n"
  9803. "nothex\r\n",
  9804. &out);
  9805. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9806. }
  9807. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9808. std::string out;
  9809. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9810. "Content-Type: text/plain\r\n"
  9811. "Transfer-Encoding: chunked\r\n"
  9812. "\r\n"
  9813. "3\r\n"
  9814. "xyz\r\n"
  9815. "NaN\r\n",
  9816. &out);
  9817. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9818. }
  9819. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9820. std::string out;
  9821. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9822. "Content-Type: text/plain\r\n"
  9823. "Transfer-Encoding: chunked\r\n"
  9824. "\r\n"
  9825. // Length is too large for 64 bits.
  9826. "1ffffffffffffffff\r\n"
  9827. "xyz\r\n",
  9828. &out);
  9829. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9830. }
  9831. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9832. test_raw_request("GET /hi HTTP/1.1\r\n"
  9833. "Content-Type: text/plain\r\n\r");
  9834. }
  9835. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9836. std::string out;
  9837. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9838. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9839. }
  9840. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9841. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9842. std::string out;
  9843. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9844. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9845. }
  9846. }
  9847. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9848. std::string out;
  9849. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9850. "Host: localhost\r\n"
  9851. "Connection: close\r\n\r\n",
  9852. &out);
  9853. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9854. }
  9855. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9856. Server svr;
  9857. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9858. EXPECT_TRUE(!req.remote_addr.empty());
  9859. });
  9860. thread t = thread([&] { svr.listen(HOST, PORT); });
  9861. auto se = detail::scope_exit([&] {
  9862. svr.stop();
  9863. t.join();
  9864. ASSERT_FALSE(svr.is_running());
  9865. });
  9866. svr.wait_until_ready();
  9867. // Send an invalid request line to trigger Bad Request
  9868. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9869. std::string out;
  9870. ASSERT_TRUE(send_request(5, bad_req, &out));
  9871. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9872. }
  9873. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9874. // answered right away rather than blocking on a read that waits for EOF.
  9875. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9876. std::string out;
  9877. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9878. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9879. }
  9880. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9881. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9882. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9883. for (const auto *method : methods) {
  9884. Server svr;
  9885. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9886. EXPECT_FALSE(svr.is_valid()) << method;
  9887. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9888. }
  9889. }
  9890. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9891. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9892. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9893. for (const auto *method : methods) {
  9894. Server svr;
  9895. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9896. EXPECT_FALSE(svr.is_valid()) << method;
  9897. }
  9898. }
  9899. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9900. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9901. "COPY", "MOVE", "LOCK",
  9902. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9903. Server svr;
  9904. for (const auto *method : methods) {
  9905. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9906. }
  9907. EXPECT_TRUE(svr.is_valid());
  9908. }
  9909. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9910. Server svr;
  9911. svr.CustomRoute("POST", "/x",
  9912. [](const Request &, Response &, const ContentReader &) {});
  9913. EXPECT_FALSE(svr.is_valid());
  9914. }
  9915. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9916. Server svr;
  9917. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9918. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9919. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9920. EXPECT_FALSE(svr.is_valid());
  9921. }
  9922. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9923. Server svr;
  9924. auto captured = Error::Success;
  9925. svr.set_error_logger(
  9926. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9927. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9928. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9929. }
  9930. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9931. std::string out;
  9932. std::string request(
  9933. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9934. test_raw_request(request, &out);
  9935. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9936. }
  9937. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9938. std::string out;
  9939. std::string request(
  9940. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9941. test_raw_request(request, &out);
  9942. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9943. }
  9944. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9945. std::string out;
  9946. std::string request(
  9947. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9948. test_raw_request(request, &out);
  9949. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9950. }
  9951. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9952. std::string out;
  9953. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9954. "Host: localhost\r\n"
  9955. "Test: \r\n\r\n",
  9956. &out);
  9957. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9958. }
  9959. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9960. Server svr;
  9961. std::string x_custom;
  9962. std::string cookie;
  9963. std::string xff;
  9964. std::string x_unicode;
  9965. std::string x_iis;
  9966. svr.Get("/check", [&](const Request &req, Response &res) {
  9967. x_custom = req.get_header_value("X-Custom");
  9968. cookie = req.get_header_value("Cookie");
  9969. xff = req.get_header_value("X-Forwarded-For");
  9970. x_unicode = req.get_header_value("X-Unicode");
  9971. x_iis = req.get_header_value("X-IIS");
  9972. res.set_content("ok", "text/plain");
  9973. });
  9974. thread t = thread([&] { svr.listen(HOST, PORT); });
  9975. auto se = detail::scope_exit([&] {
  9976. svr.stop();
  9977. t.join();
  9978. ASSERT_FALSE(svr.is_running());
  9979. });
  9980. svr.wait_until_ready();
  9981. const std::string req = "GET /check HTTP/1.1\r\n"
  9982. "Host: localhost\r\n"
  9983. "X-Custom: a%0D%0AInjected: b\r\n"
  9984. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9985. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9986. "X-Unicode: %E3%81%82\r\n"
  9987. "X-IIS: %u00E9\r\n"
  9988. "Connection: close\r\n"
  9989. "\r\n";
  9990. std::string res;
  9991. ASSERT_TRUE(send_request(5, req, &res));
  9992. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9993. // Every value must be returned verbatim (wire form), with no decoding.
  9994. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9995. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9996. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9997. EXPECT_EQ("%E3%81%82", x_unicode);
  9998. EXPECT_EQ("%u00E9", x_iis);
  9999. }
  10000. // Applications that previously relied on automatic percent-decoding can
  10001. // reproduce the old behavior by explicitly calling decode_path_component()
  10002. // or, for RFC 3986 conformance, decode_uri_component().
  10003. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10004. Server svr;
  10005. std::string decoded;
  10006. svr.Get("/check", [&](const Request &req, Response &res) {
  10007. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10008. res.set_content("ok", "text/plain");
  10009. });
  10010. thread t = thread([&] { svr.listen(HOST, PORT); });
  10011. auto se = detail::scope_exit([&] {
  10012. svr.stop();
  10013. t.join();
  10014. ASSERT_FALSE(svr.is_running());
  10015. });
  10016. svr.wait_until_ready();
  10017. const std::string req = "GET /check HTTP/1.1\r\n"
  10018. "Host: localhost\r\n"
  10019. "X-Custom: hello%20world\r\n"
  10020. "Connection: close\r\n"
  10021. "\r\n";
  10022. std::string res;
  10023. ASSERT_TRUE(send_request(5, req, &res));
  10024. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10025. EXPECT_EQ("hello world", decoded);
  10026. }
  10027. // Regression test for #2033. Browsers send Referer values that include
  10028. // percent-encoded characters such as %0A inside the URL. Decoding the
  10029. // header value would either trip the post-decode CR/LF/NUL guard (the
  10030. // original bug, returning 400) or, after that guard was relaxed, silently
  10031. // store a literal LF — both unacceptable. The wire form must round-trip.
  10032. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10033. Server svr;
  10034. std::string referer;
  10035. svr.Get("/check", [&](const Request &req, Response &res) {
  10036. referer = req.get_header_value("Referer");
  10037. res.set_content("ok", "text/plain");
  10038. });
  10039. thread t = thread([&] { svr.listen(HOST, PORT); });
  10040. auto se = detail::scope_exit([&] {
  10041. svr.stop();
  10042. t.join();
  10043. ASSERT_FALSE(svr.is_running());
  10044. });
  10045. svr.wait_until_ready();
  10046. const std::string req = "GET /check HTTP/1.1\r\n"
  10047. "Host: localhost\r\n"
  10048. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10049. "Connection: close\r\n"
  10050. "\r\n";
  10051. std::string res;
  10052. ASSERT_TRUE(send_request(5, req, &res));
  10053. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10054. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10055. }
  10056. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10057. Server svr;
  10058. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10059. res.set_header("Cache-Control", "no-cache");
  10060. res.set_chunked_content_provider(
  10061. "text/event-stream", [](size_t offset, DataSink &sink) {
  10062. std::string s = "data:";
  10063. s += std::to_string(offset);
  10064. s += "\n\n";
  10065. auto ret = sink.write(s.data(), s.size());
  10066. EXPECT_TRUE(ret);
  10067. std::this_thread::sleep_for(std::chrono::seconds(1));
  10068. return true;
  10069. });
  10070. });
  10071. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10072. svr.wait_until_ready();
  10073. Client client(HOST, PORT);
  10074. const Headers headers = {{"Accept", "text/event-stream"}};
  10075. auto get_thread = std::thread([&client, &headers]() {
  10076. auto res = client.Get(
  10077. "/events", headers,
  10078. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10079. });
  10080. auto se = detail::scope_exit([&] {
  10081. svr.stop();
  10082. get_thread.join();
  10083. listen_thread.join();
  10084. ASSERT_FALSE(svr.is_running());
  10085. });
  10086. // Give GET time to get a few messages.
  10087. std::this_thread::sleep_for(std::chrono::seconds(2));
  10088. }
  10089. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10090. httplib::Server svr;
  10091. svr.Post("/hi",
  10092. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10093. res.status = StatusCode::OK_200;
  10094. });
  10095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10096. svr.wait_until_ready();
  10097. Client cli(HOST, PORT);
  10098. auto res = cli.Post("/hi", "data", "text/plain");
  10099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10100. EXPECT_EQ(StatusCode::OK_200, res->status);
  10101. svr.stop();
  10102. thread.join();
  10103. ASSERT_FALSE(svr.is_running());
  10104. res = cli.Post("/hi", "data", "text/plain");
  10105. ASSERT_FALSE(res);
  10106. }
  10107. TEST(ServerStopTest, ListenFailure) {
  10108. Server svr;
  10109. auto t = thread([&]() {
  10110. auto ret = svr.listen("????", PORT);
  10111. EXPECT_FALSE(ret);
  10112. });
  10113. svr.wait_until_ready();
  10114. svr.stop();
  10115. t.join();
  10116. }
  10117. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10118. TEST(ServerStopTest, Decommision) {
  10119. Server svr;
  10120. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10121. for (int i = 0; i < 4; i++) {
  10122. auto is_even = !(i % 2);
  10123. std::thread t{[&] {
  10124. try {
  10125. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10126. if (is_even) {
  10127. throw std::runtime_error("Some thing that happens to go wrong.");
  10128. }
  10129. svr.listen(HOST, PORT);
  10130. } catch (...) { svr.decommission(); }
  10131. }};
  10132. svr.wait_until_ready();
  10133. // Server is up
  10134. {
  10135. Client cli(HOST, PORT);
  10136. auto res = cli.Get("/hi");
  10137. if (is_even) {
  10138. EXPECT_FALSE(res);
  10139. } else {
  10140. EXPECT_TRUE(res);
  10141. EXPECT_EQ("hi...", res->body);
  10142. }
  10143. }
  10144. svr.stop();
  10145. t.join();
  10146. // Server is down...
  10147. {
  10148. Client cli(HOST, PORT);
  10149. auto res = cli.Get("/hi");
  10150. EXPECT_FALSE(res);
  10151. }
  10152. }
  10153. }
  10154. #endif
  10155. // Helper function for string body upload progress tests
  10156. template <typename SetupHandler, typename ClientCall>
  10157. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10158. ClientCall &&client_call,
  10159. const string &body) {
  10160. Server svr;
  10161. setup_handler(svr);
  10162. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10163. auto se = detail::scope_exit([&] {
  10164. svr.stop();
  10165. t.join();
  10166. });
  10167. svr.wait_until_ready();
  10168. Client cli(HOST, PORT);
  10169. vector<uint64_t> progress_values;
  10170. bool progress_called = false;
  10171. auto res =
  10172. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10173. progress_values.push_back(current);
  10174. progress_called = true;
  10175. return true;
  10176. });
  10177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10178. EXPECT_EQ(200, res->status);
  10179. EXPECT_TRUE(progress_called);
  10180. }
  10181. TEST(UploadProgressTest, PostStringBodyBasic) {
  10182. TestStringBodyUploadProgress(
  10183. [](Server &svr) {
  10184. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10185. res.set_content("received", "text/plain");
  10186. });
  10187. },
  10188. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10189. return cli.Post("/test", body, "text/plain", progress_callback);
  10190. },
  10191. "test data for upload progress");
  10192. }
  10193. TEST(UploadProgressTest, PutStringBodyBasic) {
  10194. TestStringBodyUploadProgress(
  10195. [](Server &svr) {
  10196. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10197. res.set_content("put received", "text/plain");
  10198. });
  10199. },
  10200. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10201. return cli.Put("/test", body, "text/plain", progress_callback);
  10202. },
  10203. "put test data for upload progress");
  10204. }
  10205. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10206. TestStringBodyUploadProgress(
  10207. [](Server &svr) {
  10208. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10209. res.set_content("patch received", "text/plain");
  10210. });
  10211. },
  10212. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10213. return cli.Patch("/test", body, "text/plain", progress_callback);
  10214. },
  10215. "patch test data for upload progress");
  10216. }
  10217. // Helper function for content provider upload progress tests
  10218. template <typename SetupHandler, typename ClientCall>
  10219. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10220. ClientCall &&client_call) {
  10221. Server svr;
  10222. setup_handler(svr);
  10223. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10224. auto se = detail::scope_exit([&] {
  10225. svr.stop();
  10226. t.join();
  10227. });
  10228. svr.wait_until_ready();
  10229. Client cli(HOST, PORT);
  10230. vector<uint64_t> progress_values;
  10231. auto res =
  10232. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10233. progress_values.push_back(current);
  10234. return true;
  10235. });
  10236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10237. EXPECT_EQ(200, res->status);
  10238. EXPECT_FALSE(progress_values.empty());
  10239. }
  10240. TEST(UploadProgressTest, PostContentProviderProgress) {
  10241. TestContentProviderUploadProgress(
  10242. [](Server &svr) {
  10243. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10244. res.set_content("provider received", "text/plain");
  10245. });
  10246. },
  10247. [](Client &cli, UploadProgress progress_callback) {
  10248. return cli.Post(
  10249. "/test", 9,
  10250. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10251. sink.os << "test data";
  10252. return true;
  10253. },
  10254. "text/plain", progress_callback);
  10255. });
  10256. }
  10257. // Helper function for multipart upload progress tests
  10258. template <typename SetupHandler, typename ClientCall>
  10259. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10260. ClientCall &&client_call,
  10261. const string &endpoint) {
  10262. Server svr;
  10263. setup_handler(svr);
  10264. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10265. auto se = detail::scope_exit([&] {
  10266. svr.stop();
  10267. t.join();
  10268. });
  10269. svr.wait_until_ready();
  10270. Client cli(HOST, PORT);
  10271. vector<uint64_t> progress_values;
  10272. UploadFormDataItems items = {
  10273. {"field1", "value1", "", ""},
  10274. {"field2", "longer value for progress tracking test", "", ""},
  10275. {"file1", "file content data for upload progress", "test.txt",
  10276. "text/plain"}};
  10277. auto res = client_call(cli, endpoint, items,
  10278. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10279. progress_values.push_back(current);
  10280. return true;
  10281. });
  10282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10283. EXPECT_EQ(200, res->status);
  10284. EXPECT_FALSE(progress_values.empty());
  10285. }
  10286. TEST(UploadProgressTest, PostMultipartProgress) {
  10287. TestMultipartUploadProgress(
  10288. [](Server &svr) {
  10289. svr.Post("/multipart", [](const Request &req, Response &res) {
  10290. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10291. res.set_content("multipart received", "text/plain");
  10292. });
  10293. },
  10294. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10295. UploadProgress progress_callback) {
  10296. return cli.Post(endpoint, items, progress_callback);
  10297. },
  10298. "/multipart");
  10299. }
  10300. // Helper function for basic download progress tests
  10301. template <typename SetupHandler, typename ClientCall>
  10302. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10303. ClientCall &&client_call, const string &endpoint,
  10304. size_t expected_content_size) {
  10305. Server svr;
  10306. setup_handler(svr);
  10307. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10308. auto se = detail::scope_exit([&] {
  10309. svr.stop();
  10310. t.join();
  10311. });
  10312. svr.wait_until_ready();
  10313. Client cli(HOST, PORT);
  10314. vector<uint64_t> progress_values;
  10315. auto res = client_call(cli, endpoint,
  10316. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10317. progress_values.push_back(current);
  10318. return true;
  10319. });
  10320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10321. EXPECT_EQ(200, res->status);
  10322. EXPECT_FALSE(progress_values.empty());
  10323. EXPECT_EQ(expected_content_size, res->body.size());
  10324. }
  10325. TEST(DownloadProgressTest, GetBasic) {
  10326. TestBasicDownloadProgress(
  10327. [](Server &svr) {
  10328. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10329. string content(1000, 'D');
  10330. res.set_content(content, "text/plain");
  10331. });
  10332. },
  10333. [](Client &cli, const string &endpoint,
  10334. DownloadProgress progress_callback) {
  10335. return cli.Get(endpoint, progress_callback);
  10336. },
  10337. "/download", 1000u);
  10338. }
  10339. // Helper function for content receiver download progress tests
  10340. template <typename SetupHandler, typename ClientCall>
  10341. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10342. ClientCall &&client_call,
  10343. const string &endpoint,
  10344. size_t expected_content_size) {
  10345. Server svr;
  10346. setup_handler(svr);
  10347. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10348. auto se = detail::scope_exit([&] {
  10349. svr.stop();
  10350. t.join();
  10351. });
  10352. svr.wait_until_ready();
  10353. Client cli(HOST, PORT);
  10354. vector<uint64_t> progress_values;
  10355. string received_body;
  10356. auto res = client_call(
  10357. cli, endpoint,
  10358. [&](const char *data, size_t data_length) -> bool {
  10359. received_body.append(data, data_length);
  10360. return true;
  10361. },
  10362. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10363. progress_values.push_back(current);
  10364. return true;
  10365. });
  10366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10367. EXPECT_EQ(200, res->status);
  10368. EXPECT_FALSE(progress_values.empty());
  10369. EXPECT_EQ(expected_content_size, received_body.size());
  10370. EXPECT_TRUE(res->body.empty());
  10371. }
  10372. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10373. TestContentReceiverDownloadProgress(
  10374. [](Server &svr) {
  10375. svr.Get("/download-receiver",
  10376. [](const Request & /*req*/, Response &res) {
  10377. string content(2000, 'R');
  10378. res.set_content(content, "text/plain");
  10379. });
  10380. },
  10381. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10382. DownloadProgress progress_callback) {
  10383. return cli.Get(endpoint, content_receiver, progress_callback);
  10384. },
  10385. "/download-receiver", 2000u);
  10386. }
  10387. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10388. // A provider reaching a pass with nothing to hand over - an empty buffer
  10389. // popped off a queue, say - must not be taken to mean the body is finished.
  10390. // It used to end the loop with the terminating chunk unwritten while the
  10391. // server still considered the response complete, so the peer waited for an
  10392. // end that never arrived.
  10393. Server svr;
  10394. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10395. auto step = std::make_shared<int>(0);
  10396. res.set_chunked_content_provider("text/plain",
  10397. [step](size_t /*offset*/, DataSink &sink) {
  10398. switch ((*step)++) {
  10399. case 0: sink.write("", 0); break;
  10400. case 1: sink.write("hello", 5); break;
  10401. default: sink.done(); break;
  10402. }
  10403. return true;
  10404. });
  10405. });
  10406. auto port = svr.bind_to_any_port(HOST);
  10407. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10408. auto listen_se = detail::scope_exit([&] {
  10409. svr.stop();
  10410. listen_thread.join();
  10411. ASSERT_FALSE(svr.is_running());
  10412. });
  10413. svr.wait_until_ready();
  10414. Client cli(HOST, port);
  10415. // Without the fix the body is never terminated, so bound the wait rather
  10416. // than letting the test hang on the default read timeout.
  10417. cli.set_read_timeout(5, 0);
  10418. auto res = cli.Get("/stream");
  10419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10420. EXPECT_EQ(StatusCode::OK_200, res->status);
  10421. EXPECT_EQ("hello", res->body);
  10422. }
  10423. TEST(StreamingTest, NoContentLengthStreaming) {
  10424. Server svr;
  10425. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10426. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10427. if (offset < 6) {
  10428. sink.os << (offset < 3 ? "a" : "b");
  10429. } else {
  10430. sink.done();
  10431. }
  10432. return true;
  10433. });
  10434. });
  10435. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10436. auto listen_se = detail::scope_exit([&] {
  10437. svr.stop();
  10438. listen_thread.join();
  10439. ASSERT_FALSE(svr.is_running());
  10440. });
  10441. svr.wait_until_ready();
  10442. Client client(HOST, PORT);
  10443. auto get_thread = std::thread([&client]() {
  10444. std::string s;
  10445. auto res =
  10446. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10447. s += std::string(data, len);
  10448. return true;
  10449. });
  10450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10451. EXPECT_EQ(StatusCode::OK_200, res->status);
  10452. EXPECT_EQ("aaabbb", s);
  10453. });
  10454. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10455. // Give GET time to get a few messages.
  10456. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10457. }
  10458. TEST(MountTest, Unmount) {
  10459. Server svr;
  10460. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10461. auto se = detail::scope_exit([&] {
  10462. svr.stop();
  10463. listen_thread.join();
  10464. ASSERT_FALSE(svr.is_running());
  10465. });
  10466. svr.wait_until_ready();
  10467. Client cli("localhost", PORT);
  10468. svr.set_mount_point("/mount2", "./www2");
  10469. auto res = cli.Get("/");
  10470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10471. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10472. res = cli.Get("/mount2/dir/test.html");
  10473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10474. EXPECT_EQ(StatusCode::OK_200, res->status);
  10475. svr.set_mount_point("/", "./www");
  10476. res = cli.Get("/dir/");
  10477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10478. EXPECT_EQ(StatusCode::OK_200, res->status);
  10479. svr.remove_mount_point("/");
  10480. res = cli.Get("/dir/");
  10481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10482. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10483. svr.remove_mount_point("/mount2");
  10484. res = cli.Get("/mount2/dir/test.html");
  10485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10486. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10487. }
  10488. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10489. Server svr;
  10490. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10491. svr.Get("/api/hello", [](const Request &, Response &res) {
  10492. res.set_content("api", "text/plain");
  10493. });
  10494. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10495. auto se = detail::scope_exit([&] {
  10496. svr.stop();
  10497. listen_thread.join();
  10498. ASSERT_FALSE(svr.is_running());
  10499. });
  10500. svr.wait_until_ready();
  10501. Client cli(HOST, PORT);
  10502. auto res = cli.Get("/dir/test.html");
  10503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10504. EXPECT_EQ(StatusCode::OK_200, res->status);
  10505. res = cli.Get("/api/hello");
  10506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10507. EXPECT_EQ(StatusCode::OK_200, res->status);
  10508. EXPECT_EQ("api", res->body);
  10509. }
  10510. TEST(MountTest, PathSegmentBoundary) {
  10511. Server svr;
  10512. svr.set_mount_point("/mount2", "./www2");
  10513. svr.set_mount_point("/", "./www");
  10514. auto port = svr.bind_to_any_port(HOST);
  10515. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10516. auto se = detail::scope_exit([&] {
  10517. svr.stop();
  10518. listen_thread.join();
  10519. ASSERT_FALSE(svr.is_running());
  10520. });
  10521. svr.wait_until_ready();
  10522. Client cli(HOST, port);
  10523. auto res = cli.Get("/mount2/dir/test.html");
  10524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10525. EXPECT_EQ(StatusCode::OK_200, res->status);
  10526. // "/mount2" must not match part-way through a path segment.
  10527. res = cli.Get("/mount2dir/test.html");
  10528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10530. // A mount point ending in '/' keeps matching every path below it.
  10531. res = cli.Get("/dir/test.html");
  10532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10533. EXPECT_EQ(StatusCode::OK_200, res->status);
  10534. }
  10535. TEST(MountTest, Redicect) {
  10536. Server svr;
  10537. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10538. auto se = detail::scope_exit([&] {
  10539. svr.stop();
  10540. listen_thread.join();
  10541. ASSERT_FALSE(svr.is_running());
  10542. });
  10543. svr.set_mount_point("/", "./www");
  10544. svr.wait_until_ready();
  10545. Client cli("localhost", PORT);
  10546. auto res = cli.Get("/dir/");
  10547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10548. EXPECT_EQ(StatusCode::OK_200, res->status);
  10549. res = cli.Get("/dir");
  10550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10551. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10552. res = cli.Get("/file");
  10553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10554. EXPECT_EQ(StatusCode::OK_200, res->status);
  10555. res = cli.Get("/file/");
  10556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10557. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10558. cli.set_follow_location(true);
  10559. res = cli.Get("/dir");
  10560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10561. EXPECT_EQ(StatusCode::OK_200, res->status);
  10562. }
  10563. TEST(MountTest, MultibytesPathName) {
  10564. Server svr;
  10565. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10566. auto se = detail::scope_exit([&] {
  10567. svr.stop();
  10568. listen_thread.join();
  10569. ASSERT_FALSE(svr.is_running());
  10570. });
  10571. svr.set_mount_point("/", "./www");
  10572. svr.wait_until_ready();
  10573. Client cli("localhost", PORT);
  10574. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10576. EXPECT_EQ(StatusCode::OK_200, res->status);
  10577. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10578. }
  10579. #ifdef _WIN32
  10580. // Issue #2435: mmap::open() must succeed even when another handle holds
  10581. // the file open for writing (e.g. an active log file).
  10582. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10583. const char *path = "mmap_concurrent_writer_test.txt";
  10584. const char *content = "hello";
  10585. {
  10586. std::ofstream f(path, std::ios::binary);
  10587. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10588. }
  10589. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10590. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10591. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10592. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10593. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10594. detail::mmap m(path);
  10595. ASSERT_TRUE(m.is_open());
  10596. EXPECT_EQ(strlen(content), m.size());
  10597. char buf[8];
  10598. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10599. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10600. }
  10601. #endif
  10602. #ifndef _WIN32
  10603. // A directory or a device has no size to serve.
  10604. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10605. const char *path = "./mmap_not_regular_test_dir";
  10606. ASSERT_EQ(0, ::mkdir(path, 0755));
  10607. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10608. for (auto p : {path, "/dev/null"}) {
  10609. detail::mmap m(p);
  10610. EXPECT_FALSE(m.is_open()) << p;
  10611. EXPECT_EQ(0U, m.size()) << p;
  10612. }
  10613. Server svr;
  10614. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10615. res.set_file_content("/dev/null");
  10616. });
  10617. auto port = svr.bind_to_any_port(HOST);
  10618. thread t = thread([&] { svr.listen_after_bind(); });
  10619. auto se = detail::scope_exit([&] {
  10620. svr.stop();
  10621. t.join();
  10622. });
  10623. svr.wait_until_ready();
  10624. auto res = Client(HOST, port).Get("/null");
  10625. ASSERT_TRUE(res);
  10626. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10627. }
  10628. #endif
  10629. #ifdef __linux__
  10630. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10631. TEST(MmapTest, FileIsNotMapped) {
  10632. const char *path = "mmap_not_mapped_test.txt";
  10633. {
  10634. std::ofstream f(path, std::ios::binary);
  10635. f << "hello";
  10636. }
  10637. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10638. detail::mmap m(path);
  10639. ASSERT_TRUE(m.is_open());
  10640. std::ifstream maps("/proc/self/maps");
  10641. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10642. std::istreambuf_iterator<char>());
  10643. EXPECT_EQ(std::string::npos, mappings.find(path));
  10644. }
  10645. #endif
  10646. TEST(KeepAliveTest, ReadTimeout) {
  10647. Server svr;
  10648. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10649. std::this_thread::sleep_for(std::chrono::seconds(2));
  10650. res.set_content("a", "text/plain");
  10651. });
  10652. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10653. res.set_content("b", "text/plain");
  10654. });
  10655. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10656. auto se = detail::scope_exit([&] {
  10657. svr.stop();
  10658. listen_thread.join();
  10659. ASSERT_FALSE(svr.is_running());
  10660. });
  10661. svr.wait_until_ready();
  10662. Client cli("localhost", PORT);
  10663. cli.set_keep_alive(true);
  10664. cli.set_read_timeout(std::chrono::seconds(1));
  10665. auto resa = cli.Get("/a");
  10666. ASSERT_FALSE(resa);
  10667. EXPECT_EQ(Error::Read, resa.error());
  10668. auto resb = cli.Get("/b");
  10669. ASSERT_TRUE(resb);
  10670. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10671. EXPECT_EQ("b", resb->body);
  10672. }
  10673. TEST(KeepAliveTest, MaxCount) {
  10674. size_t keep_alive_max_count = 3;
  10675. Server svr;
  10676. svr.set_keep_alive_max_count(keep_alive_max_count);
  10677. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10678. res.set_content("Hello World!", "text/plain");
  10679. });
  10680. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10681. auto se = detail::scope_exit([&] {
  10682. svr.stop();
  10683. listen_thread.join();
  10684. ASSERT_FALSE(svr.is_running());
  10685. });
  10686. svr.wait_until_ready();
  10687. Client cli(HOST, PORT);
  10688. cli.set_keep_alive(true);
  10689. for (size_t i = 0; i < 5; i++) {
  10690. auto result = cli.Get("/hi");
  10691. ASSERT_TRUE(result);
  10692. EXPECT_EQ(StatusCode::OK_200, result->status);
  10693. if (i == keep_alive_max_count - 1) {
  10694. EXPECT_EQ("close", result->get_header_value("Connection"));
  10695. } else {
  10696. EXPECT_FALSE(result->has_header("Connection"));
  10697. }
  10698. }
  10699. }
  10700. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10701. // can pull the next one into the server's buffer. The server must serve it
  10702. // without waiting for the socket to become readable again. The keep-alive
  10703. // timeout outlasts the client's read timeout, so a request left waiting for it
  10704. // shows up as a missing response.
  10705. static void serve_pipelining_routes(Server &svr,
  10706. const std::function<void(int)> &client) {
  10707. svr.set_keep_alive_timeout(5);
  10708. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10709. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10710. });
  10711. svr.Post("/echo", [](const Request &req, Response &res) {
  10712. res.set_content("echo " + req.body, "text/plain");
  10713. });
  10714. auto port = svr.bind_to_any_port(HOST);
  10715. thread t = thread([&] { svr.listen_after_bind(); });
  10716. auto se = detail::scope_exit([&] {
  10717. svr.stop();
  10718. t.join();
  10719. });
  10720. svr.wait_until_ready();
  10721. client(port);
  10722. }
  10723. static std::string
  10724. send_pipelined_requests(const std::vector<std::string> &parts) {
  10725. Server svr;
  10726. std::string res;
  10727. serve_pipelining_routes(svr, [&](int port) {
  10728. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10729. });
  10730. return res;
  10731. }
  10732. static void expect_in_order(const std::string &res,
  10733. const std::vector<std::string> &bodies) {
  10734. size_t pos = 0;
  10735. for (const auto &body : bodies) {
  10736. pos = res.find(body, pos);
  10737. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10738. pos += body.size();
  10739. }
  10740. }
  10741. TEST(KeepAliveTest, PipelinedRequests) {
  10742. auto res = send_pipelined_requests(
  10743. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10744. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10745. "Content-Length: 4\r\n\r\nbody"
  10746. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10747. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10748. }
  10749. // The second request starts in the server's buffer and ends on the socket.
  10750. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10751. auto res =
  10752. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10753. "GET /hi/2 HTTP/1.1\r\nHo",
  10754. "st: localhost\r\nConnection: close\r\n\r\n"});
  10755. expect_in_order(res, {"hi 1", "hi 2"});
  10756. }
  10757. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10758. // CRLF after a body does not turn into a 400 for the next request.
  10759. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10760. auto res = send_pipelined_requests(
  10761. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10762. "Content-Length: 4\r\n\r\nbody\r\n"
  10763. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10764. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10765. expect_in_order(res, {"echo body", "hi 2"});
  10766. }
  10767. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10768. // must not be served as the next request.
  10769. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10770. auto res = send_pipelined_requests(
  10771. {"INVALID REQUEST LINE\r\n\r\n"
  10772. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10773. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10774. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10775. }
  10776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10777. // Over TLS, the next request is held by the TLS library as already decrypted
  10778. // data rather than on the socket.
  10779. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10781. std::string res;
  10782. serve_pipelining_routes(svr, [&](int port) {
  10783. // One part, so all three requests arrive in one TLS record
  10784. EXPECT_TRUE(send_ssl_request_in_parts(
  10785. 2,
  10786. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10787. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10788. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10789. &res, port));
  10790. });
  10791. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10792. }
  10793. #endif
  10794. TEST(KeepAliveTest, Issue1041) {
  10795. Server svr;
  10796. svr.set_keep_alive_timeout(3);
  10797. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10798. res.set_content("Hello World!", "text/plain");
  10799. });
  10800. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10801. auto se = detail::scope_exit([&] {
  10802. svr.stop();
  10803. listen_thread.join();
  10804. ASSERT_FALSE(svr.is_running());
  10805. });
  10806. svr.wait_until_ready();
  10807. Client cli(HOST, PORT);
  10808. cli.set_keep_alive(true);
  10809. auto result = cli.Get("/hi");
  10810. ASSERT_TRUE(result);
  10811. EXPECT_EQ(StatusCode::OK_200, result->status);
  10812. std::this_thread::sleep_for(std::chrono::seconds(5));
  10813. result = cli.Get("/hi");
  10814. ASSERT_TRUE(result);
  10815. EXPECT_EQ(StatusCode::OK_200, result->status);
  10816. }
  10817. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10818. Server svr;
  10819. svr.set_keep_alive_max_count(0);
  10820. std::set<int> remote_ports;
  10821. svr.Get("/hi", [&](const Request &req, Response &res) {
  10822. remote_ports.insert(req.remote_port);
  10823. res.set_content("hi", "text/plain");
  10824. });
  10825. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10826. auto se = detail::scope_exit([&] {
  10827. svr.stop();
  10828. listen_thread.join();
  10829. ASSERT_FALSE(svr.is_running());
  10830. });
  10831. svr.wait_until_ready();
  10832. Client cli(HOST, PORT);
  10833. cli.set_keep_alive(true);
  10834. for (int i = 0; i < 3; i++) {
  10835. auto res = cli.Get("/hi");
  10836. ASSERT_TRUE(res);
  10837. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10838. }
  10839. // All three over one connection
  10840. EXPECT_EQ(1u, remote_ports.size());
  10841. }
  10842. TEST(KeepAliveTest, Issue1959) {
  10843. Server svr;
  10844. svr.set_keep_alive_timeout(5);
  10845. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10846. res.set_content("a", "text/plain");
  10847. });
  10848. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10849. auto se = detail::scope_exit([&] {
  10850. if (!svr.is_running()) return;
  10851. svr.stop();
  10852. listen_thread.join();
  10853. ASSERT_FALSE(svr.is_running());
  10854. });
  10855. svr.wait_until_ready();
  10856. Client cli("localhost", PORT);
  10857. cli.set_keep_alive(true);
  10858. using namespace std::chrono;
  10859. auto start = steady_clock::now();
  10860. cli.Get("/a");
  10861. svr.stop();
  10862. listen_thread.join();
  10863. auto end = steady_clock::now();
  10864. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10865. EXPECT_LT(elapsed, 5000);
  10866. }
  10867. #ifdef CPPHTTPLIB_SSL_ENABLED
  10868. TEST(KeepAliveTest, SSLClientReconnection) {
  10869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10870. ASSERT_TRUE(svr.is_valid());
  10871. svr.set_keep_alive_timeout(1);
  10872. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10873. res.set_content("Hello World!", "text/plain");
  10874. });
  10875. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10876. auto se = detail::scope_exit([&] {
  10877. svr.stop();
  10878. listen_thread.join();
  10879. ASSERT_FALSE(svr.is_running());
  10880. });
  10881. svr.wait_until_ready();
  10882. SSLClient cli(HOST, PORT);
  10883. cli.enable_server_certificate_verification(false);
  10884. cli.set_keep_alive(true);
  10885. auto result = cli.Get("/hi");
  10886. ASSERT_TRUE(result);
  10887. EXPECT_EQ(StatusCode::OK_200, result->status);
  10888. result = cli.Get("/hi");
  10889. ASSERT_TRUE(result);
  10890. EXPECT_EQ(StatusCode::OK_200, result->status);
  10891. std::this_thread::sleep_for(std::chrono::seconds(2));
  10892. // Recoonect
  10893. result = cli.Get("/hi");
  10894. ASSERT_TRUE(result);
  10895. EXPECT_EQ(StatusCode::OK_200, result->status);
  10896. result = cli.Get("/hi");
  10897. ASSERT_TRUE(result);
  10898. EXPECT_EQ(StatusCode::OK_200, result->status);
  10899. }
  10900. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10902. ASSERT_TRUE(svr.is_valid());
  10903. svr.set_keep_alive_timeout(1);
  10904. std::string content = "reconnect";
  10905. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10906. res.set_content("Hello World!", "text/plain");
  10907. });
  10908. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10909. auto se = detail::scope_exit([&] {
  10910. svr.stop();
  10911. listen_thread.join();
  10912. ASSERT_FALSE(svr.is_running());
  10913. });
  10914. svr.wait_until_ready();
  10915. SSLClient cli(HOST, PORT);
  10916. cli.enable_server_certificate_verification(false);
  10917. cli.set_keep_alive(true);
  10918. auto result = cli.Post(
  10919. "/hi", content.size(),
  10920. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10921. sink.write(content.c_str(), content.size());
  10922. return true;
  10923. },
  10924. "text/plain");
  10925. ASSERT_TRUE(result);
  10926. EXPECT_EQ(200, result->status);
  10927. std::this_thread::sleep_for(std::chrono::seconds(2));
  10928. // Recoonect
  10929. result = cli.Post(
  10930. "/hi", content.size(),
  10931. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10932. sink.write(content.c_str(), content.size());
  10933. return true;
  10934. },
  10935. "text/plain");
  10936. ASSERT_TRUE(result);
  10937. EXPECT_EQ(200, result->status);
  10938. result = cli.Post(
  10939. "/hi", content.size(),
  10940. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10941. sink.write(content.c_str(), content.size());
  10942. return true;
  10943. },
  10944. "text/plain");
  10945. ASSERT_TRUE(result);
  10946. EXPECT_EQ(200, result->status);
  10947. }
  10948. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10949. using namespace httplib::tls;
  10950. {
  10951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10952. ASSERT_TRUE(svr.is_valid());
  10953. svr.Get("/sni", [&](const Request &req, Response &res) {
  10954. std::string expected = req.sni();
  10955. EXPECT_EQ(expected, req.get_param_value("expected"));
  10956. res.set_content("ok", "text/plain");
  10957. });
  10958. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10959. auto se = detail::scope_exit([&] {
  10960. svr.stop();
  10961. listen_thread.join();
  10962. ASSERT_FALSE(svr.is_running());
  10963. });
  10964. svr.wait_until_ready();
  10965. {
  10966. SSLClient cli("localhost", PORT);
  10967. cli.enable_server_certificate_verification(false);
  10968. auto res = cli.Get("/sni?expected=localhost");
  10969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10970. }
  10971. {
  10972. SSLClient cli("::1", PORT);
  10973. cli.enable_server_certificate_verification(false);
  10974. auto res = cli.Get("/sni?expected=");
  10975. // NOTE: This may fail if the server is listening on IPv4 only
  10976. // (e.g., when localhost resolves to 127.0.0.1 only)
  10977. if (res) {
  10978. EXPECT_EQ(StatusCode::OK_200, res->status);
  10979. } else {
  10980. EXPECT_EQ(Error::Connection, res.error());
  10981. }
  10982. }
  10983. }
  10984. }
  10985. #endif
  10986. TEST(ClientProblemDetectionTest, ContentProvider) {
  10987. Server svr;
  10988. size_t content_length = 1024 * 1024;
  10989. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10990. res.set_content_provider(
  10991. content_length, "text/plain",
  10992. [&](size_t offset, size_t length, DataSink &sink) {
  10993. auto out_len = std::min(length, static_cast<size_t>(1024));
  10994. std::string out(out_len, '@');
  10995. sink.write(out.data(), out_len);
  10996. return offset < 4096;
  10997. },
  10998. [](bool success) { ASSERT_FALSE(success); });
  10999. });
  11000. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11001. res.set_content_provider(
  11002. 0, "text/plain",
  11003. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11004. EXPECT_TRUE(false);
  11005. return true;
  11006. },
  11007. [](bool success) { ASSERT_FALSE(success); });
  11008. });
  11009. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11010. auto se = detail::scope_exit([&] {
  11011. svr.stop();
  11012. listen_thread.join();
  11013. ASSERT_FALSE(svr.is_running());
  11014. });
  11015. svr.wait_until_ready();
  11016. Client cli("localhost", PORT);
  11017. {
  11018. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11019. size_t /*data_length*/) { return false; });
  11020. ASSERT_FALSE(res);
  11021. }
  11022. {
  11023. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11024. size_t /*data_length*/) { return false; });
  11025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11026. }
  11027. }
  11028. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11029. // A provider that reports success without writing anything and without
  11030. // calling done() used to be handed the same offset and length again on every
  11031. // pass, so it spun for as long as the peer stayed connected.
  11032. Server svr;
  11033. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11034. res.set_content("ok", "text/plain");
  11035. });
  11036. auto port = svr.bind_to_any_port(HOST);
  11037. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11038. auto se = detail::scope_exit([&] {
  11039. svr.stop();
  11040. listen_thread.join();
  11041. ASSERT_FALSE(svr.is_running());
  11042. });
  11043. svr.wait_until_ready();
  11044. std::atomic<int> call_count{0};
  11045. Client cli(HOST, port);
  11046. auto res = cli.Post(
  11047. "/", 1024,
  11048. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11049. // Give up after enough passes to show the spin, so that losing the
  11050. // check below fails this test instead of hanging it.
  11051. return ++call_count < 100;
  11052. },
  11053. "text/plain");
  11054. ASSERT_FALSE(res);
  11055. EXPECT_EQ(Error::Write, res.error());
  11056. EXPECT_EQ(1, call_count.load());
  11057. }
  11058. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11059. // A writer only has to assign `write`. The other three used to be left as
  11060. // empty std::functions, so a provider calling one threw
  11061. // std::bad_function_call out of the thread running it and took the whole
  11062. // process down.
  11063. DataSink sink;
  11064. std::string written;
  11065. sink.write = [&](const char *data, size_t data_len) {
  11066. written.append(data, data_len);
  11067. return true;
  11068. };
  11069. EXPECT_TRUE(sink.is_writable());
  11070. sink.done();
  11071. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11072. EXPECT_TRUE(written.empty());
  11073. }
  11074. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11075. // A sink that cannot carry trailers still has to finish.
  11076. DataSink sink;
  11077. auto done_count = 0;
  11078. sink.done = [&]() { done_count++; };
  11079. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11080. EXPECT_EQ(1, done_count);
  11081. }
  11082. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11083. Server svr;
  11084. const std::string body(4096, 'x');
  11085. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11086. res.set_content_provider(body.size(), "text/plain",
  11087. [&](size_t offset, size_t length, DataSink &sink) {
  11088. sink.write(body.data() + offset, length);
  11089. sink.done();
  11090. return true;
  11091. });
  11092. });
  11093. auto port = svr.bind_to_any_port(HOST);
  11094. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11095. auto se = detail::scope_exit([&] {
  11096. svr.stop();
  11097. listen_thread.join();
  11098. ASSERT_FALSE(svr.is_running());
  11099. });
  11100. svr.wait_until_ready();
  11101. Client cli(HOST, port);
  11102. auto res = cli.Get("/");
  11103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11104. EXPECT_EQ(StatusCode::OK_200, res->status);
  11105. EXPECT_EQ(body, res->body);
  11106. }
  11107. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11108. Server svr;
  11109. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11110. res.set_content_provider(
  11111. 1024, "text/plain",
  11112. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11113. sink.write("hello", 5);
  11114. sink.done(); // short of the 1024 bytes the response promised
  11115. return true;
  11116. });
  11117. });
  11118. auto port = svr.bind_to_any_port(HOST);
  11119. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11120. auto se = detail::scope_exit([&] {
  11121. svr.stop();
  11122. listen_thread.join();
  11123. ASSERT_FALSE(svr.is_running());
  11124. });
  11125. svr.wait_until_ready();
  11126. Client cli(HOST, port);
  11127. cli.set_read_timeout(5, 0);
  11128. // The response is short of its Content-Length, so the client cannot read a
  11129. // complete body. What matters is that this returns at all: a no-op done()
  11130. // would leave the writer looping over a provider that never makes progress.
  11131. auto res = cli.Get("/");
  11132. EXPECT_FALSE(res);
  11133. }
  11134. // Read as the next response by a peer that sees it after a framed body.
  11135. static const std::string smuggled_response =
  11136. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11137. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11138. Server svr;
  11139. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11140. res.set_content_provider(
  11141. 5, "text/plain",
  11142. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11143. auto data = "AAAAA" + smuggled_response;
  11144. sink.write(data.data(), data.size());
  11145. return true;
  11146. });
  11147. });
  11148. thread t = thread([&] { svr.listen(HOST, PORT); });
  11149. auto se = detail::scope_exit([&] {
  11150. svr.stop();
  11151. t.join();
  11152. ASSERT_FALSE(svr.is_running());
  11153. });
  11154. svr.wait_until_ready();
  11155. std::string resp;
  11156. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11157. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11158. resp.clear();
  11159. ASSERT_TRUE(send_request(
  11160. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11161. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11162. }
  11163. TEST(NoContentTest, BodyIsNotSent) {
  11164. Server svr;
  11165. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11166. res.status = StatusCode::NoContent_204;
  11167. res.set_content(smuggled_response, "text/plain");
  11168. });
  11169. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11170. res.status = StatusCode::NotModified_304;
  11171. res.set_chunked_content_provider(
  11172. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11173. sink.write(smuggled_response.data(), smuggled_response.size());
  11174. sink.done();
  11175. return true;
  11176. });
  11177. });
  11178. thread t = thread([&] { svr.listen(HOST, PORT); });
  11179. auto se = detail::scope_exit([&] {
  11180. svr.stop();
  11181. t.join();
  11182. ASSERT_FALSE(svr.is_running());
  11183. });
  11184. svr.wait_until_ready();
  11185. for (auto path : {"/204", "/304"}) {
  11186. std::string resp;
  11187. ASSERT_TRUE(send_request(
  11188. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11189. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11190. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11191. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11192. }
  11193. }
  11194. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11195. Server svr;
  11196. std::atomic<bool> smuggled(false);
  11197. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11198. res.set_content("ok", "text/plain");
  11199. });
  11200. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11201. smuggled = true;
  11202. });
  11203. auto port = svr.bind_to_any_port(HOST);
  11204. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11205. auto se = detail::scope_exit([&] {
  11206. svr.stop();
  11207. listen_thread.join();
  11208. ASSERT_FALSE(svr.is_running());
  11209. });
  11210. svr.wait_until_ready();
  11211. // What follows the body would be read as the next request.
  11212. Client cli(HOST, port);
  11213. auto res = cli.Post(
  11214. "/", 5,
  11215. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11216. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11217. sink.write(data.data(), data.size());
  11218. return true;
  11219. },
  11220. "text/plain");
  11221. ASSERT_FALSE(res);
  11222. EXPECT_EQ(Error::Write, res.error());
  11223. EXPECT_FALSE(smuggled);
  11224. }
  11225. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11226. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11227. // The compressed path builds the whole body before connecting, so this
  11228. // fails client-side and never reaches a server.
  11229. Client cli(HOST, PORT);
  11230. cli.set_compress(true);
  11231. auto res = cli.Post(
  11232. "/", 1024,
  11233. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11234. sink.write("hello", 5);
  11235. sink.done(); // short of the 1024 bytes the request announced
  11236. return true;
  11237. },
  11238. "text/plain");
  11239. ASSERT_FALSE(res);
  11240. EXPECT_EQ(Error::Write, res.error());
  11241. }
  11242. #endif
  11243. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11244. Server svr;
  11245. svr.set_error_handler([](Request const &, Response &res) -> void {
  11246. res.set_chunked_content_provider(
  11247. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11248. sink.os << "hello";
  11249. sink.os << "world";
  11250. sink.done();
  11251. return true;
  11252. });
  11253. });
  11254. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11255. auto se = detail::scope_exit([&] {
  11256. svr.stop();
  11257. listen_thread.join();
  11258. ASSERT_FALSE(svr.is_running());
  11259. });
  11260. svr.wait_until_ready();
  11261. Client cli("localhost", PORT);
  11262. auto res = cli.Get("/");
  11263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11265. EXPECT_EQ("helloworld", res->body);
  11266. }
  11267. // A body set after a content provider must replace it, not be sent through it.
  11268. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11269. Server svr;
  11270. svr.set_mount_point("/", "./www");
  11271. svr.set_file_request_handler([](const Request &req, Response &res) {
  11272. if (req.path == "/dir/test.html") {
  11273. res.status = StatusCode::Forbidden_403;
  11274. res.set_content(std::string(5000, 'D'), "text/plain");
  11275. } else if (req.path == "/file") {
  11276. res.status = StatusCode::Forbidden_403;
  11277. res.body = "Denied";
  11278. }
  11279. });
  11280. auto port = svr.bind_to_any_port(HOST);
  11281. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11282. auto se = detail::scope_exit([&] {
  11283. svr.stop();
  11284. t.join();
  11285. ASSERT_FALSE(svr.is_running());
  11286. });
  11287. svr.wait_until_ready();
  11288. Client cli(HOST, port);
  11289. {
  11290. auto res = cli.Get("/dir/test.html");
  11291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11292. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11293. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11294. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11295. }
  11296. {
  11297. auto res = cli.Get("/file");
  11298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11299. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11300. EXPECT_EQ("Denied", res->body);
  11301. }
  11302. {
  11303. auto res = cli.Get("/dir/index.html");
  11304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11305. EXPECT_EQ(StatusCode::OK_200, res->status);
  11306. EXPECT_EQ(0U, res->body.find("<html>"));
  11307. }
  11308. }
  11309. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11310. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11311. Server svr;
  11312. std::vector<bool> released;
  11313. std::mutex released_mutex;
  11314. auto releaser = [&](bool success) {
  11315. std::lock_guard<std::mutex> guard(released_mutex);
  11316. released.push_back(success);
  11317. };
  11318. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11319. return sink.write(&"hello"[offset], length);
  11320. };
  11321. svr.Get("/sized", [&](const Request &, Response &res) {
  11322. res.status = StatusCode::NotFound_404;
  11323. res.set_content_provider(5, "text/plain", provider, releaser);
  11324. });
  11325. svr.Get("/chunked", [&](const Request &, Response &res) {
  11326. res.status = StatusCode::ServiceUnavailable_503;
  11327. res.set_chunked_content_provider(
  11328. "text/plain",
  11329. [](size_t, DataSink &sink) {
  11330. sink.os << "chunk";
  11331. sink.done();
  11332. return true;
  11333. },
  11334. releaser);
  11335. });
  11336. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11337. res.set_content_provider(5, "text/plain", provider, releaser);
  11338. throw std::runtime_error("after the provider");
  11339. });
  11340. svr.set_error_handler([](const Request &req, Response &res) {
  11341. // Leave the exception handler's content to it.
  11342. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11343. res.set_content(std::string(1000, 'E'), "text/html");
  11344. return Server::HandlerResponse::Handled;
  11345. });
  11346. svr.set_exception_handler(
  11347. [](const Request &, Response &res, std::exception_ptr) {
  11348. res.status = StatusCode::InternalServerError_500;
  11349. res.set_content(std::string(1000, 'X'), "text/html");
  11350. });
  11351. auto port = svr.bind_to_any_port(HOST);
  11352. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11353. auto se = detail::scope_exit([&] {
  11354. svr.stop();
  11355. t.join();
  11356. ASSERT_FALSE(svr.is_running());
  11357. });
  11358. svr.wait_until_ready();
  11359. Client cli(HOST, port);
  11360. {
  11361. auto res = cli.Get("/sized");
  11362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11363. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11364. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11365. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11366. }
  11367. {
  11368. auto res = cli.Get("/chunked");
  11369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11370. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11371. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11372. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11373. }
  11374. {
  11375. auto res = cli.Get("/throw");
  11376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11377. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11378. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11379. }
  11380. std::lock_guard<std::mutex> guard(released_mutex);
  11381. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11382. }
  11383. #endif
  11384. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11385. Server svr;
  11386. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11387. return sink.write(&"abc"[offset], length);
  11388. };
  11389. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11390. res.set_file_content("./www/dir/test.html");
  11391. res.set_content("body", "text/plain");
  11392. });
  11393. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11394. res.set_content(std::string(100, 'B'), "text/plain");
  11395. res.set_file_content("./www/dir/test.html");
  11396. });
  11397. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11398. res.set_content(std::string(100, 'B'), "text/plain");
  11399. res.set_content_provider(3, "text/x-provider", abc);
  11400. });
  11401. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11402. res.set_content_provider(3, "text/x-provider", abc);
  11403. res.set_content(std::string(100, 'B'), "text/plain");
  11404. });
  11405. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11406. res.set_content_provider(3, "text/x-provider", abc);
  11407. res.set_file_content("./www/dir/test.html", "text/x-file");
  11408. });
  11409. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11410. res.set_file_content("./www/dir/test.html");
  11411. res.set_header("Content-Type", "text/x-handler");
  11412. });
  11413. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11414. res.set_content_provider(3, "text/plain", abc);
  11415. res.body = "direct";
  11416. });
  11417. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11418. res.set_file_content("./www/dir/test.html");
  11419. res.body = "direct";
  11420. });
  11421. auto port = svr.bind_to_any_port(HOST);
  11422. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11423. auto se = detail::scope_exit([&] {
  11424. svr.stop();
  11425. t.join();
  11426. ASSERT_FALSE(svr.is_running());
  11427. });
  11428. svr.wait_until_ready();
  11429. Client cli(HOST, port);
  11430. auto expect_body = [&](const char *path, const std::string &body,
  11431. const std::string &type) {
  11432. // Uncompressed, so Content-Length can be compared with the body.
  11433. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11434. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11435. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11436. EXPECT_EQ(body, res->body) << path;
  11437. EXPECT_EQ(std::to_string(body.size()),
  11438. res->get_header_value("Content-Length"))
  11439. << path;
  11440. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11441. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11442. };
  11443. expect_body("/file-then-body", "body", "text/plain");
  11444. expect_body("/body-then-file", "test.html", "text/html");
  11445. expect_body("/body-then-provider", "abc", "text/x-provider");
  11446. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11447. expect_body("/provider-then-file", "test.html", "text/x-file");
  11448. expect_body("/file-then-header", "test.html", "text/x-handler");
  11449. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11450. expect_body("/file-then-direct-body", "direct", "text/plain");
  11451. // Ranges are checked against the body, not the dropped provider.
  11452. {
  11453. auto res = cli.Get("/provider-then-direct-body",
  11454. Headers{{make_range_header({{1, 2}})}});
  11455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11456. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11457. EXPECT_EQ("ir", res->body);
  11458. }
  11459. {
  11460. auto res = cli.Get("/file-then-direct-body",
  11461. Headers{{make_range_header({{7, 8}})}});
  11462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11463. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11464. }
  11465. }
  11466. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11467. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11468. const char *path = "./truncated_while_served.txt";
  11469. const size_t size = 32 * 1024 * 1024;
  11470. {
  11471. std::ofstream f(path, std::ios::binary);
  11472. f << std::string(size, 'x');
  11473. }
  11474. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11475. // Over TLS, where the bytes are encrypted in this process rather than
  11476. // copied by send().
  11477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11478. svr.Get("/file", [&](const Request &, Response &res) {
  11479. res.set_file_content(path, "text/plain");
  11480. });
  11481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11482. auto se = detail::scope_exit([&] {
  11483. svr.stop();
  11484. thread.join();
  11485. ASSERT_FALSE(svr.is_running());
  11486. });
  11487. svr.wait_until_ready();
  11488. // The file shrinks once the first bytes are in, as a rewrite in place
  11489. // would, and reading the mapping past its new end used to raise SIGBUS.
  11490. SSLClient cli(HOST, PORT);
  11491. cli.enable_server_certificate_verification(false);
  11492. size_t received = 0;
  11493. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11494. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11495. received += len;
  11496. return true;
  11497. });
  11498. EXPECT_FALSE(res);
  11499. EXPECT_LT(received, size);
  11500. }
  11501. #endif
  11502. // Forward declaration (see the base64_encode note).
  11503. namespace httplib {
  11504. namespace detail {
  11505. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11506. const std::string &content_type,
  11507. EncodingType encoding);
  11508. } // namespace detail
  11509. } // namespace httplib
  11510. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11511. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11512. ASSERT_TRUE(mm->is_open());
  11513. Response res;
  11514. detail::set_file_content_provider(res, mm, "text/html",
  11515. detail::EncodingType::None);
  11516. std::string out;
  11517. DataSink sink;
  11518. sink.write = [&](const char *d, size_t l) {
  11519. out.append(d, l);
  11520. return true;
  11521. };
  11522. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11523. EXPECT_EQ("test.html", out);
  11524. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11525. EXPECT_EQ("test.html", out);
  11526. }
  11527. TEST(LongPollingTest, ClientCloseDetection) {
  11528. Server svr;
  11529. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11530. res.set_chunked_content_provider(
  11531. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11532. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11533. sink.os << "hello";
  11534. auto count = 10;
  11535. while (count > 0 && sink.is_writable()) {
  11536. this_thread::sleep_for(chrono::milliseconds(10));
  11537. count--;
  11538. }
  11539. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11540. return true;
  11541. });
  11542. });
  11543. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11544. auto se = detail::scope_exit([&] {
  11545. svr.stop();
  11546. listen_thread.join();
  11547. ASSERT_FALSE(svr.is_running());
  11548. });
  11549. svr.wait_until_ready();
  11550. Client cli("localhost", PORT);
  11551. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11552. EXPECT_EQ("hello", string(data, data_length));
  11553. return false; // close the socket immediately.
  11554. });
  11555. ASSERT_FALSE(res);
  11556. }
  11557. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11558. Server svr;
  11559. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11560. res.set_chunked_content_provider(
  11561. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11562. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11563. sink.os << "hello";
  11564. EXPECT_TRUE(sink.os.good());
  11565. // Wait for the client to close the connection
  11566. auto count = 10;
  11567. while (count > 0 && sink.is_writable()) {
  11568. this_thread::sleep_for(chrono::milliseconds(10));
  11569. count--;
  11570. }
  11571. // After client disconnect, write repeatedly until the socket
  11572. // write actually fails (small writes may be absorbed by the
  11573. // kernel buffer)
  11574. std::string chunk(1024, 'x');
  11575. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11576. sink.os << chunk;
  11577. }
  11578. EXPECT_TRUE(sink.os.fail());
  11579. return true;
  11580. });
  11581. });
  11582. auto port = svr.bind_to_any_port("localhost");
  11583. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11584. auto se = detail::scope_exit([&] {
  11585. svr.stop();
  11586. listen_thread.join();
  11587. ASSERT_FALSE(svr.is_running());
  11588. });
  11589. svr.wait_until_ready();
  11590. Client cli("localhost", port);
  11591. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11592. EXPECT_EQ("hello", string(data, data_length));
  11593. return false; // close the socket immediately.
  11594. });
  11595. ASSERT_FALSE(res);
  11596. }
  11597. TEST(GetWithParametersTest, GetWithParameters) {
  11598. Server svr;
  11599. svr.Get("/", [&](const Request &req, Response &) {
  11600. EXPECT_EQ("world", req.get_param_value("hello"));
  11601. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11602. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11603. });
  11604. svr.Get("/params", [&](const Request &req, Response &) {
  11605. EXPECT_EQ("world", req.get_param_value("hello"));
  11606. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11607. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11608. });
  11609. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11610. EXPECT_EQ("resource-id", req.matches[1]);
  11611. EXPECT_EQ("foo", req.get_param_value("param1"));
  11612. EXPECT_EQ("bar", req.get_param_value("param2"));
  11613. });
  11614. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11615. EXPECT_EQ("user-id", req.path_params.at("id"));
  11616. EXPECT_EQ("foo", req.get_param_value("param1"));
  11617. EXPECT_EQ("bar", req.get_param_value("param2"));
  11618. });
  11619. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11620. auto se = detail::scope_exit([&] {
  11621. svr.stop();
  11622. listen_thread.join();
  11623. ASSERT_FALSE(svr.is_running());
  11624. });
  11625. svr.wait_until_ready();
  11626. {
  11627. Client cli(HOST, PORT);
  11628. Params params;
  11629. params.emplace("hello", "world");
  11630. params.emplace("hello2", "world2");
  11631. params.emplace("hello3", "world3");
  11632. auto res = cli.Get("/", params, Headers{});
  11633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11634. EXPECT_EQ(StatusCode::OK_200, res->status);
  11635. }
  11636. {
  11637. Client cli(HOST, PORT);
  11638. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11640. EXPECT_EQ(StatusCode::OK_200, res->status);
  11641. }
  11642. {
  11643. Client cli(HOST, PORT);
  11644. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11646. EXPECT_EQ(StatusCode::OK_200, res->status);
  11647. }
  11648. {
  11649. Client cli(HOST, PORT);
  11650. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11652. EXPECT_EQ(StatusCode::OK_200, res->status);
  11653. }
  11654. }
  11655. TEST(GetWithParametersTest, GetWithParameters2) {
  11656. Server svr;
  11657. svr.Get("/", [&](const Request &req, Response &res) {
  11658. auto text = req.get_param_value("hello");
  11659. res.set_content(text, "text/plain");
  11660. });
  11661. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11662. auto se = detail::scope_exit([&] {
  11663. svr.stop();
  11664. listen_thread.join();
  11665. ASSERT_FALSE(svr.is_running());
  11666. });
  11667. svr.wait_until_ready();
  11668. Client cli("localhost", PORT);
  11669. Params params;
  11670. params.emplace("hello", "world");
  11671. std::string body;
  11672. auto res = cli.Get("/", params, Headers{},
  11673. [&](const char *data, size_t data_length) {
  11674. body.append(data, data_length);
  11675. return true;
  11676. });
  11677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11678. EXPECT_EQ(StatusCode::OK_200, res->status);
  11679. EXPECT_EQ("world", body);
  11680. }
  11681. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11682. Server svr;
  11683. svr.Get("/search", [&](const Request &req, Response &res) {
  11684. auto q = req.get_param_value("q");
  11685. res.set_content(q, "text/plain");
  11686. });
  11687. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11688. auto se = detail::scope_exit([&] {
  11689. svr.stop();
  11690. listen_thread.join();
  11691. ASSERT_FALSE(svr.is_running());
  11692. });
  11693. svr.wait_until_ready();
  11694. Client cli("localhost", PORT);
  11695. // Verify that Get(path, params) works without requiring Headers argument
  11696. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11698. EXPECT_EQ(StatusCode::OK_200, res->status);
  11699. EXPECT_EQ("cpp-httplib", res->body);
  11700. }
  11701. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11702. auto host = "httpbingo.org";
  11703. auto path = std::string{"/range/32"};
  11704. #ifdef CPPHTTPLIB_SSL_ENABLED
  11705. SSLClient cli(host);
  11706. #else
  11707. Client cli(host);
  11708. #endif
  11709. cli.set_default_headers({make_range_header({{1, 10}})});
  11710. cli.set_connection_timeout(5);
  11711. {
  11712. auto res = cli.Get(path);
  11713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11714. EXPECT_EQ("bcdefghijk", res->body);
  11715. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11716. }
  11717. {
  11718. auto res = cli.Get(path);
  11719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11720. EXPECT_EQ("bcdefghijk", res->body);
  11721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11722. }
  11723. }
  11724. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11725. Server svr;
  11726. svr.set_default_headers({{"Hello", "World"}});
  11727. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11728. res.set_content("ok", "text/plain");
  11729. });
  11730. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11731. auto se = detail::scope_exit([&] {
  11732. svr.stop();
  11733. listen_thread.join();
  11734. ASSERT_FALSE(svr.is_running());
  11735. });
  11736. svr.wait_until_ready();
  11737. Client cli("localhost", PORT);
  11738. auto res = cli.Get("/");
  11739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11740. EXPECT_EQ(StatusCode::OK_200, res->status);
  11741. EXPECT_EQ("ok", res->body);
  11742. EXPECT_EQ("World", res->get_header_value("Hello"));
  11743. }
  11744. #ifdef CPPHTTPLIB_SSL_ENABLED
  11745. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11747. ASSERT_TRUE(svr.is_valid());
  11748. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11749. std::this_thread::sleep_for(std::chrono::seconds(2));
  11750. res.set_content("a", "text/plain");
  11751. });
  11752. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11753. res.set_content("b", "text/plain");
  11754. });
  11755. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11756. auto se = detail::scope_exit([&] {
  11757. svr.stop();
  11758. listen_thread.join();
  11759. ASSERT_FALSE(svr.is_running());
  11760. });
  11761. svr.wait_until_ready();
  11762. SSLClient cli("localhost", PORT);
  11763. cli.enable_server_certificate_verification(false);
  11764. cli.set_keep_alive(true);
  11765. cli.set_read_timeout(std::chrono::seconds(1));
  11766. auto resa = cli.Get("/a");
  11767. ASSERT_TRUE(!resa);
  11768. EXPECT_EQ(Error::Read, resa.error());
  11769. auto resb = cli.Get("/b");
  11770. ASSERT_TRUE(resb);
  11771. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11772. EXPECT_EQ("b", resb->body);
  11773. }
  11774. // Closing an idle keep-alive connection sends close_notify and returns. The
  11775. // server must not wait for the client's close_notify: an idle client never
  11776. // sends one, so the worker would be held until the read timeout expires, and
  11777. // stop() would wait for it.
  11778. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11780. ASSERT_TRUE(svr.is_valid());
  11781. svr.set_keep_alive_timeout(1);
  11782. svr.set_read_timeout(10, 0);
  11783. svr.Get("/", [](const Request &, Response &res) {
  11784. res.set_content("ok", "text/plain");
  11785. });
  11786. auto port = svr.bind_to_any_port(HOST);
  11787. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11788. auto se = detail::scope_exit([&] {
  11789. if (listen_thread.joinable()) {
  11790. svr.stop();
  11791. listen_thread.join();
  11792. }
  11793. });
  11794. svr.wait_until_ready();
  11795. SSLClient cli(HOST, port);
  11796. cli.enable_server_certificate_verification(false);
  11797. cli.set_keep_alive(true);
  11798. auto res = cli.Get("/");
  11799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11800. EXPECT_EQ(StatusCode::OK_200, res->status);
  11801. // Stay idle past the keep-alive timeout so the server closes the connection.
  11802. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11803. auto start = std::chrono::steady_clock::now();
  11804. svr.stop();
  11805. listen_thread.join();
  11806. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11807. std::chrono::steady_clock::now() - start)
  11808. .count();
  11809. EXPECT_LT(elapsed, 3000);
  11810. }
  11811. #endif
  11812. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11813. protected:
  11814. ServerTestWithAI_PASSIVE()
  11815. : cli_(HOST, PORT)
  11816. #ifdef CPPHTTPLIB_SSL_ENABLED
  11817. ,
  11818. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11819. #endif
  11820. {
  11821. #ifdef CPPHTTPLIB_SSL_ENABLED
  11822. cli_.enable_server_certificate_verification(false);
  11823. #endif
  11824. }
  11825. virtual void SetUp() {
  11826. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11827. res.set_content("Hello World!", "text/plain");
  11828. });
  11829. t_ = thread(
  11830. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11831. svr_.wait_until_ready();
  11832. }
  11833. virtual void TearDown() {
  11834. svr_.stop();
  11835. t_.join();
  11836. }
  11837. #ifdef CPPHTTPLIB_SSL_ENABLED
  11838. SSLClient cli_;
  11839. SSLServer svr_;
  11840. #else
  11841. Client cli_;
  11842. Server svr_;
  11843. #endif
  11844. thread t_;
  11845. };
  11846. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11847. auto res = cli_.Get("/hi");
  11848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11849. EXPECT_EQ(StatusCode::OK_200, res->status);
  11850. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11851. EXPECT_EQ("Hello World!", res->body);
  11852. }
  11853. class ServerUpDownTest : public ::testing::Test {
  11854. protected:
  11855. ServerUpDownTest() : cli_(HOST, PORT) {}
  11856. virtual void SetUp() {
  11857. t_ = thread([&]() {
  11858. svr_.bind_to_any_port(HOST);
  11859. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11860. ASSERT_TRUE(svr_.listen_after_bind());
  11861. });
  11862. svr_.wait_until_ready();
  11863. }
  11864. virtual void TearDown() {
  11865. svr_.stop();
  11866. t_.join();
  11867. }
  11868. Client cli_;
  11869. Server svr_;
  11870. thread t_;
  11871. };
  11872. TEST_F(ServerUpDownTest, QuickStartStop) {
  11873. // Should not crash, especially when run with
  11874. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11875. }
  11876. class PayloadMaxLengthTest : public ::testing::Test {
  11877. protected:
  11878. PayloadMaxLengthTest()
  11879. : cli_(HOST, PORT)
  11880. #ifdef CPPHTTPLIB_SSL_ENABLED
  11881. ,
  11882. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11883. #endif
  11884. {
  11885. #ifdef CPPHTTPLIB_SSL_ENABLED
  11886. cli_.enable_server_certificate_verification(false);
  11887. #endif
  11888. }
  11889. virtual void SetUp() {
  11890. svr_.set_payload_max_length(8);
  11891. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11892. res.set_content("test", "text/plain");
  11893. });
  11894. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11895. svr_.wait_until_ready();
  11896. }
  11897. virtual void TearDown() {
  11898. svr_.stop();
  11899. t_.join();
  11900. }
  11901. #ifdef CPPHTTPLIB_SSL_ENABLED
  11902. SSLClient cli_;
  11903. SSLServer svr_;
  11904. #else
  11905. Client cli_;
  11906. Server svr_;
  11907. #endif
  11908. thread t_;
  11909. };
  11910. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11911. auto res = cli_.Post("/test", "123456789", "text/plain");
  11912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11913. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11914. res = cli_.Post("/test", "12345678", "text/plain");
  11915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11916. EXPECT_EQ(StatusCode::OK_200, res->status);
  11917. }
  11918. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11919. // Test chunked encoding with payload exceeding the 8-byte limit
  11920. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11921. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11923. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11924. }
  11925. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11926. // Test chunked encoding with payload within the 8-byte limit
  11927. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11928. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11930. EXPECT_EQ(StatusCode::OK_200, res->status);
  11931. }
  11932. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11933. // Test using send_request to send chunked data exceeding payload limit
  11934. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11935. "Host: " +
  11936. std::string(HOST) + ":" + std::to_string(PORT) +
  11937. "\r\n"
  11938. "Transfer-Encoding: chunked\r\n"
  11939. "Connection: close\r\n"
  11940. "\r\n"
  11941. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11942. "0123456789\r\n"
  11943. "0\r\n" // End chunk
  11944. "\r\n";
  11945. std::string response;
  11946. bool result = send_request(1, chunked_request, &response);
  11947. if (!result) {
  11948. // If send_request fails, it might be because the server closed the
  11949. // connection due to payload limit enforcement, which is acceptable
  11950. SUCCEED()
  11951. << "Server rejected oversized chunked request (connection closed)";
  11952. } else {
  11953. // If we got a response, check if it's an error response or connection was
  11954. // closed early Short response length indicates connection was closed due to
  11955. // payload limit
  11956. if (response.length() <= 10) {
  11957. SUCCEED() << "Server closed connection for oversized chunked request";
  11958. } else {
  11959. // Check for error status codes
  11960. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11961. response.find("Payload Too Large") != std::string::npos ||
  11962. response.find("400") != std::string::npos);
  11963. }
  11964. }
  11965. }
  11966. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11967. // Test request without Content-Length header exceeding payload limit
  11968. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11969. "Host: " +
  11970. std::string(HOST) + ":" +
  11971. std::to_string(PORT) +
  11972. "\r\n"
  11973. "Connection: close\r\n"
  11974. "\r\n";
  11975. // Add payload exceeding the 8-byte limit
  11976. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11977. request_without_content_length += large_payload;
  11978. std::string response;
  11979. bool result = send_request(1, request_without_content_length, &response);
  11980. if (!result) {
  11981. // If send_request fails, server likely closed connection due to payload
  11982. // limit
  11983. SUCCEED() << "Server rejected oversized request without Content-Length "
  11984. "(connection closed)";
  11985. } else {
  11986. // Check if server responded with error or closed connection early
  11987. if (response.length() <= 10) {
  11988. SUCCEED() << "Server closed connection for oversized request without "
  11989. "Content-Length";
  11990. } else {
  11991. // Check for error status codes
  11992. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11993. response.find("Payload Too Large") != std::string::npos ||
  11994. response.find("400") != std::string::npos);
  11995. }
  11996. }
  11997. }
  11998. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11999. // Test request without Content-Length header within payload limit
  12000. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12001. "Host: " +
  12002. std::string(HOST) + ":" +
  12003. std::to_string(PORT) +
  12004. "\r\n"
  12005. "Connection: close\r\n"
  12006. "\r\n";
  12007. // Add payload within the 8-byte limit
  12008. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12009. request_without_content_length += small_payload;
  12010. std::string response;
  12011. bool result = send_request(1, request_without_content_length, &response);
  12012. // For requests without Content-Length, the server may have different behavior
  12013. // The key is that it should not reject due to payload limit for small
  12014. // payloads
  12015. if (result) {
  12016. // Check for any HTTP response (success or error, but not connection closed)
  12017. if (response.length() > 10) {
  12018. SUCCEED()
  12019. << "Server processed request without Content-Length within limit";
  12020. } else {
  12021. // Short response might indicate connection closed, which is acceptable
  12022. SUCCEED() << "Server closed connection for request without "
  12023. "Content-Length (acceptable behavior)";
  12024. }
  12025. } else {
  12026. // Connection failure might be due to protocol requirements
  12027. SUCCEED() << "Connection issue with request without Content-Length "
  12028. "(environment-specific)";
  12029. }
  12030. }
  12031. class LargePayloadMaxLengthTest : public ::testing::Test {
  12032. protected:
  12033. LargePayloadMaxLengthTest()
  12034. : cli_(HOST, PORT)
  12035. #ifdef CPPHTTPLIB_SSL_ENABLED
  12036. ,
  12037. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12038. #endif
  12039. {
  12040. #ifdef CPPHTTPLIB_SSL_ENABLED
  12041. cli_.enable_server_certificate_verification(false);
  12042. #endif
  12043. }
  12044. virtual void SetUp() {
  12045. // Set 10MB payload limit
  12046. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12047. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12048. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12049. res.set_content("Large payload test", "text/plain");
  12050. });
  12051. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12052. svr_.wait_until_ready();
  12053. }
  12054. virtual void TearDown() {
  12055. svr_.stop();
  12056. t_.join();
  12057. }
  12058. #ifdef CPPHTTPLIB_SSL_ENABLED
  12059. SSLClient cli_;
  12060. SSLServer svr_;
  12061. #else
  12062. Client cli_;
  12063. Server svr_;
  12064. #endif
  12065. thread t_;
  12066. };
  12067. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12068. // Test chunked encoding with payload within 10MB limit
  12069. std::string medium_payload(5 * 1024 * 1024,
  12070. 'A'); // 5MB payload, within 10MB limit
  12071. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12073. EXPECT_EQ(StatusCode::OK_200, res->status);
  12074. }
  12075. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12076. // Test chunked encoding with payload exceeding 10MB limit
  12077. std::string large_payload(12 * 1024 * 1024,
  12078. 'B'); // 12MB payload, exceeds 10MB limit
  12079. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12080. // Server may either return 413 or close the connection
  12081. if (res) {
  12082. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12083. } else {
  12084. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12085. }
  12086. }
  12087. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12088. // Test request without Content-Length header within 10MB limit
  12089. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12090. "Host: " +
  12091. std::string(HOST) + ":" +
  12092. std::to_string(PORT) +
  12093. "\r\n"
  12094. "Connection: close\r\n"
  12095. "\r\n";
  12096. // Add 1MB payload (within 10MB limit)
  12097. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12098. request_without_content_length += medium_payload;
  12099. std::string response;
  12100. bool result = send_request(5, request_without_content_length, &response);
  12101. if (result) {
  12102. // Should get a proper HTTP response for payloads within limit
  12103. if (response.length() > 10) {
  12104. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12105. "10MB limit";
  12106. } else {
  12107. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12108. "Content-Length)";
  12109. }
  12110. } else {
  12111. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12112. }
  12113. }
  12114. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12115. // Test request without Content-Length header exceeding 10MB limit
  12116. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12117. "Host: " +
  12118. std::string(HOST) + ":" +
  12119. std::to_string(PORT) +
  12120. "\r\n"
  12121. "Connection: close\r\n"
  12122. "\r\n";
  12123. // Add 12MB payload (exceeds 10MB limit)
  12124. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12125. request_without_content_length += large_payload;
  12126. std::string response;
  12127. bool result = send_request(10, request_without_content_length, &response);
  12128. if (!result) {
  12129. // Server should close connection due to payload limit
  12130. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12131. "(connection closed)";
  12132. } else {
  12133. // Check for error response
  12134. if (response.length() <= 10) {
  12135. SUCCEED()
  12136. << "Server closed connection for 12MB request exceeding 10MB limit";
  12137. } else {
  12138. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12139. response.find("Payload Too Large") != std::string::npos ||
  12140. response.find("400") != std::string::npos);
  12141. }
  12142. }
  12143. }
  12144. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12145. Server svr;
  12146. svr.Get("/", [](const Request &, Response &res) {
  12147. // Claims the most the client accepts, far more than it sends, then drops
  12148. // the connection.
  12149. res.set_content_provider(std::string().max_size(), "text/plain",
  12150. [](size_t, size_t, DataSink &sink) {
  12151. sink.write("abc", 3);
  12152. return false;
  12153. });
  12154. });
  12155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12156. auto se = detail::scope_exit([&] {
  12157. svr.stop();
  12158. thread.join();
  12159. ASSERT_FALSE(svr.is_running());
  12160. });
  12161. svr.wait_until_ready();
  12162. Client cli(HOST, PORT);
  12163. cli.set_payload_max_length(0);
  12164. EXPECT_FALSE(cli.Get("/"));
  12165. }
  12166. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12167. // Stream API does, not as a plain read failure
  12168. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12169. Server svr;
  12170. svr.Get("/big", [](const Request &, Response &res) {
  12171. res.set_content(std::string(100000, 'b'), "text/plain");
  12172. });
  12173. auto port = svr.bind_to_any_port(HOST);
  12174. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12175. auto se = detail::scope_exit([&] {
  12176. svr.stop();
  12177. thread.join();
  12178. });
  12179. svr.wait_until_ready();
  12180. Client cli(HOST, port);
  12181. cli.set_payload_max_length(1000);
  12182. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12183. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12184. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12185. [](const char *, size_t) { return true; });
  12186. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12187. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12188. // Small on the wire, over the limit once decompressed
  12189. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12190. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12191. #endif
  12192. }
  12193. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12194. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12195. // path.
  12196. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12197. Server svr;
  12198. const size_t LIMIT = 64 * 1024; // 64KB
  12199. svr.set_payload_max_length(LIMIT);
  12200. size_t total = 0;
  12201. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12202. const ContentReader &content_reader) {
  12203. content_reader([&](const char * /*data*/, size_t len) {
  12204. total += len;
  12205. return true;
  12206. });
  12207. res.status = 200;
  12208. res.set_content("stream_ok", "text/plain");
  12209. });
  12210. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12211. auto se = detail::scope_exit([&] {
  12212. svr.stop();
  12213. thread.join();
  12214. ASSERT_FALSE(svr.is_running());
  12215. });
  12216. svr.wait_until_ready();
  12217. // Prepare 256KB raw data and gzip-compress it
  12218. std::string raw(256 * 1024, 'A');
  12219. std::string gz;
  12220. {
  12221. z_stream zs{};
  12222. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12223. Z_DEFAULT_STRATEGY);
  12224. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12225. zs.avail_in = static_cast<uInt>(raw.size());
  12226. char outbuf[4096];
  12227. int ret;
  12228. do {
  12229. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12230. zs.avail_out = sizeof(outbuf);
  12231. ret = deflate(&zs, Z_FINISH);
  12232. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12233. } while (ret != Z_STREAM_END);
  12234. deflateEnd(&zs);
  12235. }
  12236. Client cli(HOST, PORT);
  12237. cli.set_connection_timeout(std::chrono::seconds(5));
  12238. Headers headers = {{"Content-Encoding", "gzip"}};
  12239. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12240. "application/octet-stream");
  12241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12242. // Server must reject oversized decompressed payloads with 413.
  12243. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12244. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12245. EXPECT_LE(total, LIMIT);
  12246. }
  12247. #ifndef CPPHTTPLIB_SSL_ENABLED
  12248. // For a request with neither Content-Length nor Transfer-Encoding, the
  12249. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12250. // compressed wire bytes straight to the ContentReader without ever routing
  12251. // them through the decompressor, so payload_max_length_ only bounded the
  12252. // compressed size on the wire, not the decompressed size.
  12253. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12254. Server svr;
  12255. const size_t LIMIT = 64 * 1024; // 64KB
  12256. svr.set_payload_max_length(LIMIT);
  12257. size_t total = 0;
  12258. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12259. const ContentReader &content_reader) {
  12260. content_reader([&](const char * /*data*/, size_t len) {
  12261. total += len;
  12262. return true;
  12263. });
  12264. res.status = 200;
  12265. res.set_content("stream_ok", "text/plain");
  12266. });
  12267. auto port = svr.bind_to_any_port(HOST);
  12268. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12269. auto se = detail::scope_exit([&] {
  12270. svr.stop();
  12271. thread.join();
  12272. ASSERT_FALSE(svr.is_running());
  12273. });
  12274. svr.wait_until_ready();
  12275. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12276. // StreamingGzipDecompression test above.
  12277. std::string raw(256 * 1024, 'A');
  12278. std::string gz;
  12279. {
  12280. httplib::detail::gzip_compressor compressor;
  12281. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12282. [&](const char *chunk, size_t len) {
  12283. gz.append(chunk, len);
  12284. return true;
  12285. });
  12286. ASSERT_TRUE(result);
  12287. }
  12288. // Send the gzip body over raw TCP with neither Content-Length nor
  12289. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12290. // kicks in.
  12291. std::string req = "POST /stream HTTP/1.1\r\n"
  12292. "Host: " +
  12293. std::string(HOST) + ":" + std::to_string(port) +
  12294. "\r\n"
  12295. "Content-Encoding: gzip\r\n"
  12296. "Connection: close\r\n"
  12297. "\r\n" +
  12298. gz;
  12299. std::string response;
  12300. ASSERT_TRUE(send_request(5, req, &response, port));
  12301. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12302. EXPECT_LE(total, LIMIT);
  12303. }
  12304. #endif
  12305. #endif
  12306. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12307. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12308. // the payload must be passed through untouched instead of being rejected.
  12309. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12310. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12311. Server svr;
  12312. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12313. res.set_content(body, "image/jpeg");
  12314. res.set_header("Content-Encoding", "UTF-8");
  12315. });
  12316. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12317. res.set_content(body, "image/jpeg");
  12318. res.set_header("Content-Encoding", "identity");
  12319. });
  12320. svr.Post("/echo", [](const Request &req, Response &res) {
  12321. res.set_content(req.body, "image/jpeg");
  12322. });
  12323. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12324. auto se = detail::scope_exit([&] {
  12325. svr.stop();
  12326. t.join();
  12327. ASSERT_FALSE(svr.is_running());
  12328. });
  12329. svr.wait_until_ready();
  12330. Client cli(HOST, PORT);
  12331. {
  12332. auto res = cli.Get("/image");
  12333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12334. EXPECT_EQ(StatusCode::OK_200, res->status);
  12335. EXPECT_EQ(body, res->body);
  12336. }
  12337. {
  12338. auto res = cli.Get("/identity");
  12339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12340. EXPECT_EQ(StatusCode::OK_200, res->status);
  12341. EXPECT_EQ(body, res->body);
  12342. }
  12343. {
  12344. // The same applies to a request body reaching the server.
  12345. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12346. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12348. EXPECT_EQ(StatusCode::OK_200, res->status);
  12349. EXPECT_EQ(body, res->body);
  12350. }
  12351. }
  12352. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12353. // gzip-encoded response even when the build has no zlib support.
  12354. static const char GZIPPED_HELLO_WORLD[] = {
  12355. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12356. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12357. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12358. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12359. // A content coding is a whole token, not something the field value merely
  12360. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12361. // as "fibre" look like Brotli, and turned a multi-coding value like
  12362. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12363. // it was never meant to see.
  12364. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12365. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12366. Server svr;
  12367. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12368. res.set_content(body, "image/jpeg");
  12369. res.set_header("Content-Encoding", "fibre");
  12370. });
  12371. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12372. res.set_content(body, "image/jpeg");
  12373. res.set_header("Content-Encoding", "gzip, br");
  12374. });
  12375. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12376. res.set_content(body, "image/jpeg");
  12377. res.set_header("Content-Encoding", "x-zstd-ish");
  12378. });
  12379. auto port = svr.bind_to_any_port(HOST);
  12380. thread t = thread([&]() { svr.listen_after_bind(); });
  12381. auto se = detail::scope_exit([&] {
  12382. svr.stop();
  12383. t.join();
  12384. ASSERT_FALSE(svr.is_running());
  12385. });
  12386. svr.wait_until_ready();
  12387. Client cli(HOST, port);
  12388. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12389. auto res = cli.Get(path);
  12390. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12391. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12392. // Not a coding we recognize, so the payload comes back untouched
  12393. EXPECT_EQ(body, res->body) << path;
  12394. }
  12395. }
  12396. // A content coding cpp-httplib recognizes but was not built with must be
  12397. // reported as such. Handing the still-compressed payload back to the caller
  12398. // would silently corrupt it.
  12399. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12400. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12401. Server svr;
  12402. // "image/jpeg" keeps the server from applying a content coding of its own,
  12403. // so the hand-crafted Content-Encoding below survives.
  12404. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12405. res.set_content(gzipped, "image/jpeg");
  12406. res.set_header("Content-Encoding", "gzip");
  12407. });
  12408. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12409. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12410. res.set_content(gzipped, "image/jpeg");
  12411. res.set_header("Content-Encoding", "GZIP");
  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. Client cli(HOST, PORT);
  12421. {
  12422. auto res = cli.Get("/gzipped");
  12423. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12425. EXPECT_EQ("Hello World!", res->body);
  12426. #else
  12427. ASSERT_FALSE(res);
  12428. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12429. #endif
  12430. }
  12431. {
  12432. // open_stream() must behave the same way.
  12433. auto handle = cli.open_stream("GET", "/gzipped");
  12434. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12435. ASSERT_TRUE(handle.is_valid());
  12436. std::string received;
  12437. char buf[256];
  12438. ssize_t n;
  12439. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12440. received.append(buf, static_cast<size_t>(n));
  12441. }
  12442. EXPECT_EQ("Hello World!", received);
  12443. #else
  12444. EXPECT_FALSE(handle.is_valid());
  12445. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12446. #endif
  12447. }
  12448. {
  12449. // A differently-cased coding must not be mistaken for an unknown one, or
  12450. // the body would be handed back still compressed.
  12451. auto res = cli.Get("/gzipped-uppercase");
  12452. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12454. EXPECT_EQ("Hello World!", res->body);
  12455. #else
  12456. ASSERT_FALSE(res);
  12457. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12458. #endif
  12459. }
  12460. }
  12461. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12462. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12463. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12464. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12465. // body a second time and appending a second Content-Encoding field line, so
  12466. // clients that decode one coding per listed value handed back raw gzip bytes.
  12467. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12468. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12469. Server svr;
  12470. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12471. // keeps the server from applying a coding of its own.
  12472. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12473. res.set_content(gzipped, "text/plain");
  12474. res.set_header("Content-Encoding", "gzip");
  12475. });
  12476. auto port = svr.bind_to_any_port(HOST);
  12477. thread t = thread([&]() { svr.listen_after_bind(); });
  12478. auto se = detail::scope_exit([&] {
  12479. svr.stop();
  12480. t.join();
  12481. ASSERT_FALSE(svr.is_running());
  12482. });
  12483. svr.wait_until_ready();
  12484. Client cli(HOST, port);
  12485. Headers headers = {{"Accept-Encoding", "gzip"}};
  12486. auto res = cli.Get("/pre-gzipped", headers);
  12487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12488. EXPECT_EQ(StatusCode::OK_200, res->status);
  12489. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12490. EXPECT_EQ("Hello World!", res->body);
  12491. }
  12492. // A chunked provider settles its coding where the headers are written and
  12493. // reuses it at write time. Both ends of that have to hold: a handler's own
  12494. // Content-Encoding suppresses the coding, and a response without one is still
  12495. // compressed as it always was.
  12496. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12497. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12498. const std::string plain = "Hello World! Hello World! Hello World!";
  12499. Server svr;
  12500. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12501. res.set_header("Content-Encoding", "gzip");
  12502. res.set_chunked_content_provider(
  12503. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12504. sink.write(gzipped.data(), gzipped.size());
  12505. sink.done();
  12506. return true;
  12507. });
  12508. });
  12509. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12510. res.set_chunked_content_provider(
  12511. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12512. sink.write(plain.data(), plain.size());
  12513. sink.done();
  12514. return true;
  12515. });
  12516. });
  12517. auto port = svr.bind_to_any_port(HOST);
  12518. thread t = thread([&]() { svr.listen_after_bind(); });
  12519. auto se = detail::scope_exit([&] {
  12520. svr.stop();
  12521. t.join();
  12522. ASSERT_FALSE(svr.is_running());
  12523. });
  12524. svr.wait_until_ready();
  12525. Client cli(HOST, port);
  12526. Headers headers = {{"Accept-Encoding", "gzip"}};
  12527. {
  12528. auto res = cli.Get("/pre-gzipped", headers);
  12529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12530. EXPECT_EQ(StatusCode::OK_200, res->status);
  12531. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12532. EXPECT_EQ("Hello World!", res->body);
  12533. }
  12534. {
  12535. auto res = cli.Get("/negotiated", headers);
  12536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12537. EXPECT_EQ(StatusCode::OK_200, res->status);
  12538. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12539. EXPECT_EQ(plain, res->body);
  12540. }
  12541. }
  12542. #endif
  12543. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12544. // the same message as the comma-joined one, so both have to be read the same
  12545. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12546. // single gzip coding, and a body the sender says was encoded twice was handed
  12547. // back after one pass, still compressed but presented as decoded.
  12548. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12549. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12550. Server svr;
  12551. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12552. res.set_content(body, "image/jpeg");
  12553. res.headers.emplace("Content-Encoding", "gzip");
  12554. res.headers.emplace("Content-Encoding", "gzip");
  12555. });
  12556. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12557. res.set_content(body, "image/jpeg");
  12558. res.set_header("Content-Encoding", "gzip, gzip");
  12559. });
  12560. auto port = svr.bind_to_any_port(HOST);
  12561. thread t = thread([&]() { svr.listen_after_bind(); });
  12562. auto se = detail::scope_exit([&] {
  12563. svr.stop();
  12564. t.join();
  12565. ASSERT_FALSE(svr.is_running());
  12566. });
  12567. svr.wait_until_ready();
  12568. Client cli(HOST, port);
  12569. // Two codings is not something cpp-httplib decodes, so both representations
  12570. // take the pass-through path rather than one of them being gunzipped once.
  12571. for (const char *path : {"/split", "/joined"}) {
  12572. auto res = cli.Get(path);
  12573. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12574. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12575. EXPECT_EQ(body, res->body) << path;
  12576. }
  12577. }
  12578. // Regression test for DoS vulnerability: a malicious server sending a response
  12579. // without Content-Length header must not cause unbounded memory consumption on
  12580. // the client side. The client should stop reading after a reasonable limit,
  12581. // similar to the server-side set_payload_max_length protection.
  12582. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12583. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12584. #ifndef _WIN32
  12585. signal(SIGPIPE, SIG_IGN);
  12586. #endif
  12587. auto server_thread = std::thread([] {
  12588. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12589. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12590. default_socket_options(srv);
  12591. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12592. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12593. sockaddr_in addr{};
  12594. addr.sin_family = AF_INET;
  12595. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12596. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12597. int opt = 1;
  12598. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12599. #ifdef _WIN32
  12600. reinterpret_cast<const char *>(&opt),
  12601. #else
  12602. &opt,
  12603. #endif
  12604. sizeof(opt));
  12605. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12606. ::listen(srv, 1);
  12607. sockaddr_in cli_addr{};
  12608. socklen_t cli_len = sizeof(cli_addr);
  12609. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12610. if (cli != INVALID_SOCKET) {
  12611. char buf[4096];
  12612. ::recv(cli, buf, sizeof(buf), 0);
  12613. // Malicious response: no Content-Length, no chunked encoding
  12614. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12615. "Connection: close\r\n"
  12616. "\r\n";
  12617. ::send(cli,
  12618. #ifdef _WIN32
  12619. static_cast<const char *>(response_header.c_str()),
  12620. static_cast<int>(response_header.size()),
  12621. #else
  12622. response_header.c_str(), response_header.size(),
  12623. #endif
  12624. 0);
  12625. // Send 10MB of data
  12626. std::string chunk(64 * 1024, 'A');
  12627. size_t total_sent = 0;
  12628. while (total_sent < MALICIOUS_DATA_SIZE) {
  12629. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12630. auto sent = ::send(cli,
  12631. #ifdef _WIN32
  12632. static_cast<const char *>(chunk.c_str()),
  12633. static_cast<int>(to_send),
  12634. #else
  12635. chunk.c_str(), to_send,
  12636. #endif
  12637. 0);
  12638. if (sent <= 0) break;
  12639. total_sent += static_cast<size_t>(sent);
  12640. }
  12641. detail::close_socket(cli);
  12642. }
  12643. detail::close_socket(srv);
  12644. });
  12645. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12646. size_t total_read = 0;
  12647. {
  12648. Client cli("127.0.0.1", PORT + 2);
  12649. cli.set_read_timeout(5, 0);
  12650. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12651. auto stream = cli.open_stream("GET", "/malicious");
  12652. ASSERT_TRUE(stream.is_valid());
  12653. char buffer[64 * 1024];
  12654. ssize_t n;
  12655. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12656. total_read += static_cast<size_t>(n);
  12657. }
  12658. } // StreamHandle and Client destroyed here, closing the socket
  12659. server_thread.join();
  12660. // With set_payload_max_length, the client must stop reading before consuming
  12661. // all 10MB. The read loop should be cut off at or near the configured limit.
  12662. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12663. << "Client read " << total_read << " bytes, exceeding the configured "
  12664. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12665. }
  12666. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12667. // the entire response body without truncation.
  12668. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12669. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12670. #ifndef _WIN32
  12671. signal(SIGPIPE, SIG_IGN);
  12672. #endif
  12673. auto server_thread = std::thread([] {
  12674. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12675. default_socket_options(srv);
  12676. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12677. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12678. sockaddr_in addr{};
  12679. addr.sin_family = AF_INET;
  12680. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12681. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12682. int opt = 1;
  12683. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12684. #ifdef _WIN32
  12685. reinterpret_cast<const char *>(&opt),
  12686. #else
  12687. &opt,
  12688. #endif
  12689. sizeof(opt));
  12690. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12691. ::listen(srv, 1);
  12692. sockaddr_in cli_addr{};
  12693. socklen_t cli_len = sizeof(cli_addr);
  12694. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12695. if (cli != INVALID_SOCKET) {
  12696. char buf[4096];
  12697. ::recv(cli, buf, sizeof(buf), 0);
  12698. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12699. "Connection: close\r\n"
  12700. "\r\n";
  12701. ::send(cli,
  12702. #ifdef _WIN32
  12703. static_cast<const char *>(response_header.c_str()),
  12704. static_cast<int>(response_header.size()),
  12705. #else
  12706. response_header.c_str(), response_header.size(),
  12707. #endif
  12708. 0);
  12709. std::string chunk(64 * 1024, 'A');
  12710. size_t total_sent = 0;
  12711. while (total_sent < DATA_SIZE) {
  12712. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12713. auto sent = ::send(cli,
  12714. #ifdef _WIN32
  12715. static_cast<const char *>(chunk.c_str()),
  12716. static_cast<int>(to_send),
  12717. #else
  12718. chunk.c_str(), to_send,
  12719. #endif
  12720. 0);
  12721. if (sent <= 0) break;
  12722. total_sent += static_cast<size_t>(sent);
  12723. }
  12724. #ifdef _WIN32
  12725. ::shutdown(cli, SD_SEND);
  12726. #else
  12727. ::shutdown(cli, SHUT_WR);
  12728. #endif
  12729. // Drain until the client closes its end, ensuring all data is delivered
  12730. char drain[1024];
  12731. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12732. detail::close_socket(cli);
  12733. }
  12734. detail::close_socket(srv);
  12735. });
  12736. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12737. size_t total_read = 0;
  12738. {
  12739. Client cli("127.0.0.1", PORT + 2);
  12740. cli.set_read_timeout(5, 0);
  12741. cli.set_payload_max_length(0); // 0 means no limit
  12742. auto stream = cli.open_stream("GET", "/data");
  12743. ASSERT_TRUE(stream.is_valid());
  12744. char buffer[64 * 1024];
  12745. ssize_t n;
  12746. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12747. total_read += static_cast<size_t>(n);
  12748. }
  12749. }
  12750. server_thread.join();
  12751. EXPECT_EQ(total_read, DATA_SIZE)
  12752. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12753. << " bytes without truncation, but only read " << total_read << " bytes.";
  12754. }
  12755. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12756. // enormous Content-Length must not cause the client to pre-allocate a huge
  12757. // response body buffer. The reservation is capped at payload_max_length_, and
  12758. // the read itself fails when the body exceeds the limit.
  12759. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12760. #ifndef _WIN32
  12761. signal(SIGPIPE, SIG_IGN);
  12762. #endif
  12763. auto server_thread = std::thread([] {
  12764. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12765. default_socket_options(srv);
  12766. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12767. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12768. sockaddr_in addr{};
  12769. addr.sin_family = AF_INET;
  12770. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12771. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12772. int opt = 1;
  12773. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12774. #ifdef _WIN32
  12775. reinterpret_cast<const char *>(&opt),
  12776. #else
  12777. &opt,
  12778. #endif
  12779. sizeof(opt));
  12780. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12781. ::listen(srv, 1);
  12782. sockaddr_in cli_addr{};
  12783. socklen_t cli_len = sizeof(cli_addr);
  12784. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12785. if (cli != INVALID_SOCKET) {
  12786. char buf[4096];
  12787. ::recv(cli, buf, sizeof(buf), 0);
  12788. // Malicious response: claim a 20GB body but send only a tiny payload.
  12789. std::string response = "HTTP/1.1 200 OK\r\n"
  12790. "Content-Length: 20000000000\r\n"
  12791. "\r\n"
  12792. "abc";
  12793. ::send(cli,
  12794. #ifdef _WIN32
  12795. static_cast<const char *>(response.c_str()),
  12796. static_cast<int>(response.size()),
  12797. #else
  12798. response.c_str(), response.size(),
  12799. #endif
  12800. 0);
  12801. detail::close_socket(cli);
  12802. }
  12803. detail::close_socket(srv);
  12804. });
  12805. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12806. {
  12807. Client cli("127.0.0.1", PORT + 2);
  12808. cli.set_read_timeout(5, 0);
  12809. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12810. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12811. // (server claims more bytes than payload_max_length permits), but it must
  12812. // not exhaust memory before getting there.
  12813. auto res = cli.Get("/malicious");
  12814. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12815. }
  12816. server_thread.join();
  12817. }
  12818. // Verify that content_receiver bypasses the default payload_max_length,
  12819. // allowing streaming downloads larger than 100MB without requiring an explicit
  12820. // set_payload_max_length call.
  12821. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12822. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12823. #ifndef _WIN32
  12824. signal(SIGPIPE, SIG_IGN);
  12825. #endif
  12826. auto server_thread = std::thread([] {
  12827. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12828. default_socket_options(srv);
  12829. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12830. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12831. sockaddr_in addr{};
  12832. addr.sin_family = AF_INET;
  12833. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12834. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12835. int opt = 1;
  12836. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12837. #ifdef _WIN32
  12838. reinterpret_cast<const char *>(&opt),
  12839. #else
  12840. &opt,
  12841. #endif
  12842. sizeof(opt));
  12843. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12844. ::listen(srv, 1);
  12845. sockaddr_in cli_addr{};
  12846. socklen_t cli_len = sizeof(cli_addr);
  12847. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12848. if (cli != INVALID_SOCKET) {
  12849. char buf[4096];
  12850. ::recv(cli, buf, sizeof(buf), 0);
  12851. // Response with Content-Length larger than default 100MB limit
  12852. auto content_length = std::to_string(DATA_SIZE);
  12853. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12854. "Content-Length: " +
  12855. content_length +
  12856. "\r\n"
  12857. "Connection: close\r\n"
  12858. "\r\n";
  12859. ::send(cli,
  12860. #ifdef _WIN32
  12861. static_cast<const char *>(response_header.c_str()),
  12862. static_cast<int>(response_header.size()),
  12863. #else
  12864. response_header.c_str(), response_header.size(),
  12865. #endif
  12866. 0);
  12867. std::string chunk(64 * 1024, 'A');
  12868. size_t total_sent = 0;
  12869. while (total_sent < DATA_SIZE) {
  12870. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12871. auto sent = ::send(cli,
  12872. #ifdef _WIN32
  12873. static_cast<const char *>(chunk.c_str()),
  12874. static_cast<int>(to_send),
  12875. #else
  12876. chunk.c_str(), to_send,
  12877. #endif
  12878. 0);
  12879. if (sent <= 0) break;
  12880. total_sent += static_cast<size_t>(sent);
  12881. }
  12882. detail::close_socket(cli);
  12883. }
  12884. detail::close_socket(srv);
  12885. });
  12886. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12887. size_t total_received = 0;
  12888. {
  12889. Client cli("127.0.0.1", PORT + 2);
  12890. cli.set_read_timeout(10, 0);
  12891. // Do NOT call set_payload_max_length — use the default 100MB limit
  12892. auto res =
  12893. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12894. total_received += data_length;
  12895. return true;
  12896. });
  12897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12898. EXPECT_EQ(StatusCode::OK_200, res->status);
  12899. }
  12900. server_thread.join();
  12901. EXPECT_EQ(total_received, DATA_SIZE)
  12902. << "With content_receiver, the client should read all " << DATA_SIZE
  12903. << " bytes despite the default 100MB payload_max_length, but only read "
  12904. << total_received << " bytes.";
  12905. }
  12906. // Verify that an explicit set_payload_max_length smaller than the response is
  12907. // enforced even when a content_receiver is used.
  12908. TEST(ClientVulnerabilityTest,
  12909. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12910. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12911. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12912. #ifndef _WIN32
  12913. signal(SIGPIPE, SIG_IGN);
  12914. #endif
  12915. auto server_thread = std::thread([] {
  12916. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12917. default_socket_options(srv);
  12918. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12919. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12920. sockaddr_in addr{};
  12921. addr.sin_family = AF_INET;
  12922. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12923. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12924. int opt = 1;
  12925. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12926. #ifdef _WIN32
  12927. reinterpret_cast<const char *>(&opt),
  12928. #else
  12929. &opt,
  12930. #endif
  12931. sizeof(opt));
  12932. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12933. ::listen(srv, 1);
  12934. sockaddr_in cli_addr{};
  12935. socklen_t cli_len = sizeof(cli_addr);
  12936. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12937. if (cli != INVALID_SOCKET) {
  12938. char buf[4096];
  12939. ::recv(cli, buf, sizeof(buf), 0);
  12940. auto content_length = std::to_string(DATA_SIZE);
  12941. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12942. "Content-Length: " +
  12943. content_length +
  12944. "\r\n"
  12945. "Connection: close\r\n"
  12946. "\r\n";
  12947. ::send(cli,
  12948. #ifdef _WIN32
  12949. static_cast<const char *>(response_header.c_str()),
  12950. static_cast<int>(response_header.size()),
  12951. #else
  12952. response_header.c_str(), response_header.size(),
  12953. #endif
  12954. 0);
  12955. std::string chunk(64 * 1024, 'A');
  12956. size_t total_sent = 0;
  12957. while (total_sent < DATA_SIZE) {
  12958. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12959. auto sent = ::send(cli,
  12960. #ifdef _WIN32
  12961. static_cast<const char *>(chunk.c_str()),
  12962. static_cast<int>(to_send),
  12963. #else
  12964. chunk.c_str(), to_send,
  12965. #endif
  12966. 0);
  12967. if (sent <= 0) break;
  12968. total_sent += static_cast<size_t>(sent);
  12969. }
  12970. detail::close_socket(cli);
  12971. }
  12972. detail::close_socket(srv);
  12973. });
  12974. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12975. size_t total_received = 0;
  12976. {
  12977. Client cli("127.0.0.1", PORT + 2);
  12978. cli.set_read_timeout(10, 0);
  12979. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12980. auto res =
  12981. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12982. total_received += data_length;
  12983. return true;
  12984. });
  12985. // Should fail because 200MB exceeds the explicit 150MB limit
  12986. EXPECT_FALSE(res);
  12987. }
  12988. server_thread.join();
  12989. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12990. << "Client with content_receiver should respect the explicit "
  12991. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12992. << total_received << " bytes.";
  12993. }
  12994. // Verify that an explicit set_payload_max_length larger than the response
  12995. // allows the content_receiver to read all data successfully.
  12996. TEST(ClientVulnerabilityTest,
  12997. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12998. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12999. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13000. #ifndef _WIN32
  13001. signal(SIGPIPE, SIG_IGN);
  13002. #endif
  13003. auto server_thread = std::thread([] {
  13004. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13005. default_socket_options(srv);
  13006. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13007. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13008. sockaddr_in addr{};
  13009. addr.sin_family = AF_INET;
  13010. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13011. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13012. int opt = 1;
  13013. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13014. #ifdef _WIN32
  13015. reinterpret_cast<const char *>(&opt),
  13016. #else
  13017. &opt,
  13018. #endif
  13019. sizeof(opt));
  13020. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13021. ::listen(srv, 1);
  13022. sockaddr_in cli_addr{};
  13023. socklen_t cli_len = sizeof(cli_addr);
  13024. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13025. if (cli != INVALID_SOCKET) {
  13026. char buf[4096];
  13027. ::recv(cli, buf, sizeof(buf), 0);
  13028. auto content_length = std::to_string(DATA_SIZE);
  13029. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13030. "Content-Length: " +
  13031. content_length +
  13032. "\r\n"
  13033. "Connection: close\r\n"
  13034. "\r\n";
  13035. ::send(cli,
  13036. #ifdef _WIN32
  13037. static_cast<const char *>(response_header.c_str()),
  13038. static_cast<int>(response_header.size()),
  13039. #else
  13040. response_header.c_str(), response_header.size(),
  13041. #endif
  13042. 0);
  13043. std::string chunk(64 * 1024, 'A');
  13044. size_t total_sent = 0;
  13045. while (total_sent < DATA_SIZE) {
  13046. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13047. auto sent = ::send(cli,
  13048. #ifdef _WIN32
  13049. static_cast<const char *>(chunk.c_str()),
  13050. static_cast<int>(to_send),
  13051. #else
  13052. chunk.c_str(), to_send,
  13053. #endif
  13054. 0);
  13055. if (sent <= 0) break;
  13056. total_sent += static_cast<size_t>(sent);
  13057. }
  13058. #ifdef _WIN32
  13059. ::shutdown(cli, SD_SEND);
  13060. #else
  13061. ::shutdown(cli, SHUT_WR);
  13062. #endif
  13063. char drain[1024];
  13064. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13065. detail::close_socket(cli);
  13066. }
  13067. detail::close_socket(srv);
  13068. });
  13069. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13070. size_t total_received = 0;
  13071. {
  13072. Client cli("127.0.0.1", PORT + 2);
  13073. cli.set_read_timeout(10, 0);
  13074. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13075. auto res =
  13076. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13077. total_received += data_length;
  13078. return true;
  13079. });
  13080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13081. EXPECT_EQ(StatusCode::OK_200, res->status);
  13082. }
  13083. server_thread.join();
  13084. EXPECT_EQ(total_received, DATA_SIZE)
  13085. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13086. << " bytes (larger than " << DATA_SIZE
  13087. << " bytes response), content_receiver should read all data, but only "
  13088. "read "
  13089. << total_received << " bytes.";
  13090. }
  13091. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13092. // Regression test for "zip bomb" attack on the client side: a malicious server
  13093. // sends a small gzip-compressed response that decompresses to a huge payload.
  13094. // The client must enforce payload_max_length on the decompressed size.
  13095. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13096. constexpr size_t DECOMPRESSED_SIZE =
  13097. 10 * 1024 * 1024; // 10MB after decompression
  13098. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13099. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13100. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13101. std::string compressed;
  13102. {
  13103. httplib::detail::gzip_compressor compressor;
  13104. bool ok =
  13105. compressor.compress(uncompressed.data(), uncompressed.size(),
  13106. /*last=*/true, [&](const char *buf, size_t len) {
  13107. compressed.append(buf, len);
  13108. return true;
  13109. });
  13110. ASSERT_TRUE(ok);
  13111. }
  13112. // Sanity: compressed data should be much smaller than the decompressed size
  13113. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13114. #ifndef _WIN32
  13115. signal(SIGPIPE, SIG_IGN);
  13116. #endif
  13117. // Set up the listening socket in the main thread so the server is guaranteed
  13118. // to be ready before the client connects (eliminates race condition).
  13119. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13120. default_socket_options(srv);
  13121. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13122. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13123. sockaddr_in addr{};
  13124. addr.sin_family = AF_INET;
  13125. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13126. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13127. int opt = 1;
  13128. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13129. #ifdef _WIN32
  13130. reinterpret_cast<const char *>(&opt),
  13131. #else
  13132. &opt,
  13133. #endif
  13134. sizeof(opt));
  13135. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13136. ASSERT_EQ(0, ::listen(srv, 1));
  13137. auto server_thread = std::thread([&compressed, srv] {
  13138. sockaddr_in cli_addr{};
  13139. socklen_t cli_len = sizeof(cli_addr);
  13140. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13141. if (cli != INVALID_SOCKET) {
  13142. // Read the full HTTP request (until \r\n\r\n)
  13143. char buf[4096];
  13144. size_t total = 0;
  13145. while (total < sizeof(buf)) {
  13146. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13147. if (n <= 0) break;
  13148. total += static_cast<size_t>(n);
  13149. // Check for end of headers
  13150. if (total >= 4) {
  13151. std::string req(buf, total);
  13152. if (req.find("\r\n\r\n") != std::string::npos) break;
  13153. }
  13154. }
  13155. // Malicious response: gzip-compressed body, no Content-Length
  13156. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13157. "Content-Encoding: gzip\r\n"
  13158. "Connection: close\r\n"
  13159. "\r\n";
  13160. ::send(cli,
  13161. #ifdef _WIN32
  13162. static_cast<const char *>(response_header.c_str()),
  13163. static_cast<int>(response_header.size()),
  13164. #else
  13165. response_header.c_str(), response_header.size(),
  13166. #endif
  13167. 0);
  13168. // Send the compressed payload (small on the wire, huge when decompressed)
  13169. size_t total_sent = 0;
  13170. while (total_sent < compressed.size()) {
  13171. auto to_send = std::min(compressed.size() - total_sent,
  13172. static_cast<size_t>(64 * 1024));
  13173. auto sent =
  13174. ::send(cli,
  13175. #ifdef _WIN32
  13176. static_cast<const char *>(compressed.c_str() + total_sent),
  13177. static_cast<int>(to_send),
  13178. #else
  13179. compressed.c_str() + total_sent, to_send,
  13180. #endif
  13181. 0);
  13182. if (sent <= 0) break;
  13183. total_sent += static_cast<size_t>(sent);
  13184. }
  13185. detail::close_socket(cli);
  13186. }
  13187. });
  13188. auto se = detail::scope_exit([&] {
  13189. detail::close_socket(srv);
  13190. server_thread.join();
  13191. });
  13192. size_t total_decompressed = 0;
  13193. {
  13194. Client cli("127.0.0.1", PORT + 3);
  13195. cli.set_read_timeout(5, 0);
  13196. cli.set_decompress(true);
  13197. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13198. auto stream = cli.open_stream("GET", "/zipbomb");
  13199. ASSERT_TRUE(stream.is_valid());
  13200. char buffer[64 * 1024];
  13201. ssize_t n;
  13202. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13203. total_decompressed += static_cast<size_t>(n);
  13204. }
  13205. }
  13206. // The decompressed size must be capped by payload_max_length. Without
  13207. // protection, the client would decompress the full 10MB from a tiny
  13208. // compressed payload, enabling a zip bomb DoS attack.
  13209. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13210. << "Client decompressed " << total_decompressed
  13211. << " bytes from a gzip response. The decompressed size should be "
  13212. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13213. }
  13214. #endif
  13215. TEST(HostAndPortPropertiesTest, NoSSL) {
  13216. httplib::Client cli("www.google.com", 1234);
  13217. ASSERT_EQ("www.google.com", cli.host());
  13218. ASSERT_EQ(1234, cli.port());
  13219. }
  13220. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13221. httplib::Client cli("www.google.com:1234");
  13222. ASSERT_EQ("www.google.com", cli.host());
  13223. ASSERT_EQ(1234, cli.port());
  13224. }
  13225. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13226. // Port number that overflows int — should not crash, client becomes invalid
  13227. httplib::Client cli("http://www.google.com:99999999999999999999");
  13228. ASSERT_FALSE(cli.is_valid());
  13229. }
  13230. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13231. // Port 99999 exceeds valid range (1-65535) — should not crash
  13232. httplib::Client cli("http://www.google.com:99999");
  13233. ASSERT_FALSE(cli.is_valid());
  13234. auto res = cli.Get("/");
  13235. EXPECT_FALSE(res);
  13236. EXPECT_EQ(Error::Connection, res.error());
  13237. }
  13238. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13239. httplib::Client cli("http://user:pass@localhost:1234");
  13240. ASSERT_FALSE(cli.is_valid());
  13241. EXPECT_FALSE(cli.Get("/"));
  13242. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13243. }
  13244. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13245. httplib::Client cli("http://www.google.com:80abc");
  13246. ASSERT_FALSE(cli.is_valid());
  13247. }
  13248. #ifdef CPPHTTPLIB_SSL_ENABLED
  13249. TEST(HostAndPortPropertiesTest, SSL) {
  13250. httplib::SSLClient cli("www.google.com");
  13251. ASSERT_EQ("www.google.com", cli.host());
  13252. ASSERT_EQ(443, cli.port());
  13253. }
  13254. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13255. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13256. std::string cert;
  13257. read_file(CA_CERT_FILE, cert);
  13258. httplib::SSLClient httplib_client("www.google.com");
  13259. // Load CA store first time
  13260. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13261. // Load CA store second time (update)
  13262. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13263. // Verify client is still valid and can make connections
  13264. httplib_client.enable_server_certificate_verification(true);
  13265. auto res = httplib_client.Get("/");
  13266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13267. // Google may return 200 or 301 depending on various factors
  13268. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13269. res->status == StatusCode::MovedPermanently_301);
  13270. }
  13271. TEST(SSLClientTest, ServerNameIndication_Online) {
  13272. auto host = "httpbingo.org";
  13273. auto path = std::string{"/get"};
  13274. SSLClient cli(host, 443);
  13275. auto res = cli.Get(path);
  13276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13277. ASSERT_EQ(StatusCode::OK_200, res->status);
  13278. }
  13279. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13280. // Use a site that will cause SSL verification failure due to self-signed cert
  13281. SSLClient cli("self-signed.badssl.com", 443);
  13282. cli.enable_server_certificate_verification(true);
  13283. auto res = cli.Get("/");
  13284. ASSERT_TRUE(!res);
  13285. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13286. // Verify backend error is captured for SSLServerVerification
  13287. // This occurs when certificate verification fails
  13288. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13289. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13290. EXPECT_NE(0UL, res.ssl_backend_error());
  13291. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13292. // For OpenSSL, ssl_error is 0 for verification errors
  13293. EXPECT_EQ(0, res.ssl_error());
  13294. #if !defined(_WIN32) || \
  13295. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13296. // On non-Windows or when Windows Schannel is disabled, the error comes
  13297. // from OpenSSL's verification
  13298. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13299. res.ssl_backend_error());
  13300. #endif
  13301. #endif
  13302. }
  13303. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13304. // Use a site where hostname doesn't match the certificate
  13305. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13306. SSLClient cli("wrong.host.badssl.com", 443);
  13307. cli.enable_server_certificate_verification(true);
  13308. cli.enable_server_hostname_verification(true);
  13309. auto res = cli.Get("/");
  13310. ASSERT_TRUE(!res);
  13311. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13312. // Verify backend error is captured for hostname verification failure
  13313. EXPECT_NE(0UL, res.ssl_backend_error());
  13314. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13315. // For OpenSSL, ssl_error is 0 for verification errors
  13316. EXPECT_EQ(0, res.ssl_error());
  13317. #if !defined(_WIN32) || \
  13318. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13319. // On non-Windows or when Windows Schannel is disabled, the error comes
  13320. // from OpenSSL's hostname verification
  13321. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13322. res.ssl_backend_error());
  13323. #endif
  13324. #endif
  13325. }
  13326. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13327. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13328. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13329. SSLClient cli("www.google.com", 443);
  13330. cli.enable_server_certificate_verification(true);
  13331. auto res = cli.Get("/");
  13332. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13333. }
  13334. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13335. SSLClient cli("www.google.com", 443);
  13336. cli.enable_server_certificate_verification(true);
  13337. cli.enable_windows_certificate_verification(false);
  13338. auto res = cli.Get("/");
  13339. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13340. }
  13341. // The server sends an intermediate cross-signed by a root Windows trusts,
  13342. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13343. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13344. SSLClient cli("accounts.spotify.com", 443);
  13345. auto res = cli.Get("/");
  13346. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13347. << " ssl_backend_error=" << res.ssl_backend_error();
  13348. }
  13349. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13350. // policy status, which no backend reports for a self-signed certificate.
  13351. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13352. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13353. ASSERT_TRUE(svr.is_valid());
  13354. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13355. auto se = detail::scope_exit([&] {
  13356. svr.stop();
  13357. t.join();
  13358. ASSERT_FALSE(svr.is_running());
  13359. });
  13360. svr.wait_until_ready();
  13361. SSLClient cli("127.0.0.1", PORT);
  13362. cli.set_connection_timeout(30);
  13363. auto res = cli.Get("/");
  13364. ASSERT_FALSE(res);
  13365. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13366. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13367. }
  13368. #endif
  13369. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13370. Client cli("https://google.com");
  13371. auto res = cli.Get("/");
  13372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13373. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13374. }
  13375. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13376. SSLClient cli("google.com");
  13377. cli.set_ca_cert_path(CA_CERT_FILE);
  13378. auto res = cli.Get("/");
  13379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13380. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13381. }
  13382. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13383. SSLClient cli("google.com");
  13384. cli.enable_server_certificate_verification(true);
  13385. cli.set_ca_cert_path("hello");
  13386. auto res = cli.Get("/");
  13387. ASSERT_TRUE(!res);
  13388. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13389. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13390. // should be set
  13391. EXPECT_EQ(0, res.ssl_error());
  13392. // Verify backend error is captured for SSLLoadingCerts
  13393. // This error occurs when loading CA certificates fails
  13394. EXPECT_NE(0UL, res.ssl_backend_error());
  13395. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13396. // OpenSSL specific error codes:
  13397. // > openssl errstr 0x80000002
  13398. // error:80000002:system library::No such file or directory
  13399. // > openssl errstr 0xA000126
  13400. // error:0A000126:SSL routines::unexpected eof while reading
  13401. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13402. res.ssl_backend_error() == 0xA000126);
  13403. #endif
  13404. }
  13405. TEST(SSLClientTest, ServerCertificateVerification4) {
  13406. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13407. ASSERT_TRUE(svr.is_valid());
  13408. svr.Get("/test", [&](const Request &, Response &res) {
  13409. res.set_content("test", "text/plain");
  13410. svr.stop();
  13411. ASSERT_TRUE(true);
  13412. });
  13413. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13414. auto se = detail::scope_exit([&] {
  13415. t.join();
  13416. ASSERT_FALSE(svr.is_running());
  13417. });
  13418. svr.wait_until_ready();
  13419. SSLClient cli("127.0.0.1", PORT);
  13420. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13421. cli.enable_server_certificate_verification(true);
  13422. cli.set_connection_timeout(30);
  13423. auto res = cli.Get("/test");
  13424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13425. ASSERT_EQ(StatusCode::OK_200, res->status);
  13426. }
  13427. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13428. std::string cert;
  13429. read_file(CA_CERT_FILE, cert);
  13430. SSLClient cli("google.com");
  13431. cli.load_ca_cert_store(cert.data(), cert.size());
  13432. const auto res = cli.Get("/");
  13433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13434. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13435. }
  13436. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13437. // clang-format off
  13438. static constexpr char cert[] =
  13439. "GlobalSign Root CA\n"
  13440. "==================\n"
  13441. "-----BEGIN CERTIFICATE-----\n"
  13442. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13443. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13444. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13445. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13446. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13447. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13448. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13449. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13450. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13451. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13452. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13453. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13454. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13455. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13456. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13457. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13458. "-----END CERTIFICATE-----\n";
  13459. // clang-format on
  13460. SSLClient cli("google.com");
  13461. cli.load_ca_cert_store(cert, sizeof(cert));
  13462. const auto res = cli.Get("/");
  13463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13464. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13465. }
  13466. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13467. SSLClient cli("www.youtube.com");
  13468. cli.set_ca_cert_path(CA_CERT_FILE);
  13469. cli.enable_server_certificate_verification(true);
  13470. cli.set_follow_location(true);
  13471. auto res = cli.Get("/");
  13472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13473. ASSERT_EQ(StatusCode::OK_200, res->status);
  13474. }
  13475. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13476. SSLClient cli("wWw.YouTube.Com");
  13477. cli.set_ca_cert_path(CA_CERT_FILE);
  13478. cli.enable_server_certificate_verification(true);
  13479. cli.enable_server_hostname_verification(true);
  13480. cli.set_follow_location(true);
  13481. auto res = cli.Get("/");
  13482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13483. ASSERT_EQ(StatusCode::OK_200, res->status);
  13484. }
  13485. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13486. SSLClient cli("gOoGlE.COm");
  13487. cli.enable_server_certificate_verification(true);
  13488. cli.enable_server_hostname_verification(true);
  13489. cli.set_follow_location(true);
  13490. auto res = cli.Get("/");
  13491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13492. ASSERT_EQ(StatusCode::OK_200, res->status);
  13493. }
  13494. TEST(SSLClientTest, Issue2004_Online) {
  13495. Client client("https://google.com");
  13496. client.set_follow_location(true);
  13497. auto res = client.Get("/");
  13498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13499. ASSERT_EQ(StatusCode::OK_200, res->status);
  13500. auto body = res->body;
  13501. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13502. }
  13503. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13504. // Create SSLClient with invalid cert/key to make is_valid() return false
  13505. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13506. "nonexistent_key.pem");
  13507. // is_valid() should be false due to cert loading failure
  13508. ASSERT_FALSE(cli.is_valid());
  13509. auto res = cli.Get("/");
  13510. ASSERT_FALSE(res);
  13511. EXPECT_EQ(Error::SSLConnection, res.error());
  13512. }
  13513. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13514. // Test for Issue #2251: SSL error not properly reported when client cert
  13515. // and key paths are swapped or mismatched
  13516. // This simulates the scenario where user accidentally swaps the cert and key
  13517. // files
  13518. // Using client cert file as private key and vice versa (completely wrong)
  13519. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13520. // Should fail validation due to cert/key mismatch
  13521. ASSERT_FALSE(cli.is_valid());
  13522. // Attempt to make a request should fail with proper error
  13523. auto res = cli.Get("/");
  13524. ASSERT_FALSE(res);
  13525. EXPECT_EQ(Error::SSLConnection, res.error());
  13526. // SSL error should be recorded in the Result object (this is the key fix for
  13527. // Issue #2251)
  13528. auto backend_error = res.ssl_backend_error();
  13529. EXPECT_NE(0u, backend_error);
  13530. }
  13531. // Tests cert/key mismatch detection at the TLS context level
  13532. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13533. // Test that using mismatched cert/key causes connection failure.
  13534. // We verify this at the SSLClient level rather than through internal
  13535. // TLS API functions.
  13536. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13537. cli.enable_server_certificate_verification(false);
  13538. cli.set_connection_timeout(2);
  13539. // The mismatch should cause a connection or handshake error
  13540. auto res = cli.Get("/test");
  13541. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13542. // Either way, the request should fail
  13543. EXPECT_FALSE(res);
  13544. }
  13545. #endif
  13546. #if 0
  13547. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13548. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13549. ASSERT_TRUE(cli != nullptr);
  13550. cli->set_address_family(AF_INET6);
  13551. cli->set_interface("en0");
  13552. auto res = cli->Get("/get");
  13553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13554. ASSERT_EQ(StatusCode::OK_200, res->status);
  13555. }
  13556. #endif
  13557. // Client certificate tests - work with all TLS backends
  13558. #ifdef CPPHTTPLIB_SSL_ENABLED
  13559. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13560. void ClientCertPresent(
  13561. const std::string &client_cert_file,
  13562. const std::string &client_private_key_file,
  13563. const std::string &client_encrypted_private_key_pass = std::string(),
  13564. const ClientCertServerSetup &setup = nullptr) {
  13565. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13566. ASSERT_TRUE(svr.is_valid());
  13567. if (setup) { setup(svr); }
  13568. svr.Get("/test", [&](const Request &req, Response &res) {
  13569. res.set_content("test", "text/plain");
  13570. auto cert = req.peer_cert();
  13571. ASSERT_TRUE(static_cast<bool>(cert));
  13572. std::string common_name = cert.subject_cn();
  13573. EXPECT_EQ("Common Name", common_name);
  13574. });
  13575. auto port = svr.bind_to_any_port(HOST);
  13576. ASSERT_LT(0, port);
  13577. thread t = thread([&]() { svr.listen_after_bind(); });
  13578. auto se = detail::scope_exit([&] {
  13579. svr.stop();
  13580. t.join();
  13581. ASSERT_FALSE(svr.is_running());
  13582. });
  13583. svr.wait_until_ready();
  13584. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13585. client_encrypted_private_key_pass);
  13586. cli.enable_server_certificate_verification(false);
  13587. cli.set_connection_timeout(30);
  13588. auto res = cli.Get("/test");
  13589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13590. ASSERT_EQ(StatusCode::OK_200, res->status);
  13591. }
  13592. TEST(SSLClientServerTest, ClientCertPresent) {
  13593. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13594. }
  13595. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13596. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13597. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13598. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13599. }
  13600. // Expects svr, which must require client certificates, to reject a client
  13601. // that has none
  13602. void RejectsClientWithoutCert(SSLServer &svr) {
  13603. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13604. auto port = svr.bind_to_any_port(HOST);
  13605. ASSERT_LT(0, port);
  13606. thread t = thread([&]() { svr.listen_after_bind(); });
  13607. auto se = detail::scope_exit([&] {
  13608. svr.stop();
  13609. t.join();
  13610. ASSERT_FALSE(svr.is_running());
  13611. });
  13612. svr.wait_until_ready();
  13613. SSLClient cli(HOST, port);
  13614. cli.set_connection_timeout(30);
  13615. // Skip the server certificate check, so that the request fails because the
  13616. // client certificate is missing rather than because cert.pem is not trusted
  13617. cli.enable_server_certificate_verification(false);
  13618. auto res = cli.Get("/test");
  13619. ASSERT_FALSE(res);
  13620. // The server rejects the client during the handshake, or on TLS 1.3 right
  13621. // after it, which the client notices on its first write or read
  13622. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13623. res.error() == Error::Write || res.error() == Error::Read)
  13624. << to_string(res.error());
  13625. if (res.error() == Error::SSLConnection) {
  13626. EXPECT_NE(0UL, res.ssl_backend_error());
  13627. }
  13628. // A rejection noticed on the write keeps the TLS error the write hit
  13629. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13630. }
  13631. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13632. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13633. ASSERT_TRUE(svr.is_valid());
  13634. if (setup) { setup(svr); }
  13635. RejectsClientWithoutCert(svr);
  13636. }
  13637. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13638. // A server that requires client certificates must keep requiring them after
  13639. // setup changes it, and keep accepting a client that has one
  13640. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13641. ClientCertMissing(setup);
  13642. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13643. setup);
  13644. }
  13645. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13646. ClientCertStillRequired([](SSLServer &svr) {
  13647. ASSERT_TRUE(tls::set_verify_callback(
  13648. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13649. });
  13650. }
  13651. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13652. ClientCertStillRequired([](SSLServer &svr) {
  13653. ASSERT_TRUE(tls::set_verify_callback(
  13654. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13655. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13656. });
  13657. }
  13658. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13659. ClientCertStillRequired([](SSLServer &svr) {
  13660. std::string cert_pem, key_pem, ca_pem;
  13661. read_file(SERVER_CERT_FILE, cert_pem);
  13662. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13663. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13664. ASSERT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  13665. ca_pem.c_str()));
  13666. });
  13667. }
  13668. // A TLS error from one request must not show up in a later request's Result
  13669. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13671. ASSERT_TRUE(svr.is_valid());
  13672. svr.Get("/test", [](const Request &, Response &res) {
  13673. res.set_content("test", "text/plain");
  13674. });
  13675. auto port = svr.bind_to_any_port(HOST);
  13676. ASSERT_LT(0, port);
  13677. thread t = thread([&]() { svr.listen_after_bind(); });
  13678. auto se = detail::scope_exit([&] {
  13679. svr.stop();
  13680. t.join();
  13681. ASSERT_FALSE(svr.is_running());
  13682. });
  13683. svr.wait_until_ready();
  13684. SSLClient cli(HOST, port);
  13685. cli.set_connection_timeout(30);
  13686. cli.enable_server_hostname_verification(false);
  13687. // cert.pem is not trusted, so the handshake fails
  13688. ASSERT_FALSE(cli.Get("/test"));
  13689. cli.enable_server_certificate_verification(false);
  13690. auto res = cli.Get("/test");
  13691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13692. EXPECT_EQ(0, res.ssl_error());
  13693. EXPECT_EQ(0UL, res.ssl_backend_error());
  13694. }
  13695. // PEM memory-based constructor tests (works with all TLS backends).
  13696. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13697. // terminator after it.
  13698. void PemMemoryClientCertPresent(
  13699. const std::string &client_cert_file,
  13700. const std::string &client_private_key_file,
  13701. const std::string &client_encrypted_private_key_pass = std::string(),
  13702. bool exact_size = false) {
  13703. // Read PEM files into memory
  13704. std::string server_cert_pem, server_key_pem;
  13705. std::string client_ca_pem;
  13706. std::string client_cert_pem, client_key_pem;
  13707. read_file(SERVER_CERT_FILE, server_cert_pem);
  13708. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13709. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13710. read_file(client_cert_file, client_cert_pem);
  13711. read_file(client_private_key_file, client_key_pem);
  13712. std::list<std::vector<char>> exact_copies;
  13713. auto data = [&](const std::string &pem) -> const char * {
  13714. if (!exact_size) { return pem.c_str(); }
  13715. exact_copies.emplace_back(pem.begin(), pem.end());
  13716. return exact_copies.back().data();
  13717. };
  13718. // Create server with PEM memory
  13719. SSLServer::PemMemory server_pem = {
  13720. data(server_cert_pem),
  13721. server_cert_pem.size(),
  13722. data(server_key_pem),
  13723. server_key_pem.size(),
  13724. data(client_ca_pem),
  13725. client_ca_pem.size(),
  13726. nullptr // no password for server key
  13727. };
  13728. SSLServer svr(server_pem);
  13729. ASSERT_TRUE(svr.is_valid());
  13730. svr.Get("/test", [&](const Request &req, Response &res) {
  13731. res.set_content("test", "text/plain");
  13732. auto cert = req.peer_cert();
  13733. ASSERT_TRUE(static_cast<bool>(cert));
  13734. EXPECT_EQ("Common Name", cert.subject_cn());
  13735. });
  13736. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13737. auto se = detail::scope_exit([&] {
  13738. svr.stop();
  13739. t.join();
  13740. ASSERT_FALSE(svr.is_running());
  13741. });
  13742. svr.wait_until_ready();
  13743. // Create client with PEM memory
  13744. const char *password = client_encrypted_private_key_pass.empty()
  13745. ? nullptr
  13746. : client_encrypted_private_key_pass.c_str();
  13747. SSLClient::PemMemory client_pem = {
  13748. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13749. client_key_pem.size(), password};
  13750. SSLClient cli(HOST, PORT, client_pem);
  13751. cli.enable_server_certificate_verification(false);
  13752. cli.set_connection_timeout(30);
  13753. auto res = cli.Get("/test");
  13754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13755. ASSERT_EQ(StatusCode::OK_200, res->status);
  13756. }
  13757. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13758. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13759. }
  13760. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13761. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13762. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13763. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13764. }
  13765. // A server built from PEM memory with a client CA requires client certificates
  13766. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13767. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13768. read_file(SERVER_CERT_FILE, server_cert_pem);
  13769. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13770. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13771. SSLServer::PemMemory server_pem = {
  13772. server_cert_pem.c_str(),
  13773. server_cert_pem.size(),
  13774. server_key_pem.c_str(),
  13775. server_key_pem.size(),
  13776. client_ca_pem.c_str(),
  13777. client_ca_pem.size(),
  13778. nullptr // no password for server key
  13779. };
  13780. SSLServer svr(server_pem);
  13781. ASSERT_TRUE(svr.is_valid());
  13782. RejectsClientWithoutCert(svr);
  13783. }
  13784. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13785. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13786. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13787. true);
  13788. }
  13789. // A length shorter than the PEM cuts it short, so it no longer loads
  13790. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13791. std::string cert, key;
  13792. read_file(SERVER_CERT_FILE, cert);
  13793. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13794. for (auto cut_cert : {true, false}) {
  13795. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13796. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13797. SSLServer::PemMemory server_pem = {
  13798. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13799. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13800. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13801. key_len, nullptr};
  13802. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13803. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13804. key.c_str(), key_len, nullptr};
  13805. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13806. }
  13807. }
  13808. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13809. class NoListenSSLServer : public SSLServer {
  13810. public:
  13811. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13812. const char *client_ca_cert_file_path,
  13813. const char *client_ca_cert_dir_path = nullptr)
  13814. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13815. client_ca_cert_dir_path),
  13816. stop_(false) {}
  13817. std::atomic_bool stop_;
  13818. private:
  13819. bool process_and_close_socket(socket_t /*sock*/) override {
  13820. // Don't create SSL context
  13821. while (!stop_.load()) {
  13822. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13823. }
  13824. return true;
  13825. }
  13826. };
  13827. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13828. CLIENT_CA_CERT_FILE);
  13829. ASSERT_TRUE(svr.is_valid());
  13830. svr.Get("/test", [&](const Request &, Response &res) {
  13831. res.set_content("test", "text/plain");
  13832. });
  13833. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13834. auto se = detail::scope_exit([&] {
  13835. svr.stop_ = true;
  13836. svr.stop();
  13837. t.join();
  13838. ASSERT_FALSE(svr.is_running());
  13839. });
  13840. svr.wait_until_ready();
  13841. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13842. cli.enable_server_certificate_verification(false);
  13843. cli.set_connection_timeout(1);
  13844. auto res = cli.Get("/test");
  13845. ASSERT_TRUE(!res);
  13846. EXPECT_EQ(Error::SSLConnection, res.error());
  13847. // Timeout results in WantRead error code (maps to backend-specific value)
  13848. EXPECT_NE(0, res.ssl_error());
  13849. }
  13850. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13851. // Test SSLServer with client certificate verification using the standard
  13852. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13854. CLIENT_CA_CERT_DIR);
  13855. ASSERT_TRUE(svr.is_valid());
  13856. svr.Get("/test", [&](const Request &req, Response &res) {
  13857. res.set_content("test", "text/plain");
  13858. auto cert = req.peer_cert();
  13859. ASSERT_TRUE(static_cast<bool>(cert));
  13860. auto common_name = cert.subject_cn();
  13861. EXPECT_EQ("Common Name", common_name);
  13862. });
  13863. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13864. auto se = detail::scope_exit([&] {
  13865. svr.stop();
  13866. t.join();
  13867. ASSERT_FALSE(svr.is_running());
  13868. });
  13869. svr.wait_until_ready();
  13870. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13871. cli.enable_server_certificate_verification(false);
  13872. cli.set_connection_timeout(30);
  13873. auto res = cli.Get("/test");
  13874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13875. ASSERT_EQ(StatusCode::OK_200, res->status);
  13876. }
  13877. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13878. // Verifies that wildcard matching and exact matching work consistently
  13879. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13880. using namespace httplib::tls;
  13881. // We need a running server to test against
  13882. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13883. ASSERT_TRUE(svr.is_valid());
  13884. svr.Get("/test", [](const Request &, Response &res) {
  13885. res.set_content("ok", "text/plain");
  13886. });
  13887. thread t([&]() { svr.listen(HOST, PORT); });
  13888. auto se = detail::scope_exit([&] {
  13889. svr.stop();
  13890. t.join();
  13891. });
  13892. svr.wait_until_ready();
  13893. bool verify_callback_called = false;
  13894. bool verify_result_wrong = false;
  13895. SSLClient cli(HOST, PORT);
  13896. cli.enable_server_certificate_verification(true);
  13897. cli.set_ca_cert_path(CA_CERT_FILE);
  13898. cli.set_connection_timeout(5);
  13899. // Note: Test certificate has CN="Common Name", not "localhost"
  13900. bool verify_result_cn = false;
  13901. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13902. verify_callback_called = true;
  13903. if (!ctx.cert) return false;
  13904. // Test 1: "Common Name" should match (our test server cert CN)
  13905. verify_result_cn = ctx.check_hostname("Common Name");
  13906. // Test 2: wrong hostname should not match
  13907. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13908. return true; // Accept for the purpose of this test
  13909. });
  13910. auto res = cli.Get("/test");
  13911. // The request may succeed or fail depending on cert configuration
  13912. // but the callback should have been called
  13913. ASSERT_TRUE(verify_callback_called)
  13914. << "Verify callback should have been called";
  13915. // CN="Common Name" should match our test certificate
  13916. //
  13917. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13918. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13919. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13920. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13921. // <openssl/base.h>, which is included transitively when
  13922. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13923. #if defined(OPENSSL_IS_BORINGSSL)
  13924. EXPECT_FALSE(verify_result_cn)
  13925. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13926. #else
  13927. EXPECT_TRUE(verify_result_cn)
  13928. << "verify_hostname should match 'Common Name' (certificate CN)";
  13929. #endif
  13930. // Wrong hostname should not match
  13931. EXPECT_FALSE(verify_result_wrong)
  13932. << "verify_hostname should not match 'wronghost.example.com'";
  13933. }
  13934. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13935. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13936. // X509_check_ip behavior and must hold for every backend.
  13937. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13938. using namespace httplib::tls;
  13939. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13940. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13941. ASSERT_TRUE(svr.is_valid());
  13942. svr.Get("/test", [](const Request &, Response &res) {
  13943. res.set_content("ok", "text/plain");
  13944. });
  13945. thread t([&]() { svr.listen(HOST, PORT); });
  13946. auto se = detail::scope_exit([&] {
  13947. svr.stop();
  13948. t.join();
  13949. });
  13950. svr.wait_until_ready();
  13951. bool verify_callback_called = false;
  13952. bool ip_matched_via_cn = true;
  13953. SSLClient cli(HOST, PORT);
  13954. cli.enable_server_certificate_verification(true);
  13955. cli.set_ca_cert_path(CA_CERT_FILE);
  13956. cli.set_connection_timeout(5);
  13957. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13958. verify_callback_called = true;
  13959. if (!ctx.cert) return false;
  13960. // The IP appears only in the CN, so it must NOT be accepted.
  13961. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13962. return true; // Accept for the purpose of this test
  13963. });
  13964. cli.Get("/test");
  13965. ASSERT_TRUE(verify_callback_called)
  13966. << "Verify callback should have been called";
  13967. EXPECT_FALSE(ip_matched_via_cn)
  13968. << "An IP host must not be authenticated via the certificate CN";
  13969. }
  13970. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13971. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13972. using namespace httplib::tls;
  13973. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13974. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13975. ASSERT_TRUE(svr.is_valid());
  13976. svr.Get("/test", [](const Request &, Response &res) {
  13977. res.set_content("ok", "text/plain");
  13978. });
  13979. thread t([&]() { svr.listen(HOST, PORT); });
  13980. auto se = detail::scope_exit([&] {
  13981. svr.stop();
  13982. t.join();
  13983. });
  13984. svr.wait_until_ready();
  13985. bool verify_callback_called = false;
  13986. bool san_matched = false;
  13987. bool wrong_ipv6_matched = true;
  13988. bool cn_ipv6_matched = true;
  13989. SSLClient cli(HOST, PORT);
  13990. cli.enable_server_certificate_verification(true);
  13991. cli.set_ca_cert_path(CA_CERT_FILE);
  13992. cli.set_connection_timeout(5);
  13993. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13994. verify_callback_called = true;
  13995. if (!ctx.cert) return false;
  13996. // Matches the IPv6 iPAddress SAN.
  13997. san_matched = ctx.check_hostname("2001:db8::1");
  13998. // A different IPv6 address must not match.
  13999. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14000. // "::1" lives only in the CN, so it must not be accepted.
  14001. cn_ipv6_matched = ctx.check_hostname("::1");
  14002. return true; // Accept for the purpose of this test
  14003. });
  14004. cli.Get("/test");
  14005. ASSERT_TRUE(verify_callback_called)
  14006. << "Verify callback should have been called";
  14007. EXPECT_TRUE(san_matched)
  14008. << "verify_hostname should match an IPv6 iPAddress SAN";
  14009. EXPECT_FALSE(wrong_ipv6_matched)
  14010. << "verify_hostname should not match a non-matching IPv6 address";
  14011. EXPECT_FALSE(cn_ipv6_matched)
  14012. << "An IPv6 host must not be authenticated via the certificate CN";
  14013. }
  14014. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14015. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14016. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14017. using namespace httplib::tls;
  14018. // SANs: DNS:a.zz, IP:42.46.122.122
  14019. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14020. ASSERT_TRUE(svr.is_valid());
  14021. svr.Get("/test", [](const Request &, Response &res) {
  14022. res.set_content("ok", "text/plain");
  14023. });
  14024. auto port = svr.bind_to_any_port(HOST);
  14025. thread t([&]() { svr.listen_after_bind(); });
  14026. auto se = detail::scope_exit([&] {
  14027. svr.stop();
  14028. t.join();
  14029. });
  14030. svr.wait_until_ready();
  14031. bool verify_callback_called = false;
  14032. bool dns_san_matched = false;
  14033. bool ip_san_matched = false;
  14034. bool ip_matched_via_dns_san = true;
  14035. bool dns_matched_via_ip_san = true;
  14036. bool cn_matched_next_to_dns_san = true;
  14037. SSLClient cli(HOST, port);
  14038. cli.enable_server_certificate_verification(true);
  14039. cli.set_ca_cert_path(CA_CERT_FILE);
  14040. cli.set_connection_timeout(5);
  14041. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14042. verify_callback_called = true;
  14043. if (!ctx.cert) return false;
  14044. dns_san_matched = ctx.check_hostname("a.zz");
  14045. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14046. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14047. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14048. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14049. return true; // Accept for the purpose of this test
  14050. });
  14051. cli.Get("/test");
  14052. ASSERT_TRUE(verify_callback_called)
  14053. << "Verify callback should have been called";
  14054. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14055. EXPECT_TRUE(ip_san_matched)
  14056. << "verify_hostname should match an iPAddress SAN";
  14057. EXPECT_FALSE(ip_matched_via_dns_san)
  14058. << "An IP host must not be authenticated via a dNSName SAN";
  14059. EXPECT_FALSE(dns_matched_via_ip_san)
  14060. << "A DNS host must not be authenticated via an iPAddress SAN";
  14061. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14062. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14063. }
  14064. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14065. // "www.*.example.test" names one host and not every host under example.test.
  14066. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14067. using namespace httplib::tls;
  14068. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14069. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14070. ASSERT_TRUE(svr.is_valid());
  14071. svr.Get("/test", [](const Request &, Response &res) {
  14072. res.set_content("ok", "text/plain");
  14073. });
  14074. auto port = svr.bind_to_any_port(HOST);
  14075. thread t([&]() { svr.listen_after_bind(); });
  14076. auto se = detail::scope_exit([&] {
  14077. svr.stop();
  14078. t.join();
  14079. });
  14080. svr.wait_until_ready();
  14081. bool verify_callback_called = false;
  14082. bool leftmost_wildcard_matched = false;
  14083. bool wildcard_spanned_labels = true;
  14084. bool inner_wildcard_matched = true;
  14085. SSLClient cli(HOST, port);
  14086. cli.enable_server_certificate_verification(true);
  14087. cli.set_ca_cert_path(CA_CERT_FILE);
  14088. cli.set_connection_timeout(5);
  14089. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14090. verify_callback_called = true;
  14091. if (!ctx.cert) return false;
  14092. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14093. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14094. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14095. return true; // Accept for the purpose of this test
  14096. });
  14097. cli.Get("/test");
  14098. ASSERT_TRUE(verify_callback_called)
  14099. << "Verify callback should have been called";
  14100. EXPECT_TRUE(leftmost_wildcard_matched)
  14101. << "A leftmost wildcard should match a single label";
  14102. EXPECT_FALSE(wildcard_spanned_labels)
  14103. << "A wildcard label must not match more than one label";
  14104. EXPECT_FALSE(inner_wildcard_matched)
  14105. << "A wildcard outside the leftmost label must not be honoured";
  14106. }
  14107. // sans() must report each SAN entry under its own type.
  14108. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14109. using namespace httplib::tls;
  14110. // SANs: DNS:a.zz, IP:42.46.122.122
  14111. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14112. ASSERT_TRUE(svr.is_valid());
  14113. svr.Get("/test", [](const Request &, Response &res) {
  14114. res.set_content("ok", "text/plain");
  14115. });
  14116. auto port = svr.bind_to_any_port(HOST);
  14117. thread t([&]() { svr.listen_after_bind(); });
  14118. auto se = detail::scope_exit([&] {
  14119. svr.stop();
  14120. t.join();
  14121. });
  14122. svr.wait_until_ready();
  14123. bool verify_callback_called = false;
  14124. std::vector<SanEntry> sans;
  14125. SSLClient cli(HOST, port);
  14126. cli.enable_server_certificate_verification(true);
  14127. cli.set_ca_cert_path(CA_CERT_FILE);
  14128. cli.set_connection_timeout(5);
  14129. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14130. verify_callback_called = true;
  14131. if (!ctx.cert) return false;
  14132. sans = ctx.sans();
  14133. return true; // Accept for the purpose of this test
  14134. });
  14135. cli.Get("/test");
  14136. ASSERT_TRUE(verify_callback_called)
  14137. << "Verify callback should have been called";
  14138. auto has_san = [&](SanType type, const std::string &value) {
  14139. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14140. return san.type == type && san.value == value;
  14141. });
  14142. };
  14143. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14144. << "sans() should report the dNSName SAN";
  14145. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14146. << "sans() should report the iPAddress SAN";
  14147. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14148. << "sans() must not report the dNSName SAN as an address";
  14149. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14150. << "sans() must not report the iPAddress SAN as a DNS name";
  14151. }
  14152. #endif
  14153. // mbedTLS-specific callback constructor test
  14154. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14155. #ifdef CPPHTTPLIB_SSL_ENABLED
  14156. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14158. ASSERT_TRUE(svr.is_valid());
  14159. // Set up a handler to verify client certificate is present
  14160. bool client_cert_verified = false;
  14161. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14162. // Verify that client certificate was provided
  14163. client_cert_verified = true;
  14164. res.set_content("success", "text/plain");
  14165. });
  14166. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14167. auto se = detail::scope_exit([&] {
  14168. svr.stop();
  14169. t.join();
  14170. ASSERT_FALSE(svr.is_running());
  14171. });
  14172. svr.wait_until_ready();
  14173. // Client with certificate
  14174. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14175. cli.enable_server_certificate_verification(false);
  14176. cli.set_connection_timeout(30);
  14177. auto res = cli.Get("/test");
  14178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14179. ASSERT_EQ(StatusCode::OK_200, res->status);
  14180. ASSERT_TRUE(client_cert_verified);
  14181. EXPECT_EQ("success", res->body);
  14182. }
  14183. #endif
  14184. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14185. // backends
  14186. #ifdef CPPHTTPLIB_SSL_ENABLED
  14187. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14188. using namespace httplib::tls;
  14189. // Test that when client CA cert file is provided,
  14190. // the server properly requests and validates client certificates
  14191. // Create a server with client authentication
  14192. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14193. ASSERT_TRUE(svr.is_valid());
  14194. bool handler_called = false;
  14195. svr.Get("/test", [&](const Request &req, Response &res) {
  14196. handler_called = true;
  14197. // Verify that a client certificate was provided
  14198. auto cert = req.peer_cert();
  14199. ASSERT_TRUE(static_cast<bool>(cert));
  14200. // Get the issuer name
  14201. std::string issuer_str = cert.issuer_name();
  14202. ASSERT_FALSE(issuer_str.empty());
  14203. // The client certificate should be issued by our test CA
  14204. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14205. res.set_content("authenticated", "text/plain");
  14206. });
  14207. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14208. auto se = detail::scope_exit([&] {
  14209. svr.stop();
  14210. t.join();
  14211. ASSERT_FALSE(svr.is_running());
  14212. });
  14213. svr.wait_until_ready();
  14214. // Connect with a client certificate issued by the CA
  14215. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14216. cli.enable_server_certificate_verification(false);
  14217. cli.set_connection_timeout(30);
  14218. auto res = cli.Get("/test");
  14219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14220. ASSERT_EQ(StatusCode::OK_200, res->status);
  14221. ASSERT_TRUE(handler_called);
  14222. EXPECT_EQ("authenticated", res->body);
  14223. }
  14224. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14225. using namespace httplib::tls;
  14226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14227. ASSERT_TRUE(svr.is_valid());
  14228. svr.Get("/test", [](const Request &, Response &res) {
  14229. res.set_content("ok", "text/plain");
  14230. });
  14231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14232. auto se = detail::scope_exit([&] {
  14233. svr.stop();
  14234. t.join();
  14235. });
  14236. svr.wait_until_ready();
  14237. SSLClient cli(HOST, PORT);
  14238. cli.enable_server_certificate_verification(false);
  14239. cli.set_connection_timeout(30);
  14240. bool cert_checked = false;
  14241. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14242. if (ctx.cert) {
  14243. auto sans = ctx.sans();
  14244. // Test certificate may or may not have SANs - just verify the API
  14245. // works If SANs exist, verify the types are valid
  14246. for (const auto &san : sans) {
  14247. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14248. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14249. san.type == SanType::OTHER);
  14250. EXPECT_FALSE(san.value.empty());
  14251. }
  14252. cert_checked = true;
  14253. }
  14254. return true;
  14255. });
  14256. auto res = cli.Get("/test");
  14257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14258. EXPECT_TRUE(cert_checked);
  14259. }
  14260. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14261. using namespace httplib::tls;
  14262. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14263. ASSERT_TRUE(svr.is_valid());
  14264. svr.Get("/test", [](const Request &, Response &res) {
  14265. res.set_content("ok", "text/plain");
  14266. });
  14267. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14268. auto se = detail::scope_exit([&] {
  14269. svr.stop();
  14270. t.join();
  14271. });
  14272. svr.wait_until_ready();
  14273. SSLClient cli(HOST, PORT);
  14274. cli.enable_server_certificate_verification(false);
  14275. cli.set_connection_timeout(30);
  14276. bool validity_checked = false;
  14277. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14278. if (ctx.cert) {
  14279. time_t not_before = 0, not_after = 0;
  14280. bool result = ctx.validity(not_before, not_after);
  14281. EXPECT_TRUE(result);
  14282. // Verify that not_before < now < not_after for a valid cert
  14283. time_t now = time(nullptr);
  14284. EXPECT_LT(not_before, now);
  14285. EXPECT_GT(not_after, now);
  14286. validity_checked = true;
  14287. }
  14288. return true;
  14289. });
  14290. auto res = cli.Get("/test");
  14291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14292. EXPECT_TRUE(validity_checked);
  14293. }
  14294. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14295. using namespace httplib::tls;
  14296. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14297. ASSERT_TRUE(svr.is_valid());
  14298. svr.Get("/test", [](const Request &, Response &res) {
  14299. res.set_content("ok", "text/plain");
  14300. });
  14301. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14302. auto se = detail::scope_exit([&] {
  14303. svr.stop();
  14304. t.join();
  14305. });
  14306. svr.wait_until_ready();
  14307. SSLClient cli(HOST, PORT);
  14308. cli.enable_server_certificate_verification(false);
  14309. cli.set_connection_timeout(30);
  14310. bool serial_checked = false;
  14311. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14312. if (ctx.cert) {
  14313. std::string serial = ctx.serial();
  14314. EXPECT_FALSE(serial.empty());
  14315. // Serial should be a hex string
  14316. for (char c : serial) {
  14317. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14318. (c >= 'a' && c <= 'f'));
  14319. }
  14320. serial_checked = true;
  14321. }
  14322. return true;
  14323. });
  14324. auto res = cli.Get("/test");
  14325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14326. EXPECT_TRUE(serial_checked);
  14327. }
  14328. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14329. // Test 1: Valid CA file - no error should be recorded
  14330. {
  14331. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14332. CLIENT_CA_CERT_FILE);
  14333. ASSERT_TRUE(svr.is_valid());
  14334. // With valid setup, last_ssl_error should be 0
  14335. EXPECT_EQ(0, svr.ssl_last_error());
  14336. }
  14337. // Test 2: Invalid CA file content
  14338. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14339. {
  14340. // Create a temporary file with completely invalid content
  14341. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14342. {
  14343. std::ofstream ofs(temp_invalid_ca);
  14344. ofs << "This is not a certificate file at all\n";
  14345. ofs << "Just plain text content\n";
  14346. }
  14347. // Create server with invalid CA file
  14348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14349. // Clean up temporary file
  14350. std::remove(temp_invalid_ca);
  14351. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14352. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14353. // Note: SSL_CTX_load_verify_locations typically fails first,
  14354. // but our error handling code path is still exercised
  14355. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14356. }
  14357. }
  14358. TEST(VerifyCallbackTest, VerifyContextFields) {
  14359. using namespace httplib::tls;
  14360. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14361. ASSERT_TRUE(svr.is_valid());
  14362. svr.Get("/test", [](const Request &, Response &res) {
  14363. res.set_content("ok", "text/plain");
  14364. });
  14365. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14366. auto se = detail::scope_exit([&] {
  14367. svr.stop();
  14368. t.join();
  14369. });
  14370. svr.wait_until_ready();
  14371. SSLClient cli(HOST, PORT);
  14372. cli.enable_server_certificate_verification(false);
  14373. cli.set_connection_timeout(30);
  14374. int callback_count = 0;
  14375. bool saw_leaf_cert = false;
  14376. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14377. if (ctx.cert) {
  14378. callback_count++;
  14379. // We should see at least one certificate (the leaf)
  14380. std::string cn = ctx.subject_cn();
  14381. if (!cn.empty()) { saw_leaf_cert = true; }
  14382. // Verify context fields are populated
  14383. EXPECT_NE(ctx.session, nullptr);
  14384. EXPECT_GE(ctx.depth, 0);
  14385. }
  14386. return true;
  14387. });
  14388. auto res = cli.Get("/test");
  14389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14390. EXPECT_GT(callback_count, 0);
  14391. EXPECT_TRUE(saw_leaf_cert);
  14392. }
  14393. // A verifier that accepts runs alongside the built-in verification, and is the
  14394. // only check once that is turned off.
  14395. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14396. using namespace httplib::tls;
  14397. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14398. ASSERT_TRUE(svr.is_valid());
  14399. svr.Get("/test", [](const Request &, Response &res) {
  14400. res.set_content("ok", "text/plain");
  14401. });
  14402. auto port = svr.bind_to_any_port(HOST);
  14403. thread t([&]() { svr.listen_after_bind(); });
  14404. auto se = detail::scope_exit([&] {
  14405. svr.stop();
  14406. t.join();
  14407. });
  14408. svr.wait_until_ready();
  14409. SSLClient cli(HOST, port);
  14410. cli.enable_server_hostname_verification(false);
  14411. auto calls = 0;
  14412. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14413. calls++;
  14414. return true;
  14415. });
  14416. // cert.pem is not trusted
  14417. auto res = cli.Get("/test");
  14418. ASSERT_FALSE(res);
  14419. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14420. EXPECT_GT(calls, 0);
  14421. cli.enable_server_certificate_verification(false);
  14422. res = cli.Get("/test");
  14423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14424. EXPECT_EQ("ok", res->body);
  14425. }
  14426. // A verifier belongs to the client that set it, not to the thread that set it.
  14427. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14428. using namespace httplib::tls;
  14429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14430. ASSERT_TRUE(svr.is_valid());
  14431. svr.Get("/test", [](const Request &, Response &res) {
  14432. res.set_content("ok", "text/plain");
  14433. });
  14434. auto port = svr.bind_to_any_port(HOST);
  14435. thread t([&]() { svr.listen_after_bind(); });
  14436. auto se = detail::scope_exit([&] {
  14437. svr.stop();
  14438. t.join();
  14439. });
  14440. svr.wait_until_ready();
  14441. auto rejecting_calls = 0;
  14442. SSLClient rejecting(HOST, port);
  14443. rejecting.enable_server_certificate_verification(false);
  14444. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14445. rejecting_calls++;
  14446. return false;
  14447. });
  14448. auto accepting_calls = 0;
  14449. SSLClient accepting(HOST, port);
  14450. accepting.enable_server_certificate_verification(false);
  14451. // Set on another thread than the requests below.
  14452. thread([&]() {
  14453. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14454. accepting_calls++;
  14455. return true;
  14456. });
  14457. }).join();
  14458. // Requested on another thread than the verifier was set on.
  14459. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14460. EXPECT_GT(rejecting_calls, 0);
  14461. auto res = accepting.Get("/test");
  14462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14463. EXPECT_GT(accepting_calls, 0);
  14464. }
  14465. // A verifier replaced while a handshake runs it lives until it returns.
  14466. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14467. using namespace httplib::tls;
  14468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14469. ASSERT_TRUE(svr.is_valid());
  14470. svr.Get("/test", [](const Request &, Response &res) {
  14471. res.set_content("ok", "text/plain");
  14472. });
  14473. auto port = svr.bind_to_any_port(HOST);
  14474. thread t([&]() { svr.listen_after_bind(); });
  14475. auto se = detail::scope_exit([&] {
  14476. svr.stop();
  14477. t.join();
  14478. });
  14479. svr.wait_until_ready();
  14480. SSLClient cli(HOST, port);
  14481. cli.enable_server_certificate_verification(false);
  14482. std::promise<void> entered;
  14483. std::promise<void> replaced;
  14484. auto replaced_future = replaced.get_future();
  14485. auto first_call = true;
  14486. // Long enough to live on the heap
  14487. std::string expected(64, 'v');
  14488. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14489. if (first_call) {
  14490. first_call = false;
  14491. entered.set_value();
  14492. replaced_future.wait();
  14493. }
  14494. return expected == std::string(64, 'v');
  14495. });
  14496. thread request([&]() {
  14497. auto res = cli.Get("/test");
  14498. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14499. });
  14500. entered.get_future().wait();
  14501. cli.set_server_certificate_verifier(
  14502. [](const VerifyContext &) { return true; });
  14503. replaced.set_value();
  14504. request.join();
  14505. }
  14506. // VerifyContext::session is the same handle the other tls:: functions take.
  14507. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14508. using namespace httplib::tls;
  14509. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14510. ASSERT_TRUE(svr.is_valid());
  14511. svr.Get("/test", [](const Request &, Response &res) {
  14512. res.set_content("ok", "text/plain");
  14513. });
  14514. auto port = svr.bind_to_any_port(HOST);
  14515. thread t([&]() { svr.listen_after_bind(); });
  14516. auto se = detail::scope_exit([&] {
  14517. svr.stop();
  14518. t.join();
  14519. });
  14520. svr.wait_until_ready();
  14521. SSLClient cli(HOST, port);
  14522. cli.enable_server_certificate_verification(false);
  14523. session_t verifier_session = nullptr;
  14524. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14525. verifier_session = ctx.session;
  14526. return true;
  14527. });
  14528. session_t session_verifier_session = nullptr;
  14529. cli.set_session_verifier([&](session_t session) {
  14530. session_verifier_session = session;
  14531. return SSLVerifierResponse::NoDecisionMade;
  14532. });
  14533. auto res = cli.Get("/test");
  14534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14535. EXPECT_NE(nullptr, verifier_session);
  14536. EXPECT_EQ(session_verifier_session, verifier_session);
  14537. }
  14538. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14539. using httplib::tls::TlsError;
  14540. // Test that verify_error_to_string returns empty for success
  14541. std::string success_str = TlsError::verify_error_to_string(0);
  14542. EXPECT_TRUE(success_str.empty());
  14543. // Test that verify_error_to_string returns non-empty for error codes
  14544. // Using a common error code (certificate expired)
  14545. std::string error_str =
  14546. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14547. EXPECT_FALSE(error_str.empty());
  14548. }
  14549. TEST(SessionVerifierTest, CertificateAccepted) {
  14550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14551. ASSERT_TRUE(svr.is_valid());
  14552. svr.Get("/test", [](const Request &, Response &res) {
  14553. res.set_content("ok", "text/plain");
  14554. });
  14555. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14556. auto se = detail::scope_exit([&] {
  14557. svr.stop();
  14558. t.join();
  14559. });
  14560. svr.wait_until_ready();
  14561. SSLClient cli(HOST, PORT);
  14562. cli.enable_server_certificate_verification(false);
  14563. cli.set_connection_timeout(30);
  14564. bool callback_called = false;
  14565. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14566. EXPECT_NE(session, nullptr);
  14567. callback_called = true;
  14568. return SSLVerifierResponse::CertificateAccepted;
  14569. });
  14570. auto res = cli.Get("/test");
  14571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14572. EXPECT_EQ(200, res->status);
  14573. EXPECT_TRUE(callback_called);
  14574. }
  14575. TEST(SessionVerifierTest, CertificateRejected) {
  14576. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14577. ASSERT_TRUE(svr.is_valid());
  14578. svr.Get("/test", [](const Request &, Response &res) {
  14579. res.set_content("ok", "text/plain");
  14580. });
  14581. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14582. auto se = detail::scope_exit([&] {
  14583. svr.stop();
  14584. t.join();
  14585. });
  14586. svr.wait_until_ready();
  14587. SSLClient cli(HOST, PORT);
  14588. cli.enable_server_certificate_verification(false);
  14589. cli.set_connection_timeout(30);
  14590. bool callback_called = false;
  14591. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14592. EXPECT_NE(session, nullptr);
  14593. callback_called = true;
  14594. return SSLVerifierResponse::CertificateRejected;
  14595. });
  14596. auto res = cli.Get("/test");
  14597. EXPECT_FALSE(res);
  14598. EXPECT_TRUE(callback_called);
  14599. }
  14600. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14602. ASSERT_TRUE(svr.is_valid());
  14603. svr.Get("/test", [](const Request &, Response &res) {
  14604. res.set_content("ok", "text/plain");
  14605. });
  14606. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14607. auto se = detail::scope_exit([&] {
  14608. svr.stop();
  14609. t.join();
  14610. });
  14611. svr.wait_until_ready();
  14612. // NoDecisionMade with verification disabled should succeed (no default check)
  14613. SSLClient cli(HOST, PORT);
  14614. cli.enable_server_certificate_verification(false);
  14615. cli.set_connection_timeout(30);
  14616. bool callback_called = false;
  14617. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14618. EXPECT_NE(session, nullptr);
  14619. callback_called = true;
  14620. return SSLVerifierResponse::NoDecisionMade;
  14621. });
  14622. auto res = cli.Get("/test");
  14623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14624. EXPECT_EQ(200, res->status);
  14625. EXPECT_TRUE(callback_called);
  14626. }
  14627. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14629. ASSERT_TRUE(svr.is_valid());
  14630. svr.Get("/test", [](const Request &, Response &res) {
  14631. res.set_content("ok", "text/plain");
  14632. });
  14633. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14634. auto se = detail::scope_exit([&] {
  14635. svr.stop();
  14636. t.join();
  14637. });
  14638. svr.wait_until_ready();
  14639. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14640. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14641. // so we only check that the request fails, not whether the callback was
  14642. // called.
  14643. SSLClient cli(HOST, PORT);
  14644. cli.enable_server_certificate_verification(true);
  14645. cli.set_connection_timeout(30);
  14646. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14647. EXPECT_NE(session, nullptr);
  14648. return SSLVerifierResponse::NoDecisionMade;
  14649. });
  14650. auto res = cli.Get("/test");
  14651. EXPECT_FALSE(res);
  14652. }
  14653. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14654. // Test SSL server using PemMemory constructor with client CA certificates
  14655. // Read PEM files
  14656. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14657. read_file(SERVER_CERT_FILE, server_cert_pem);
  14658. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14659. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14660. // Create SSLServer with PemMemory constructor including client CA
  14661. SSLServer::PemMemory server_pem = {
  14662. server_cert_pem.c_str(),
  14663. server_cert_pem.size(),
  14664. server_key_pem.c_str(),
  14665. server_key_pem.size(),
  14666. client_ca_pem.c_str(),
  14667. client_ca_pem.size(),
  14668. nullptr // no password for server key
  14669. };
  14670. SSLServer svr(server_pem);
  14671. ASSERT_TRUE(svr.is_valid());
  14672. // No SSL error should be recorded for valid setup
  14673. EXPECT_EQ(0, svr.ssl_last_error());
  14674. // Set up server endpoints
  14675. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14676. res.set_content("ok", "text/plain");
  14677. });
  14678. // Start server in a thread
  14679. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14680. svr.wait_until_ready();
  14681. // Connect with client certificate (using constructor with paths)
  14682. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14683. cli.enable_server_certificate_verification(false);
  14684. auto res = cli.Get("/test-pem-ca");
  14685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14686. EXPECT_EQ(200, res->status);
  14687. EXPECT_EQ("ok", res->body);
  14688. svr.stop();
  14689. server_thread.join();
  14690. }
  14691. #endif
  14692. #ifdef _WIN32
  14693. TEST(CleanupTest, WSACleanup) {
  14694. int ret = WSACleanup();
  14695. ASSERT_EQ(0, ret);
  14696. }
  14697. #endif
  14698. #ifndef CPPHTTPLIB_SSL_ENABLED
  14699. TEST(NoSSLSupport, SimpleInterface) {
  14700. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14701. }
  14702. #endif
  14703. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14704. TEST(InvalidScheme, SimpleInterface) {
  14705. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14706. }
  14707. #endif
  14708. TEST(NoScheme, SimpleInterface) {
  14709. Client cli("yahoo.com:80");
  14710. ASSERT_TRUE(cli.is_valid());
  14711. }
  14712. TEST(SendAPI, SimpleInterface_Online) {
  14713. Client cli("http://yahoo.com");
  14714. Request req;
  14715. req.method = "GET";
  14716. req.path = "/";
  14717. auto res = cli.send(req);
  14718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14719. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14720. }
  14721. TEST(SendAPI, WithParamsInRequest) {
  14722. Server svr;
  14723. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14724. EXPECT_TRUE(req.has_param("test"));
  14725. EXPECT_EQ("test_value", req.get_param_value("test"));
  14726. });
  14727. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14728. auto se = detail::scope_exit([&] {
  14729. svr.stop();
  14730. t.join();
  14731. ASSERT_FALSE(svr.is_running());
  14732. });
  14733. svr.wait_until_ready();
  14734. Client cli(HOST, PORT);
  14735. {
  14736. Request req;
  14737. req.method = "GET";
  14738. req.path = "/";
  14739. req.params.emplace("test", "test_value");
  14740. auto res = cli.send(req);
  14741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14742. }
  14743. {
  14744. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14746. }
  14747. }
  14748. TEST(ClientImplMethods, GetSocketTest) {
  14749. httplib::Server svr;
  14750. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14751. res.status = StatusCode::OK_200;
  14752. });
  14753. auto port = svr.bind_to_any_port("127.0.0.1");
  14754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14755. auto se = detail::scope_exit([&] {
  14756. svr.stop();
  14757. thread.join();
  14758. ASSERT_FALSE(svr.is_running());
  14759. });
  14760. svr.wait_until_ready();
  14761. {
  14762. httplib::Client cli("127.0.0.1", port);
  14763. cli.set_keep_alive(true);
  14764. // Use the behavior of cpp-httplib of opening the connection
  14765. // only when the first request happens. If that changes,
  14766. // this test would be obsolete.
  14767. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14768. // This also implicitly tests the server. But other tests would fail much
  14769. // earlier than this one to be considered.
  14770. auto res = cli.Get("/");
  14771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14772. EXPECT_EQ(StatusCode::OK_200, res->status);
  14773. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14774. }
  14775. }
  14776. #ifdef CPPHTTPLIB_SSL_ENABLED
  14777. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14778. Client cli("http://yahoo.com");
  14779. auto res = cli.Get("/");
  14780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14781. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14782. cli.set_follow_location(true);
  14783. res = cli.Get("/");
  14784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14785. EXPECT_EQ(StatusCode::OK_200, res->status);
  14786. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14787. }
  14788. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14789. Client cli("https://yahoo.com");
  14790. auto res = cli.Get("/");
  14791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14792. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14793. cli.set_follow_location(true);
  14794. res = cli.Get("/");
  14795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14796. EXPECT_EQ(StatusCode::OK_200, res->status);
  14797. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14798. }
  14799. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14800. Client cli("https://yahoo.com");
  14801. auto res = cli.Get("/");
  14802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14803. ASSERT_FALSE(!res);
  14804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14805. ASSERT_FALSE(res == nullptr);
  14806. ASSERT_TRUE(res != nullptr);
  14807. EXPECT_EQ(Error::Success, res.error());
  14808. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14809. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14810. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14811. cli.set_follow_location(true);
  14812. res = cli.Get("/");
  14813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14814. EXPECT_EQ(Error::Success, res.error());
  14815. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14816. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14817. EXPECT_EQ(StatusCode::OK_200, res->status);
  14818. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14819. }
  14820. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14821. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14822. Client cli("https://cdnjs.cloudflare.com");
  14823. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14824. Headers{{"Accept-Encoding", "br"}});
  14825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14826. EXPECT_EQ(StatusCode::OK_200, res->status);
  14827. EXPECT_EQ(287630U, res->body.size());
  14828. EXPECT_EQ("application/javascript; charset=utf-8",
  14829. res->get_header_value("Content-Type"));
  14830. }
  14831. #endif
  14832. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14833. #undef REDIR_HOST // Silence compiler warning
  14834. #define REDIR_HOST "https://httpbingo.org"
  14835. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14836. Client cli(REDIR_HOST);
  14837. cli.set_follow_location(true);
  14838. auto res =
  14839. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14841. EXPECT_EQ(StatusCode::OK_200, res->status);
  14842. }
  14843. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14844. Client cli(REDIR_HOST);
  14845. cli.set_follow_location(true);
  14846. Params params;
  14847. params.emplace("url", "http://example.com");
  14848. params.emplace("status_code", "302");
  14849. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14851. EXPECT_EQ(StatusCode::OK_200, res->status);
  14852. }
  14853. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14854. Client cli(REDIR_HOST);
  14855. cli.set_follow_location(true);
  14856. Params params;
  14857. params.emplace("url", "http://example.com");
  14858. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14860. EXPECT_EQ(StatusCode::OK_200, res->status);
  14861. }
  14862. TEST(HttpToHttpsRedirectTest, CertFile) {
  14863. auto ssl_port = PORT + 1;
  14864. Server svr;
  14865. ASSERT_TRUE(svr.is_valid());
  14866. svr.Get("/index", [&](const Request &, Response &res) {
  14867. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14868. "/index");
  14869. svr.stop();
  14870. });
  14871. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14872. ASSERT_TRUE(ssl_svr.is_valid());
  14873. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14874. res.set_content("test", "text/plain");
  14875. ssl_svr.stop();
  14876. });
  14877. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14878. thread t2 =
  14879. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14880. auto se = detail::scope_exit([&] {
  14881. t2.join();
  14882. t.join();
  14883. ASSERT_FALSE(svr.is_running());
  14884. });
  14885. svr.wait_until_ready();
  14886. ssl_svr.wait_until_ready();
  14887. Client cli("127.0.0.1", PORT);
  14888. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14889. cli.enable_server_certificate_verification(true);
  14890. cli.set_follow_location(true);
  14891. cli.set_connection_timeout(30);
  14892. auto res = cli.Get("/index");
  14893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14894. ASSERT_EQ(StatusCode::OK_200, res->status);
  14895. }
  14896. TEST(SSLClientRedirectTest, CertFile) {
  14897. auto ssl_port = PORT + 1;
  14898. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14899. ASSERT_TRUE(ssl_svr1.is_valid());
  14900. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14901. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14902. "/index");
  14903. ssl_svr1.stop();
  14904. });
  14905. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14906. ASSERT_TRUE(ssl_svr2.is_valid());
  14907. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14908. res.set_content("test", "text/plain");
  14909. ssl_svr2.stop();
  14910. });
  14911. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14912. thread t2 =
  14913. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14914. auto se = detail::scope_exit([&] {
  14915. t2.join();
  14916. t.join();
  14917. ASSERT_FALSE(ssl_svr1.is_running());
  14918. });
  14919. ssl_svr1.wait_until_ready();
  14920. ssl_svr2.wait_until_ready();
  14921. SSLClient cli("127.0.0.1", PORT);
  14922. std::string cert;
  14923. read_file(SERVER_CERT2_FILE, cert);
  14924. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14925. cli.enable_server_certificate_verification(true);
  14926. cli.set_follow_location(true);
  14927. cli.set_connection_timeout(30);
  14928. auto res = cli.Get("/index");
  14929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14930. ASSERT_EQ(StatusCode::OK_200, res->status);
  14931. }
  14932. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14933. // another port, so the client follows it with a new client.
  14934. static Result GetThroughTlsRedirectToDifferentPort(
  14935. const std::function<void(SSLClient &)> &setup,
  14936. const char *target_cert = SERVER_CERT2_FILE,
  14937. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14938. auto ssl_port = PORT + 1;
  14939. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14940. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14941. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14942. "/index");
  14943. });
  14944. SSLServer ssl_svr2(target_cert, target_key);
  14945. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14946. res.set_content("test", "text/plain");
  14947. });
  14948. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14949. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14950. auto se = detail::scope_exit([&] {
  14951. ssl_svr2.stop();
  14952. ssl_svr1.stop();
  14953. t2.join();
  14954. t.join();
  14955. });
  14956. ssl_svr1.wait_until_ready();
  14957. ssl_svr2.wait_until_ready();
  14958. SSLClient cli("127.0.0.1", PORT);
  14959. cli.set_follow_location(true);
  14960. cli.set_connection_timeout(30);
  14961. setup(cli);
  14962. return cli.Get("/index");
  14963. }
  14964. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14965. auto calls = 0;
  14966. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14967. cli.enable_server_certificate_verification(false);
  14968. // Accept the first server only.
  14969. cli.set_session_verifier([&](tls::session_t) {
  14970. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14971. : SSLVerifierResponse::CertificateRejected;
  14972. });
  14973. });
  14974. ASSERT_FALSE(res);
  14975. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14976. EXPECT_EQ(2, calls);
  14977. }
  14978. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14979. std::string pinned;
  14980. auto res = GetThroughTlsRedirectToDifferentPort(
  14981. [&](SSLClient &cli) {
  14982. cli.enable_server_certificate_verification(false);
  14983. // Pin the first certificate seen.
  14984. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14985. if (pinned.empty()) { pinned = ctx.serial(); }
  14986. return ctx.serial() == pinned;
  14987. });
  14988. },
  14989. // A certificate other than the first server's.
  14990. SERVER_CERT_FILE);
  14991. EXPECT_FALSE(res);
  14992. EXPECT_FALSE(pinned.empty());
  14993. }
  14994. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14995. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14996. std::string cert;
  14997. read_file(SERVER_CERT2_FILE, cert);
  14998. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14999. });
  15000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15001. EXPECT_EQ(StatusCode::OK_200, res->status);
  15002. }
  15003. // The target's certificate is signed by the root CA, which the first server's
  15004. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15005. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15006. auto res = GetThroughTlsRedirectToDifferentPort(
  15007. [](SSLClient &cli) {
  15008. std::string root_ca, cert;
  15009. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15010. read_file(SERVER_CERT2_FILE, cert);
  15011. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15012. cli.load_ca_cert_store(cert.data(), cert.size());
  15013. cli.enable_server_hostname_verification(false);
  15014. },
  15015. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15017. EXPECT_EQ(StatusCode::OK_200, res->status);
  15018. }
  15019. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15020. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15021. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15022. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15023. auto res = GetThroughTlsRedirectToDifferentPort(
  15024. [](SSLClient &cli) {
  15025. std::string root_ca, cert;
  15026. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15027. read_file(SERVER_CERT2_FILE, cert);
  15028. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15029. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15030. cli.enable_server_hostname_verification(false);
  15031. },
  15032. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15033. ASSERT_FALSE(res);
  15034. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15035. }
  15036. #endif
  15037. #endif
  15038. #ifdef CPPHTTPLIB_SSL_ENABLED
  15039. // Test that set_ca_cert_store() skips system certs (consistent with
  15040. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15041. // should be trusted - system certs should NOT be loaded.
  15042. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15043. // Load a specific cert that is NOT a system CA cert
  15044. std::string cert;
  15045. read_file(SERVER_CERT2_FILE, cert);
  15046. SSLClient cli("google.com");
  15047. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15048. cli.enable_server_certificate_verification(true);
  15049. // This should FAIL because:
  15050. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15051. // 2. System certs should NOT be loaded when custom store is set
  15052. // If system certs WERE loaded, this would succeed
  15053. auto res = cli.Get("/");
  15054. ASSERT_FALSE(res);
  15055. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15056. }
  15057. // Same as above, but through the native store handle path. Regression test:
  15058. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15059. // merged system certs into the user-provided store.
  15060. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15061. std::string cert;
  15062. read_file(SERVER_CERT2_FILE, cert);
  15063. SSLClient cli("google.com");
  15064. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15065. cli.enable_server_certificate_verification(true);
  15066. auto res = cli.Get("/");
  15067. ASSERT_FALSE(res);
  15068. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15069. }
  15070. // A custom store set via the native handle must still verify a server whose
  15071. // cert it does contain.
  15072. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15073. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15074. ASSERT_TRUE(svr.is_valid());
  15075. svr.Get("/test", [&](const Request &, Response &res) {
  15076. res.set_content("test", "text/plain");
  15077. });
  15078. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15079. auto se = detail::scope_exit([&] {
  15080. svr.stop();
  15081. t.join();
  15082. ASSERT_FALSE(svr.is_running());
  15083. });
  15084. svr.wait_until_ready();
  15085. SSLClient cli("127.0.0.1", PORT);
  15086. std::string cert;
  15087. read_file(SERVER_CERT2_FILE, cert);
  15088. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15089. cli.enable_server_certificate_verification(true);
  15090. cli.set_connection_timeout(30);
  15091. auto res = cli.Get("/test");
  15092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15093. ASSERT_EQ(StatusCode::OK_200, res->status);
  15094. }
  15095. // CA certs loaded through the universal Client must be transferred to the
  15096. // client created internally for following an HTTPS redirect. Regression test:
  15097. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15098. // the CA data for redirect transfer.
  15099. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15100. auto ssl_port = PORT + 1;
  15101. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15102. ASSERT_TRUE(ssl_svr1.is_valid());
  15103. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15104. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15105. "/index");
  15106. });
  15107. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15108. ASSERT_TRUE(ssl_svr2.is_valid());
  15109. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15110. res.set_content("test", "text/plain");
  15111. });
  15112. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15113. thread t2 =
  15114. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15115. auto se = detail::scope_exit([&] {
  15116. ssl_svr2.stop();
  15117. ssl_svr1.stop();
  15118. t2.join();
  15119. t.join();
  15120. ASSERT_FALSE(ssl_svr1.is_running());
  15121. });
  15122. ssl_svr1.wait_until_ready();
  15123. ssl_svr2.wait_until_ready();
  15124. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15125. std::string cert;
  15126. read_file(SERVER_CERT2_FILE, cert);
  15127. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15128. cli.enable_server_certificate_verification(true);
  15129. cli.set_follow_location(true);
  15130. cli.set_connection_timeout(30);
  15131. auto res = cli.Get("/index");
  15132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15133. ASSERT_EQ(StatusCode::OK_200, res->status);
  15134. }
  15135. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15136. // so a host signed by a system CA verifies even though a custom CA is set
  15137. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15138. std::string cert;
  15139. read_file(SERVER_CERT2_FILE, cert);
  15140. SSLClient cli("google.com");
  15141. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15142. cli.enable_system_ca(true);
  15143. cli.enable_server_certificate_verification(true);
  15144. auto res = cli.Get("/");
  15145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15146. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15147. }
  15148. // The custom CA remains effective when combined with the system CA
  15149. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15150. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15151. ASSERT_TRUE(svr.is_valid());
  15152. svr.Get("/test", [&](const Request &, Response &res) {
  15153. res.set_content("test", "text/plain");
  15154. });
  15155. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15156. auto se = detail::scope_exit([&] {
  15157. svr.stop();
  15158. t.join();
  15159. ASSERT_FALSE(svr.is_running());
  15160. });
  15161. svr.wait_until_ready();
  15162. SSLClient cli("127.0.0.1", PORT);
  15163. std::string cert;
  15164. read_file(SERVER_CERT2_FILE, cert);
  15165. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15166. cli.enable_system_ca(true);
  15167. cli.enable_server_certificate_verification(true);
  15168. cli.set_connection_timeout(30);
  15169. auto res = cli.Get("/test");
  15170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15171. ASSERT_EQ(StatusCode::OK_200, res->status);
  15172. }
  15173. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15174. // skip chain verification entirely (only the certificate identity was
  15175. // checked), so a server presenting an untrusted certificate with a matching
  15176. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15177. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15178. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15179. ASSERT_TRUE(svr.is_valid());
  15180. svr.Get("/test", [&](const Request &, Response &res) {
  15181. res.set_content("test", "text/plain");
  15182. });
  15183. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15184. auto se = detail::scope_exit([&] {
  15185. svr.stop();
  15186. t.join();
  15187. ASSERT_FALSE(svr.is_running());
  15188. });
  15189. svr.wait_until_ready();
  15190. SSLClient cli("127.0.0.1", PORT);
  15191. std::string cert;
  15192. // A trusted CA that did not sign the server certificate. The server cert
  15193. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15194. // this connection.
  15195. read_file(CLIENT_CA_CERT_FILE, cert);
  15196. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15197. cli.enable_server_certificate_verification(true);
  15198. cli.set_connection_timeout(30);
  15199. auto res = cli.Get("/test");
  15200. ASSERT_FALSE(res);
  15201. }
  15202. // enable_system_ca(false) prevents system CA loading entirely
  15203. TEST(SSLClientTest, DisableSystemCa_Online) {
  15204. SSLClient cli("google.com");
  15205. cli.enable_system_ca(false);
  15206. cli.enable_server_certificate_verification(true);
  15207. auto res = cli.Get("/");
  15208. ASSERT_FALSE(res);
  15209. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15210. // itself when the CA chain is empty
  15211. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15212. res.error() == Error::SSLConnection);
  15213. }
  15214. // The universal Client forwards enable_system_ca()
  15215. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15216. std::string cert;
  15217. read_file(SERVER_CERT2_FILE, cert);
  15218. Client cli("https://google.com");
  15219. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15220. cli.enable_system_ca(true);
  15221. cli.enable_server_certificate_verification(true);
  15222. auto res = cli.Get("/");
  15223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15224. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15225. }
  15226. // The system CA policy must carry over to the client created internally for
  15227. // following a cross-host HTTPS redirect
  15228. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15229. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15230. ASSERT_TRUE(svr.is_valid());
  15231. svr.Get("/index", [&](const Request &, Response &res) {
  15232. res.set_redirect("https://www.google.com/");
  15233. });
  15234. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15235. auto se = detail::scope_exit([&] {
  15236. svr.stop();
  15237. t.join();
  15238. ASSERT_FALSE(svr.is_running());
  15239. });
  15240. svr.wait_until_ready();
  15241. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15242. std::string cert;
  15243. read_file(SERVER_CERT2_FILE, cert);
  15244. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15245. cli.enable_system_ca(true);
  15246. cli.enable_server_certificate_verification(true);
  15247. cli.set_follow_location(true);
  15248. cli.set_connection_timeout(30);
  15249. // Receiving any response proves the redirect client completed the TLS
  15250. // handshake with a system-CA-signed host
  15251. auto res = cli.Get("/index");
  15252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15253. }
  15254. TEST(MultipartFormDataTest, LargeData) {
  15255. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15256. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15257. const ContentReader &content_reader) {
  15258. if (req.is_multipart_form_data()) {
  15259. std::vector<FormData> items;
  15260. content_reader(
  15261. [&](const FormData &file) {
  15262. items.push_back(file);
  15263. return true;
  15264. },
  15265. [&](const char *data, size_t data_length) {
  15266. items.back().content.append(data, data_length);
  15267. return true;
  15268. });
  15269. EXPECT_TRUE(std::string(items[0].name) == "document");
  15270. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15271. EXPECT_TRUE(items[0].filename == "2MB_data");
  15272. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15273. EXPECT_TRUE(items[1].name == "hello");
  15274. EXPECT_TRUE(items[1].content == "world");
  15275. EXPECT_TRUE(items[1].filename == "");
  15276. EXPECT_TRUE(items[1].content_type == "");
  15277. } else {
  15278. std::string body;
  15279. content_reader([&](const char *data, size_t data_length) {
  15280. body.append(data, data_length);
  15281. return true;
  15282. });
  15283. }
  15284. });
  15285. auto port = svr.bind_to_any_port(HOST);
  15286. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15287. auto se = detail::scope_exit([&] {
  15288. svr.stop();
  15289. t.join();
  15290. ASSERT_FALSE(svr.is_running());
  15291. });
  15292. svr.wait_until_ready();
  15293. {
  15294. std::string data(1024 * 1024 * 2, '.');
  15295. std::stringstream buffer;
  15296. buffer << data;
  15297. SSLClient cli(HOST, port);
  15298. cli.enable_server_certificate_verification(false);
  15299. UploadFormDataItems items{
  15300. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15301. {"hello", "world", "", ""},
  15302. };
  15303. auto res = cli.Post("/post", items);
  15304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15305. ASSERT_EQ(StatusCode::OK_200, res->status);
  15306. }
  15307. }
  15308. TEST(MultipartFormDataTest, DataProviderItems) {
  15309. std::random_device seed_gen;
  15310. std::mt19937 random(seed_gen());
  15311. std::string rand1;
  15312. rand1.resize(1000);
  15313. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15314. std::string rand2;
  15315. rand2.resize(3000);
  15316. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15317. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15318. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15319. const ContentReader &content_reader) {
  15320. ASSERT_FALSE(req.is_multipart_form_data());
  15321. std::string body;
  15322. content_reader([&](const char *data, size_t data_length) {
  15323. body.append(data, data_length);
  15324. return true;
  15325. });
  15326. EXPECT_EQ(body, "");
  15327. });
  15328. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15329. const ContentReader &content_reader) {
  15330. ASSERT_TRUE(req.is_multipart_form_data());
  15331. std::vector<FormData> items;
  15332. content_reader(
  15333. [&](const FormData &file) {
  15334. items.push_back(file);
  15335. return true;
  15336. },
  15337. [&](const char *data, size_t data_length) {
  15338. items.back().content.append(data, data_length);
  15339. return true;
  15340. });
  15341. ASSERT_TRUE(items.size() == 2);
  15342. EXPECT_EQ(std::string(items[0].name), "name1");
  15343. EXPECT_EQ(items[0].content, "Testing123");
  15344. EXPECT_EQ(items[0].filename, "filename1");
  15345. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15346. EXPECT_EQ(items[1].name, "name2");
  15347. EXPECT_EQ(items[1].content, "Testing456");
  15348. EXPECT_EQ(items[1].filename, "");
  15349. EXPECT_EQ(items[1].content_type, "");
  15350. });
  15351. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15352. const ContentReader &content_reader) {
  15353. ASSERT_TRUE(req.is_multipart_form_data());
  15354. std::vector<FormData> items;
  15355. content_reader(
  15356. [&](const FormData &file) {
  15357. items.push_back(file);
  15358. return true;
  15359. },
  15360. [&](const char *data, size_t data_length) {
  15361. items.back().content.append(data, data_length);
  15362. return true;
  15363. });
  15364. ASSERT_TRUE(items.size() == 2);
  15365. EXPECT_EQ(items[0].name, "name3");
  15366. EXPECT_EQ(items[0].content, rand1);
  15367. EXPECT_EQ(items[0].filename, "filename3");
  15368. EXPECT_EQ(items[0].content_type, "");
  15369. EXPECT_EQ(items[1].name, "name4");
  15370. EXPECT_EQ(items[1].content, rand2);
  15371. EXPECT_EQ(items[1].filename, "filename4");
  15372. EXPECT_EQ(items[1].content_type, "");
  15373. });
  15374. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15375. const ContentReader &content_reader) {
  15376. ASSERT_TRUE(req.is_multipart_form_data());
  15377. std::vector<FormData> items;
  15378. content_reader(
  15379. [&](const FormData &file) {
  15380. items.push_back(file);
  15381. return true;
  15382. },
  15383. [&](const char *data, size_t data_length) {
  15384. items.back().content.append(data, data_length);
  15385. return true;
  15386. });
  15387. ASSERT_TRUE(items.size() == 4);
  15388. EXPECT_EQ(std::string(items[0].name), "name1");
  15389. EXPECT_EQ(items[0].content, "Testing123");
  15390. EXPECT_EQ(items[0].filename, "filename1");
  15391. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15392. EXPECT_EQ(items[1].name, "name2");
  15393. EXPECT_EQ(items[1].content, "Testing456");
  15394. EXPECT_EQ(items[1].filename, "");
  15395. EXPECT_EQ(items[1].content_type, "");
  15396. EXPECT_EQ(items[2].name, "name3");
  15397. EXPECT_EQ(items[2].content, rand1);
  15398. EXPECT_EQ(items[2].filename, "filename3");
  15399. EXPECT_EQ(items[2].content_type, "");
  15400. EXPECT_EQ(items[3].name, "name4");
  15401. EXPECT_EQ(items[3].content, rand2);
  15402. EXPECT_EQ(items[3].filename, "filename4");
  15403. EXPECT_EQ(items[3].content_type, "");
  15404. });
  15405. auto port = svr.bind_to_any_port("localhost");
  15406. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15407. auto se = detail::scope_exit([&] {
  15408. svr.stop();
  15409. t.join();
  15410. ASSERT_FALSE(svr.is_running());
  15411. });
  15412. svr.wait_until_ready();
  15413. {
  15414. SSLClient cli("localhost", port);
  15415. cli.enable_server_certificate_verification(false);
  15416. UploadFormDataItems items{
  15417. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15418. {"name2", "Testing456", "", ""}, // not a file
  15419. };
  15420. {
  15421. auto res = cli.Post("/post-none", {}, {}, {});
  15422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15423. ASSERT_EQ(StatusCode::OK_200, res->status);
  15424. }
  15425. FormDataProviderItems providers;
  15426. {
  15427. auto res =
  15428. cli.Post("/post-items", {}, items, providers); // empty providers
  15429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15430. ASSERT_EQ(StatusCode::OK_200, res->status);
  15431. }
  15432. providers.push_back({"name3",
  15433. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15434. // test the offset is given correctly at each step
  15435. if (!offset)
  15436. sink.os.write(rand1.data(), 30);
  15437. else if (offset == 30)
  15438. sink.os.write(rand1.data() + 30, 300);
  15439. else if (offset == 330)
  15440. sink.os.write(rand1.data() + 330, 670);
  15441. else if (offset == rand1.size())
  15442. sink.done();
  15443. return true;
  15444. },
  15445. "filename3",
  15446. {}});
  15447. providers.push_back({"name4",
  15448. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15449. // test the offset is given correctly at each step
  15450. if (!offset)
  15451. sink.os.write(rand2.data(), 2000);
  15452. else if (offset == 2000)
  15453. sink.os.write(rand2.data() + 2000, 1);
  15454. else if (offset == 2001)
  15455. sink.os.write(rand2.data() + 2001, 999);
  15456. else if (offset == rand2.size())
  15457. sink.done();
  15458. return true;
  15459. },
  15460. "filename4",
  15461. {}});
  15462. {
  15463. auto res = cli.Post("/post-providers", {}, {}, providers);
  15464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15465. ASSERT_EQ(StatusCode::OK_200, res->status);
  15466. }
  15467. {
  15468. auto res = cli.Post("/post-both", {}, items, providers);
  15469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15470. ASSERT_EQ(StatusCode::OK_200, res->status);
  15471. }
  15472. }
  15473. }
  15474. TEST(MultipartFormDataTest, BadHeader) {
  15475. Server svr;
  15476. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15477. res.set_content("ok", "text/plain");
  15478. });
  15479. thread t = thread([&] { svr.listen(HOST, PORT); });
  15480. auto se = detail::scope_exit([&] {
  15481. svr.stop();
  15482. t.join();
  15483. ASSERT_FALSE(svr.is_running());
  15484. });
  15485. svr.wait_until_ready();
  15486. const std::string body =
  15487. "This is the preamble. It is to be ignored, though it\r\n"
  15488. "is a handy place for composition agents to include an\r\n"
  15489. "explanatory note to non-MIME conformant readers.\r\n"
  15490. "\r\n"
  15491. "\r\n"
  15492. "--simple boundary\r\n"
  15493. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15494. ": BAD...\r\n"
  15495. "\r\n"
  15496. "value1\r\n"
  15497. "--simple boundary\r\n"
  15498. "Content-Disposition: form-data; name=\"field2\"; "
  15499. "filename=\"example.txt\"\r\n"
  15500. "\r\n"
  15501. "value2\r\n"
  15502. "--simple boundary--\r\n"
  15503. "This is the epilogue. It is also to be ignored.\r\n";
  15504. std::string content_type =
  15505. R"(multipart/form-data; boundary="simple boundary")";
  15506. Client cli(HOST, PORT);
  15507. auto res = cli.Post("/post", body, content_type.c_str());
  15508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15509. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15510. }
  15511. TEST(MultipartFormDataTest, WithPreamble) {
  15512. Server svr;
  15513. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15514. res.set_content("ok", "text/plain");
  15515. });
  15516. thread t = thread([&] { svr.listen(HOST, PORT); });
  15517. auto se = detail::scope_exit([&] {
  15518. svr.stop();
  15519. t.join();
  15520. ASSERT_FALSE(svr.is_running());
  15521. });
  15522. svr.wait_until_ready();
  15523. const std::string body =
  15524. "This is the preamble. It is to be ignored, though it\r\n"
  15525. "is a handy place for composition agents to include an\r\n"
  15526. "explanatory note to non-MIME conformant readers.\r\n"
  15527. "\r\n"
  15528. "\r\n"
  15529. "--simple boundary\r\n"
  15530. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15531. "\r\n"
  15532. "value1\r\n"
  15533. "--simple boundary\r\n"
  15534. "Content-Disposition: form-data; name=\"field2\"; "
  15535. "filename=\"example.txt\"\r\n"
  15536. "\r\n"
  15537. "value2\r\n"
  15538. "--simple boundary--\r\n"
  15539. "This is the epilogue. It is also to be ignored.\r\n";
  15540. std::string content_type =
  15541. R"(multipart/form-data; boundary="simple boundary")";
  15542. Client cli(HOST, PORT);
  15543. auto res = cli.Post("/post", body, content_type.c_str());
  15544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15545. EXPECT_EQ(StatusCode::OK_200, res->status);
  15546. }
  15547. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15549. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15550. const ContentReader &content_reader) {
  15551. if (req.is_multipart_form_data()) {
  15552. std::vector<FormData> items;
  15553. content_reader(
  15554. [&](const FormData &file) {
  15555. items.push_back(file);
  15556. return true;
  15557. },
  15558. [&](const char *data, size_t data_length) {
  15559. items.back().content.append(data, data_length);
  15560. return true;
  15561. });
  15562. EXPECT_TRUE(std::string(items[0].name) == "document");
  15563. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15564. EXPECT_TRUE(items[0].filename == "2MB_data");
  15565. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15566. EXPECT_TRUE(items[1].name == "hello");
  15567. EXPECT_TRUE(items[1].content == "world");
  15568. EXPECT_TRUE(items[1].filename == "");
  15569. EXPECT_TRUE(items[1].content_type == "");
  15570. } else {
  15571. std::string body;
  15572. content_reader([&](const char *data, size_t data_length) {
  15573. body.append(data, data_length);
  15574. return true;
  15575. });
  15576. }
  15577. });
  15578. auto port = svr.bind_to_any_port("localhost");
  15579. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15580. auto se = detail::scope_exit([&] {
  15581. svr.stop();
  15582. t.join();
  15583. ASSERT_FALSE(svr.is_running());
  15584. });
  15585. svr.wait_until_ready();
  15586. {
  15587. std::string data(1024 * 1024 * 2, '.');
  15588. std::stringstream buffer;
  15589. buffer << data;
  15590. SSLClient cli("localhost", port);
  15591. cli.enable_server_certificate_verification(false);
  15592. UploadFormDataItems items{
  15593. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15594. {"hello", "world", "", ""},
  15595. };
  15596. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15598. ASSERT_EQ(StatusCode::OK_200, res->status);
  15599. }
  15600. }
  15601. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15602. std::string data(1024 * 1024 * 2, '&');
  15603. std::stringstream buffer;
  15604. buffer << data;
  15605. Client cli("https://localhost:8080");
  15606. UploadFormDataItems items{
  15607. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15608. {"hello", "world", "", ""},
  15609. };
  15610. for (const char &c : " \t\r\n") {
  15611. auto res =
  15612. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15613. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15614. ASSERT_FALSE(res);
  15615. }
  15616. }
  15617. TEST(MultipartFormDataTest, PutFormData) {
  15618. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15619. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15620. const ContentReader &content_reader) {
  15621. if (req.is_multipart_form_data()) {
  15622. std::vector<FormData> items;
  15623. content_reader(
  15624. [&](const FormData &file) {
  15625. items.push_back(file);
  15626. return true;
  15627. },
  15628. [&](const char *data, size_t data_length) {
  15629. items.back().content.append(data, data_length);
  15630. return true;
  15631. });
  15632. EXPECT_TRUE(std::string(items[0].name) == "document");
  15633. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15634. EXPECT_TRUE(items[0].filename == "2MB_data");
  15635. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15636. EXPECT_TRUE(items[1].name == "hello");
  15637. EXPECT_TRUE(items[1].content == "world");
  15638. EXPECT_TRUE(items[1].filename == "");
  15639. EXPECT_TRUE(items[1].content_type == "");
  15640. } else {
  15641. std::string body;
  15642. content_reader([&](const char *data, size_t data_length) {
  15643. body.append(data, data_length);
  15644. return true;
  15645. });
  15646. }
  15647. });
  15648. auto port = svr.bind_to_any_port("localhost");
  15649. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15650. auto se = detail::scope_exit([&] {
  15651. svr.stop();
  15652. t.join();
  15653. ASSERT_FALSE(svr.is_running());
  15654. });
  15655. svr.wait_until_ready();
  15656. {
  15657. std::string data(1024 * 1024 * 2, '&');
  15658. std::stringstream buffer;
  15659. buffer << data;
  15660. SSLClient cli("localhost", port);
  15661. cli.enable_server_certificate_verification(false);
  15662. UploadFormDataItems items{
  15663. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15664. {"hello", "world", "", ""},
  15665. };
  15666. auto res = cli.Put("/put", items);
  15667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15668. ASSERT_EQ(StatusCode::OK_200, res->status);
  15669. }
  15670. }
  15671. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15672. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15673. svr.Put("/put_customboundary",
  15674. [&](const Request &req, const Response & /*res*/,
  15675. const ContentReader &content_reader) {
  15676. if (req.is_multipart_form_data()) {
  15677. std::vector<FormData> items;
  15678. content_reader(
  15679. [&](const FormData &file) {
  15680. items.push_back(file);
  15681. return true;
  15682. },
  15683. [&](const char *data, size_t data_length) {
  15684. items.back().content.append(data, data_length);
  15685. return true;
  15686. });
  15687. EXPECT_TRUE(std::string(items[0].name) == "document");
  15688. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15689. EXPECT_TRUE(items[0].filename == "2MB_data");
  15690. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15691. EXPECT_TRUE(items[1].name == "hello");
  15692. EXPECT_TRUE(items[1].content == "world");
  15693. EXPECT_TRUE(items[1].filename == "");
  15694. EXPECT_TRUE(items[1].content_type == "");
  15695. } else {
  15696. std::string body;
  15697. content_reader([&](const char *data, size_t data_length) {
  15698. body.append(data, data_length);
  15699. return true;
  15700. });
  15701. }
  15702. });
  15703. auto port = svr.bind_to_any_port("localhost");
  15704. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15705. auto se = detail::scope_exit([&] {
  15706. svr.stop();
  15707. t.join();
  15708. ASSERT_FALSE(svr.is_running());
  15709. });
  15710. svr.wait_until_ready();
  15711. {
  15712. std::string data(1024 * 1024 * 2, '&');
  15713. std::stringstream buffer;
  15714. buffer << data;
  15715. SSLClient cli("localhost", port);
  15716. cli.enable_server_certificate_verification(false);
  15717. UploadFormDataItems items{
  15718. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15719. {"hello", "world", "", ""},
  15720. };
  15721. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15723. ASSERT_EQ(StatusCode::OK_200, res->status);
  15724. }
  15725. }
  15726. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15727. std::string data(1024 * 1024 * 2, '&');
  15728. std::stringstream buffer;
  15729. buffer << data;
  15730. Client cli("https://localhost:8080");
  15731. cli.enable_server_certificate_verification(false);
  15732. UploadFormDataItems items{
  15733. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15734. {"hello", "world", "", ""},
  15735. };
  15736. for (const char &c : " \t\r\n") {
  15737. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15738. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15739. ASSERT_FALSE(res);
  15740. }
  15741. }
  15742. TEST(MultipartFormDataTest, AlternateFilename) {
  15743. auto handled = false;
  15744. Server svr;
  15745. svr.Post("/test", [&](const Request &req, Response &res) {
  15746. ASSERT_EQ(2u, req.form.files.size());
  15747. ASSERT_EQ(1u, req.form.fields.size());
  15748. // Test files
  15749. const auto &file1 = req.form.get_file("file1");
  15750. ASSERT_EQ("file1", file1.name);
  15751. ASSERT_EQ("A.txt", file1.filename);
  15752. ASSERT_EQ("text/plain", file1.content_type);
  15753. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15754. const auto &file2 = req.form.get_file("file2");
  15755. ASSERT_EQ("file2", file2.name);
  15756. ASSERT_EQ("a.html", file2.filename);
  15757. ASSERT_EQ("text/html", file2.content_type);
  15758. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15759. file2.content);
  15760. // Test text field
  15761. const auto &text = req.form.get_field("text");
  15762. ASSERT_EQ("text default", text);
  15763. res.set_content("ok", "text/plain");
  15764. handled = true;
  15765. });
  15766. thread t = thread([&] { svr.listen(HOST, PORT); });
  15767. auto se = detail::scope_exit([&] {
  15768. svr.stop();
  15769. t.join();
  15770. ASSERT_FALSE(svr.is_running());
  15771. ASSERT_TRUE(handled);
  15772. });
  15773. svr.wait_until_ready();
  15774. auto req = "POST /test HTTP/1.1\r\n"
  15775. "Host: localhost\r\n"
  15776. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15777. "Content-Length: 399\r\n"
  15778. "\r\n"
  15779. "----------\r\n"
  15780. "Content-Disposition: form-data; name=\"text\"\r\n"
  15781. "\r\n"
  15782. "text default\r\n"
  15783. "----------\r\n"
  15784. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15785. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15786. "Content-Type: text/plain\r\n"
  15787. "\r\n"
  15788. "Content of a.txt.\r\n"
  15789. "\r\n"
  15790. "----------\r\n"
  15791. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15792. "\"a.html\"\r\n"
  15793. "Content-Type: text/html\r\n"
  15794. "\r\n"
  15795. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15796. "\r\n"
  15797. "------------\r\n";
  15798. ASSERT_TRUE(send_request(1, req));
  15799. }
  15800. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15801. auto handled = false;
  15802. Server svr;
  15803. svr.Post("/test", [&](const Request &req, Response &res) {
  15804. // Case-insensitive "utf-8''" prefix with a long value
  15805. const auto &file = req.form.get_file("file1");
  15806. ASSERT_EQ("file1", file.name);
  15807. // 8000 chars exercises both the Content-Disposition parser and the
  15808. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15809. // Prior to the fix, std::regex_match on this header would cause O(N)
  15810. // stack recursion in libstdc++, leading to SIGSEGV.
  15811. std::string expected_filename(8000, 'A');
  15812. ASSERT_EQ(expected_filename, file.filename);
  15813. res.set_content("ok", "text/plain");
  15814. handled = true;
  15815. });
  15816. thread t = thread([&] { svr.listen(HOST, PORT); });
  15817. auto se = detail::scope_exit([&] {
  15818. svr.stop();
  15819. t.join();
  15820. ASSERT_FALSE(svr.is_running());
  15821. ASSERT_TRUE(handled);
  15822. });
  15823. svr.wait_until_ready();
  15824. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15825. // Regression test for GHSA-qq6v-r583-3h69
  15826. std::string long_filename(8000, 'A');
  15827. std::string body = "----------\r\n"
  15828. "Content-Disposition: form-data; name=\"file1\"; "
  15829. "filename*=\"Utf-8''" +
  15830. long_filename +
  15831. "\"\r\n"
  15832. "\r\n"
  15833. "hello\r\n"
  15834. "------------\r\n";
  15835. auto req = "POST /test HTTP/1.1\r\n"
  15836. "Host: localhost\r\n"
  15837. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15838. "Content-Length: " +
  15839. std::to_string(body.size()) + "\r\n\r\n" + body;
  15840. ASSERT_TRUE(send_request(1, req));
  15841. }
  15842. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15843. auto handled = false;
  15844. Server svr;
  15845. svr.Post("/test", [&](const Request &req, Response &) {
  15846. ASSERT_EQ(2u, req.form.fields.size());
  15847. const auto &text1 = req.form.get_field("text1");
  15848. ASSERT_EQ("text1", text1);
  15849. const auto &text2 = req.form.get_field("text2");
  15850. ASSERT_EQ("text2", text2);
  15851. handled = true;
  15852. });
  15853. thread t = thread([&] { svr.listen(HOST, PORT); });
  15854. auto se = detail::scope_exit([&] {
  15855. svr.stop();
  15856. t.join();
  15857. ASSERT_FALSE(svr.is_running());
  15858. ASSERT_TRUE(handled);
  15859. });
  15860. svr.wait_until_ready();
  15861. auto req = "POST /test HTTP/1.1\r\n"
  15862. "Host: localhost\r\n"
  15863. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15864. "Content-Length: 146\r\n"
  15865. "\r\n----------\r\n"
  15866. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15867. "\r\n"
  15868. "text1"
  15869. "\r\n----------\r\n"
  15870. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15871. "\r\n"
  15872. "text2"
  15873. "\r\n------------";
  15874. std::string response;
  15875. ASSERT_TRUE(send_request(1, req, &response));
  15876. ASSERT_EQ("200", response.substr(9, 3));
  15877. }
  15878. TEST(MultipartFormDataTest, ContentLength) {
  15879. auto handled = false;
  15880. Server svr;
  15881. svr.Post("/test", [&](const Request &req, Response &) {
  15882. ASSERT_EQ(2u, req.form.fields.size());
  15883. const auto &text1 = req.form.get_field("text1");
  15884. ASSERT_EQ("text1", text1);
  15885. const auto &text2 = req.form.get_field("text2");
  15886. ASSERT_EQ("text2", text2);
  15887. handled = true;
  15888. });
  15889. thread t = thread([&] { svr.listen(HOST, PORT); });
  15890. auto se = detail::scope_exit([&] {
  15891. svr.stop();
  15892. t.join();
  15893. ASSERT_FALSE(svr.is_running());
  15894. ASSERT_TRUE(handled);
  15895. });
  15896. svr.wait_until_ready();
  15897. auto req = "POST /test HTTP/1.1\r\n"
  15898. "Host: localhost\r\n"
  15899. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15900. "Content-Length: 167\r\n"
  15901. "\r\n----------\r\n"
  15902. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15903. "Content-Length: 5\r\n"
  15904. "\r\n"
  15905. "text1"
  15906. "\r\n----------\r\n"
  15907. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15908. "\r\n"
  15909. "text2"
  15910. "\r\n------------\r\n";
  15911. std::string response;
  15912. ASSERT_TRUE(send_request(1, req, &response));
  15913. ASSERT_EQ("200", response.substr(9, 3));
  15914. }
  15915. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15916. auto handled = false;
  15917. Server svr;
  15918. svr.Post("/test", [&](const Request &req, Response &) {
  15919. ASSERT_EQ(2u, req.form.fields.size());
  15920. const auto &text1 = req.form.get_field("text1");
  15921. ASSERT_EQ("text1", text1);
  15922. // TODO: Add header access for text fields if needed
  15923. const auto &text2 = req.form.get_field("text2");
  15924. ASSERT_EQ("text2", text2);
  15925. // TODO: Header access for text fields needs to be implemented
  15926. // auto &headers = it->second.headers;
  15927. // ASSERT_EQ(3U, headers.size());
  15928. // auto custom_header = headers.find("x-whatever");
  15929. // ASSERT_TRUE(custom_header != headers.end());
  15930. // ASSERT_NE("customvalue", custom_header->second);
  15931. // ASSERT_EQ("CustomValue", custom_header->second);
  15932. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15933. handled = true;
  15934. });
  15935. thread t = thread([&] { svr.listen(HOST, PORT); });
  15936. auto se = detail::scope_exit([&] {
  15937. svr.stop();
  15938. t.join();
  15939. ASSERT_FALSE(svr.is_running());
  15940. ASSERT_TRUE(handled);
  15941. });
  15942. svr.wait_until_ready();
  15943. auto req = "POST /test HTTP/1.1\r\n"
  15944. "Host: localhost\r\n"
  15945. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15946. "Content-Length: 232\r\n"
  15947. "\r\n----------\r\n"
  15948. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15949. "Content-Length: 5\r\n"
  15950. "X-Test: 1\r\n"
  15951. "\r\n"
  15952. "text1"
  15953. "\r\n----------\r\n"
  15954. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15955. "Content-Type: text/plain\r\n"
  15956. "X-Whatever: CustomValue\r\n"
  15957. "\r\n"
  15958. "text2"
  15959. "\r\n------------\r\n"
  15960. "That should be disregarded. Not even read";
  15961. std::string response;
  15962. ASSERT_TRUE(send_request(1, req, &response));
  15963. ASSERT_EQ("200", response.substr(9, 3));
  15964. }
  15965. TEST(MultipartFormDataTest, LargeHeader) {
  15966. auto handled = false;
  15967. Server svr;
  15968. svr.Post("/test", [&](const Request &req, Response &) {
  15969. ASSERT_EQ(1u, req.form.fields.size());
  15970. const auto &text = req.form.get_field("name1");
  15971. ASSERT_EQ("text1", text);
  15972. handled = true;
  15973. });
  15974. thread t = thread([&] { svr.listen(HOST, PORT); });
  15975. auto se = detail::scope_exit([&] {
  15976. svr.stop();
  15977. t.join();
  15978. ASSERT_FALSE(svr.is_running());
  15979. ASSERT_TRUE(handled);
  15980. });
  15981. svr.wait_until_ready();
  15982. auto boundary = std::string("cpp-httplib-multipart-data");
  15983. std::string content = "--" + boundary +
  15984. "\r\n"
  15985. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15986. "\r\n"
  15987. "text1\r\n"
  15988. "--" +
  15989. boundary + "--\r\n";
  15990. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15991. "Host: localhost\r\n"
  15992. "Content-Type: multipart/form-data;boundary=" +
  15993. boundary +
  15994. "\r\n"
  15995. "Content-Length: " +
  15996. std::to_string(content.size()) +
  15997. "\r\n"
  15998. "Dummy-Header: ";
  15999. std::string header_suffix = "\r\n"
  16000. "\r\n";
  16001. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16002. size_t header_dummy_size =
  16003. read_buff_size -
  16004. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16005. auto header_dummy = std::string(header_dummy_size, '@');
  16006. auto req = header_prefix + header_dummy + header_suffix + content;
  16007. std::string response;
  16008. ASSERT_TRUE(send_request(1, req, &response));
  16009. ASSERT_EQ("200", response.substr(9, 3));
  16010. }
  16011. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16012. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16013. // (not chunked Transfer-Encoding) after the streaming refactor.
  16014. auto handled = false;
  16015. Server svr;
  16016. svr.Post("/upload", [&](const Request &req, Response &res) {
  16017. auto cl_it = req.headers.find("Content-Length");
  16018. EXPECT_TRUE(cl_it != req.headers.end());
  16019. auto te_it = req.headers.find("Transfer-Encoding");
  16020. EXPECT_TRUE(te_it == req.headers.end());
  16021. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16022. res.set_content("ok", "text/plain");
  16023. handled = true;
  16024. });
  16025. auto port = svr.bind_to_any_port(HOST);
  16026. auto t = thread([&] { svr.listen_after_bind(); });
  16027. auto se = detail::scope_exit([&] {
  16028. svr.stop();
  16029. t.join();
  16030. ASSERT_FALSE(svr.is_running());
  16031. ASSERT_TRUE(handled);
  16032. });
  16033. svr.wait_until_ready();
  16034. UploadFormDataItems items = {
  16035. {"field1", "hello", "", "text/plain"},
  16036. {"file1", "world", "test.txt", "application/octet-stream"},
  16037. };
  16038. Client cli(HOST, port);
  16039. auto res = cli.Post("/upload", {}, items);
  16040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16041. EXPECT_EQ(StatusCode::OK_200, res->status);
  16042. }
  16043. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16044. // Verify that make_multipart_content_provider coalesces many small segments
  16045. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16046. constexpr size_t kItemCount = 1000;
  16047. UploadFormDataItems items;
  16048. items.reserve(kItemCount);
  16049. for (size_t i = 0; i < kItemCount; i++) {
  16050. items.push_back(
  16051. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16052. }
  16053. const std::string boundary = "----test-boundary";
  16054. auto content_length = detail::get_multipart_content_length(items, boundary);
  16055. auto provider = detail::make_multipart_content_provider(items, boundary);
  16056. // Drive the provider the same way write_content_with_progress does
  16057. size_t write_count = 0;
  16058. size_t total_bytes = 0;
  16059. DataSink sink;
  16060. size_t offset = 0;
  16061. sink.write = [&](const char *d, size_t l) -> bool {
  16062. (void)d;
  16063. write_count++;
  16064. total_bytes += l;
  16065. offset += l;
  16066. return true;
  16067. };
  16068. sink.is_writable = []() -> bool { return true; };
  16069. while (offset < content_length) {
  16070. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16071. }
  16072. EXPECT_EQ(content_length, total_bytes);
  16073. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16074. // With buffering into 64KB blocks, write_count should be much smaller.
  16075. auto segment_count = 3 * kItemCount + 1;
  16076. EXPECT_LT(write_count, segment_count / 10);
  16077. }
  16078. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16079. // Integration test: send many UploadFormDataItems and verify the server
  16080. // receives all of them correctly (#2410).
  16081. constexpr size_t kItemCount = 500;
  16082. auto handled = false;
  16083. Server svr;
  16084. svr.Post("/upload", [&](const Request &req, Response &res) {
  16085. EXPECT_EQ(kItemCount, req.form.fields.size());
  16086. for (size_t i = 0; i < kItemCount; i++) {
  16087. auto key = "field" + std::to_string(i);
  16088. auto val = "value" + std::to_string(i);
  16089. auto it = req.form.fields.find(key);
  16090. if (it != req.form.fields.end()) {
  16091. EXPECT_EQ(val, it->second.content);
  16092. } else {
  16093. ADD_FAILURE() << "Missing field: " << key;
  16094. }
  16095. }
  16096. res.set_content("ok", "text/plain");
  16097. handled = true;
  16098. });
  16099. auto port = svr.bind_to_any_port(HOST);
  16100. auto t = thread([&] { svr.listen_after_bind(); });
  16101. auto se = detail::scope_exit([&] {
  16102. svr.stop();
  16103. t.join();
  16104. ASSERT_FALSE(svr.is_running());
  16105. ASSERT_TRUE(handled);
  16106. });
  16107. svr.wait_until_ready();
  16108. UploadFormDataItems items;
  16109. items.reserve(kItemCount);
  16110. for (size_t i = 0; i < kItemCount; i++) {
  16111. items.push_back(
  16112. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16113. }
  16114. Client cli(HOST, port);
  16115. auto res = cli.Post("/upload", items);
  16116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16117. EXPECT_EQ(StatusCode::OK_200, res->status);
  16118. }
  16119. TEST(MultipartFormDataTest, MakeFileProvider) {
  16120. // Verify make_file_provider sends a file's contents correctly.
  16121. const std::string file_content(4096, 'Z');
  16122. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16123. {
  16124. std::ofstream ofs(tmp_path, std::ios::binary);
  16125. ofs.write(file_content.data(),
  16126. static_cast<std::streamsize>(file_content.size()));
  16127. }
  16128. auto handled = false;
  16129. Server svr;
  16130. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16131. const ContentReader &content_reader) {
  16132. ASSERT_TRUE(req.is_multipart_form_data());
  16133. std::vector<FormData> items;
  16134. content_reader(
  16135. [&](const FormData &file) {
  16136. items.push_back(file);
  16137. return true;
  16138. },
  16139. [&](const char *data, size_t data_length) {
  16140. items.back().content.append(data, data_length);
  16141. return true;
  16142. });
  16143. ASSERT_EQ(1u, items.size());
  16144. EXPECT_EQ("myfile", items[0].name);
  16145. EXPECT_EQ("data.bin", items[0].filename);
  16146. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16147. EXPECT_EQ(file_content, items[0].content);
  16148. handled = true;
  16149. });
  16150. auto port = svr.bind_to_any_port(HOST);
  16151. auto t = thread([&] { svr.listen_after_bind(); });
  16152. auto se = detail::scope_exit([&] {
  16153. svr.stop();
  16154. t.join();
  16155. ASSERT_FALSE(svr.is_running());
  16156. ASSERT_TRUE(handled);
  16157. std::remove(tmp_path.c_str());
  16158. });
  16159. svr.wait_until_ready();
  16160. FormDataProviderItems providers;
  16161. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16162. "application/octet-stream"));
  16163. Client cli(HOST, port);
  16164. auto res = cli.Post("/upload", {}, {}, providers);
  16165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16166. EXPECT_EQ(StatusCode::OK_200, res->status);
  16167. }
  16168. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16169. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16170. // (100) headers is rejected with a 400 Bad Request response.
  16171. Server svr;
  16172. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16173. res.set_content("ok", "text/plain");
  16174. });
  16175. thread t = thread([&] { svr.listen(HOST, PORT); });
  16176. auto se = detail::scope_exit([&] {
  16177. svr.stop();
  16178. t.join();
  16179. ASSERT_FALSE(svr.is_running());
  16180. });
  16181. svr.wait_until_ready();
  16182. // Build a multipart part with 101 custom headers (exceeding
  16183. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16184. std::stringstream body;
  16185. body << "--simpleboundary\r\n"
  16186. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16187. for (int i = 0; i < 101; i++) {
  16188. body << "X-Custom-Header-" << i << ": value\r\n";
  16189. }
  16190. body << "\r\n"
  16191. << "value1\r\n"
  16192. << "--simpleboundary--\r\n";
  16193. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16194. Client cli(HOST, PORT);
  16195. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16197. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16198. }
  16199. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16200. // A body that never contains the declared boundary must not be accumulated
  16201. // while the parser waits for it. Buffering it would also make every read
  16202. // rescan everything seen so far, which is quadratic in the body size.
  16203. Server svr;
  16204. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16205. res.set_content("ok", "text/plain");
  16206. });
  16207. auto port = svr.bind_to_any_port(HOST);
  16208. thread t = thread([&] { svr.listen_after_bind(); });
  16209. auto se = detail::scope_exit([&] {
  16210. svr.stop();
  16211. t.join();
  16212. ASSERT_FALSE(svr.is_running());
  16213. });
  16214. svr.wait_until_ready();
  16215. Client cli(HOST, port);
  16216. cli.set_read_timeout(60, 0);
  16217. cli.set_write_timeout(60, 0);
  16218. // '-' is the worst case: it matches the first character of the boundary, so
  16219. // every position has to be checked against it.
  16220. auto post_dashes = [&](size_t size) {
  16221. const std::string body(size, '-');
  16222. auto start = std::chrono::steady_clock::now();
  16223. auto res =
  16224. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16225. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16226. std::chrono::steady_clock::now() - start)
  16227. .count();
  16228. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16229. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16230. return ms;
  16231. };
  16232. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16233. // Windows.
  16234. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16235. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16236. // Comparing the two sizes rather than checking an absolute duration keeps
  16237. // this meaningful across build types and CI load, both of which move the
  16238. // absolute numbers by more than an order of magnitude. Four times the bytes
  16239. // costs about four times the time when parsing is linear, and about sixteen
  16240. // times when the body is buffered and rescanned.
  16241. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16242. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16243. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16244. << "ms, which suggests the body is being buffered and rescanned";
  16245. }
  16246. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16247. // A boundary can only be followed by CRLF or by "--", so anything else is
  16248. // malformed no matter what comes next. The parser must say so right away
  16249. // instead of buffering the rest of the declared body.
  16250. Server svr;
  16251. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16252. res.set_content("ok", "text/plain");
  16253. });
  16254. auto port = svr.bind_to_any_port(HOST);
  16255. thread t = thread([&] { svr.listen_after_bind(); });
  16256. auto se = detail::scope_exit([&] {
  16257. svr.stop();
  16258. t.join();
  16259. ASSERT_FALSE(svr.is_running());
  16260. });
  16261. svr.wait_until_ready();
  16262. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16263. // buffers instead of failing would still be waiting for the remaining bytes.
  16264. const std::string body = "--zzzz\r\n"
  16265. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16266. "\r\n"
  16267. "text1"
  16268. "\r\n--zzzzXX";
  16269. const std::string req = "POST /post HTTP/1.1\r\n"
  16270. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16271. "Content-Length: 1048576\r\n"
  16272. "\r\n" +
  16273. body;
  16274. std::string response;
  16275. ASSERT_TRUE(send_request(3, req, &response, port));
  16276. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16277. EXPECT_EQ("400", response.substr(9, 3));
  16278. }
  16279. // Posts a multipart body split into two writes, so that the server sees the
  16280. // split at whatever offset the caller chose, and expects the single "text1"
  16281. // field to come through.
  16282. static void expect_split_multipart_ok(const std::string &body1,
  16283. const std::string &body2) {
  16284. auto handled = false;
  16285. Server svr;
  16286. svr.Post("/post", [&](const Request &req, Response &) {
  16287. EXPECT_EQ(1u, req.form.fields.size());
  16288. EXPECT_EQ("text1", req.form.get_field("text1"));
  16289. handled = true;
  16290. });
  16291. auto port = svr.bind_to_any_port(HOST);
  16292. thread t = thread([&] { svr.listen_after_bind(); });
  16293. auto se = detail::scope_exit([&] {
  16294. svr.stop();
  16295. t.join();
  16296. ASSERT_FALSE(svr.is_running());
  16297. ASSERT_TRUE(handled);
  16298. });
  16299. svr.wait_until_ready();
  16300. // "Connection: close" makes the server close once it has answered, so the
  16301. // response drain ends immediately instead of idling until the read timeout.
  16302. const std::string head =
  16303. "POST /post HTTP/1.1\r\n"
  16304. "Host: localhost\r\n"
  16305. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16306. "Connection: close\r\n"
  16307. "Content-Length: " +
  16308. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16309. std::string response;
  16310. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16311. ASSERT_GE(response.size(), 12u) << "no response";
  16312. EXPECT_EQ("200", response.substr(9, 3));
  16313. }
  16314. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16315. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16316. // ignored, including when it does not arrive in the same read as the
  16317. // close-delimiter itself.
  16318. expect_split_multipart_ok("--zzzz\r\n"
  16319. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16320. "\r\n"
  16321. "text1"
  16322. "\r\n--zzzz--",
  16323. "\r\nthis epilogue must be ignored\r\n");
  16324. }
  16325. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16326. // The initial boundary may be preceded by a preamble of any length and may
  16327. // straddle a read boundary. Discarding data while waiting for it must not
  16328. // throw away a partial boundary sitting at the end of the buffer.
  16329. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16330. "zz\r\n"
  16331. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16332. "\r\n"
  16333. "text1"
  16334. "\r\n--zzzz--\r\n");
  16335. }
  16336. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16337. // The received boundary was only checked for being non-empty, so it could be
  16338. // as long as a header is allowed to be. The parser scans the body for
  16339. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16340. // costs a nearly full comparison at nearly every position, making the
  16341. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16342. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16343. Server svr;
  16344. svr.Post("/post", [](const Request &req, Response &res) {
  16345. EXPECT_EQ(1u, req.form.fields.size());
  16346. EXPECT_EQ("text1", req.form.get_field("text1"));
  16347. res.set_content("ok", "text/plain");
  16348. });
  16349. auto port = svr.bind_to_any_port(HOST);
  16350. thread t = thread([&] { svr.listen_after_bind(); });
  16351. auto se = detail::scope_exit([&] {
  16352. svr.stop();
  16353. t.join();
  16354. ASSERT_FALSE(svr.is_running());
  16355. });
  16356. svr.wait_until_ready();
  16357. Client cli(HOST, port);
  16358. auto post_with_boundary_of_length = [&](size_t len) {
  16359. const std::string boundary(len, 'a');
  16360. const std::string body =
  16361. "--" + boundary +
  16362. "\r\n"
  16363. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16364. "\r\n"
  16365. "text1"
  16366. "\r\n--" +
  16367. boundary + "--\r\n";
  16368. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16369. };
  16370. auto res = post_with_boundary_of_length(70);
  16371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16372. EXPECT_EQ(StatusCode::OK_200, res->status);
  16373. res = post_with_boundary_of_length(71);
  16374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16375. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16376. }
  16377. TEST(MakeFileBodyTest, Basic) {
  16378. const std::string file_content(4096, 'Z');
  16379. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16380. {
  16381. std::ofstream ofs(tmp_path, std::ios::binary);
  16382. ofs.write(file_content.data(),
  16383. static_cast<std::streamsize>(file_content.size()));
  16384. }
  16385. auto handled = false;
  16386. Server svr;
  16387. svr.Post("/upload", [&](const Request &req, Response &res) {
  16388. EXPECT_EQ(file_content, req.body);
  16389. handled = true;
  16390. res.status = StatusCode::OK_200;
  16391. });
  16392. auto port = svr.bind_to_any_port(HOST);
  16393. auto t = thread([&] { svr.listen_after_bind(); });
  16394. auto se = detail::scope_exit([&] {
  16395. svr.stop();
  16396. t.join();
  16397. ASSERT_FALSE(svr.is_running());
  16398. ASSERT_TRUE(handled);
  16399. std::remove(tmp_path.c_str());
  16400. });
  16401. svr.wait_until_ready();
  16402. auto fb = make_file_body(tmp_path);
  16403. ASSERT_GT(fb.first, 0u);
  16404. Client cli(HOST, port);
  16405. auto res =
  16406. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16408. EXPECT_EQ(StatusCode::OK_200, res->status);
  16409. }
  16410. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16411. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16412. {
  16413. std::ofstream ofs(path, std::ios::binary);
  16414. const std::string content(100, 'A');
  16415. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16416. }
  16417. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16418. auto body = make_file_body(path);
  16419. ASSERT_EQ(100u, body.first);
  16420. ASSERT_TRUE(static_cast<bool>(body.second));
  16421. // Rewritten shorter after its length was measured - and, on a server, after
  16422. // that length has already gone out as Content-Length.
  16423. {
  16424. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16425. const std::string content(10, 'A');
  16426. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16427. }
  16428. std::string written;
  16429. DataSink sink;
  16430. sink.write = [&](const char *d, size_t l) {
  16431. written.append(d, l);
  16432. return true;
  16433. };
  16434. // The provider has to report failure. write_content_with_progress() advances
  16435. // its offset only by what was written, so a provider that returns true
  16436. // without completing the length it promised is called again straight away,
  16437. // and again.
  16438. EXPECT_FALSE(body.second(0, body.first, sink));
  16439. EXPECT_EQ(std::string(10, 'A'), written);
  16440. }
  16441. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16442. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16443. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16444. {
  16445. std::ofstream ofs(path, std::ios::binary);
  16446. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16447. }
  16448. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16449. auto body = make_file_body(path);
  16450. ASSERT_EQ(content.size(), body.first);
  16451. ASSERT_TRUE(static_cast<bool>(body.second));
  16452. std::string written;
  16453. DataSink sink;
  16454. sink.write = [&](const char *d, size_t l) {
  16455. written.append(d, l);
  16456. return true;
  16457. };
  16458. EXPECT_TRUE(body.second(0, body.first, sink));
  16459. EXPECT_EQ(content, written);
  16460. }
  16461. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16462. static constexpr unsigned int number_of_tasks{1000000};
  16463. std::atomic_uint count{0};
  16464. std::unique_ptr<TaskQueue> task_queue{
  16465. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16466. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16467. auto queued = task_queue->enqueue(
  16468. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16469. EXPECT_TRUE(queued);
  16470. }
  16471. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16472. task_queue->shutdown();
  16473. #else
  16474. EXPECT_NO_THROW(task_queue->shutdown());
  16475. #endif
  16476. EXPECT_EQ(number_of_tasks, count.load());
  16477. }
  16478. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16479. static constexpr unsigned int number_of_tasks{1000000};
  16480. static constexpr unsigned int qlimit{2};
  16481. unsigned int queued_count{0};
  16482. std::atomic_uint count{0};
  16483. std::unique_ptr<TaskQueue> task_queue{
  16484. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16485. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16486. if (task_queue->enqueue(
  16487. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16488. queued_count++;
  16489. }
  16490. }
  16491. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16492. task_queue->shutdown();
  16493. #else
  16494. EXPECT_NO_THROW(task_queue->shutdown());
  16495. #endif
  16496. EXPECT_EQ(queued_count, count.load());
  16497. EXPECT_TRUE(queued_count <= number_of_tasks);
  16498. EXPECT_TRUE(queued_count >= qlimit);
  16499. }
  16500. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16501. // Use a short idle timeout so a dynamic thread spawns, times out and
  16502. // exits during the test, and the pool keeps working afterwards.
  16503. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16504. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16505. /*idle_timeout_sec=*/1}};
  16506. std::atomic_uint count{0};
  16507. std::condition_variable cv;
  16508. std::mutex mtx;
  16509. bool release = false;
  16510. // Block the base thread so the second task spawns a dynamic thread.
  16511. EXPECT_TRUE(task_queue->enqueue([&] {
  16512. std::unique_lock<std::mutex> lock(mtx);
  16513. while (!release) {
  16514. cv.wait(lock);
  16515. }
  16516. count++;
  16517. }));
  16518. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16519. // Let the dynamic thread finish its task and exceed the idle timeout.
  16520. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16521. {
  16522. std::unique_lock<std::mutex> lock(mtx);
  16523. release = true;
  16524. }
  16525. cv.notify_all();
  16526. // The pool must still accept and run tasks after the dynamic thread exited.
  16527. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16528. task_queue->shutdown();
  16529. EXPECT_EQ(3u, count.load());
  16530. }
  16531. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16532. static constexpr size_t number_of_tasks{32};
  16533. std::unique_ptr<TaskQueue> task_queue{
  16534. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16535. // Let the base threads go idle so the burst below finds them waiting.
  16536. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16537. std::mutex mtx;
  16538. std::condition_variable cv;
  16539. size_t running = 0;
  16540. bool release = false;
  16541. for (size_t i = 0; i < number_of_tasks; i++) {
  16542. EXPECT_TRUE(task_queue->enqueue([&] {
  16543. std::unique_lock<std::mutex> lock(mtx);
  16544. running++;
  16545. cv.notify_all();
  16546. cv.wait(lock, [&] { return release; });
  16547. }));
  16548. }
  16549. {
  16550. std::unique_lock<std::mutex> lock(mtx);
  16551. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16552. [&] { return running == number_of_tasks; }));
  16553. release = true;
  16554. }
  16555. cv.notify_all();
  16556. task_queue->shutdown();
  16557. }
  16558. TEST(TaskQueueTest, MaxQueuedRequests) {
  16559. static constexpr unsigned int qlimit{3};
  16560. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16561. std::condition_variable sem_cv;
  16562. std::mutex sem_mtx;
  16563. int credits = 0;
  16564. bool queued;
  16565. /* Fill up the queue with tasks that will block until we give them credits to
  16566. * complete. */
  16567. for (unsigned int n = 0; n <= qlimit;) {
  16568. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16569. std::unique_lock<std::mutex> lock(sem_mtx);
  16570. while (credits <= 0) {
  16571. sem_cv.wait(lock);
  16572. }
  16573. /* Consume the credit and signal the test code if they are all gone. */
  16574. if (--credits == 0) { sem_cv.notify_one(); }
  16575. });
  16576. if (n < qlimit) {
  16577. /* The first qlimit enqueues must succeed. */
  16578. EXPECT_TRUE(queued);
  16579. } else {
  16580. /* The last one will succeed only when the worker thread
  16581. * starts and dequeues the first blocking task. Although
  16582. * not necessary for the correctness of this test, we sleep for
  16583. * a short while to avoid busy waiting. */
  16584. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16585. }
  16586. if (queued) { n++; }
  16587. }
  16588. /* Further enqueues must fail since the queue is full. */
  16589. for (auto i = 0; i < 4; i++) {
  16590. queued = task_queue->enqueue([] {});
  16591. EXPECT_FALSE(queued);
  16592. }
  16593. /* Give the credits to allow the previous tasks to complete. */
  16594. {
  16595. std::unique_lock<std::mutex> lock(sem_mtx);
  16596. credits += qlimit + 1;
  16597. }
  16598. sem_cv.notify_all();
  16599. /* Wait for all the credits to be consumed. */
  16600. {
  16601. std::unique_lock<std::mutex> lock(sem_mtx);
  16602. while (credits > 0) {
  16603. sem_cv.wait(lock);
  16604. }
  16605. }
  16606. /* Check that we are able again to enqueue at least qlimit tasks. */
  16607. for (unsigned int i = 0; i < qlimit; i++) {
  16608. queued = task_queue->enqueue([] {});
  16609. EXPECT_TRUE(queued);
  16610. }
  16611. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16612. task_queue->shutdown();
  16613. #else
  16614. EXPECT_NO_THROW(task_queue->shutdown());
  16615. #endif
  16616. }
  16617. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16618. Server svr;
  16619. std::string method;
  16620. std::string body;
  16621. auto has_content_length = false;
  16622. auto has_transfer_encoding = false;
  16623. std::atomic<int> bad_requests{0};
  16624. // Leftover body bytes get parsed as a malformed request and answered with
  16625. // 400
  16626. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16627. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16628. });
  16629. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16630. res.set_redirect("/down", StatusCode::SeeOther_303);
  16631. });
  16632. svr.Get("/down", [&](const Request &req, Response &res) {
  16633. method = req.method;
  16634. body = req.body;
  16635. has_content_length = req.has_header("Content-Length");
  16636. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16637. res.set_content("ok", "text/plain");
  16638. });
  16639. auto port = svr.bind_to_any_port(HOST);
  16640. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16641. auto se = detail::scope_exit([&] {
  16642. svr.stop();
  16643. thread.join();
  16644. ASSERT_FALSE(svr.is_running());
  16645. });
  16646. svr.wait_until_ready();
  16647. const std::string payload = "SECRET-BODY";
  16648. auto check = [&](Client &cli, const Result &res) {
  16649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16650. EXPECT_EQ(StatusCode::OK_200, res->status);
  16651. EXPECT_EQ("ok", res->body);
  16652. EXPECT_EQ("GET", method);
  16653. EXPECT_TRUE(body.empty());
  16654. EXPECT_FALSE(has_content_length);
  16655. EXPECT_FALSE(has_transfer_encoding);
  16656. // Nothing of the original body may be left on the connection
  16657. auto res2 = cli.Get("/down");
  16658. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16659. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16660. EXPECT_EQ("ok", res2->body);
  16661. EXPECT_EQ(0, bad_requests);
  16662. };
  16663. // With content length
  16664. {
  16665. Client cli(HOST, port);
  16666. cli.set_keep_alive(true);
  16667. cli.set_follow_location(true);
  16668. auto res = cli.Post(
  16669. "/up", payload.size(),
  16670. [&](size_t offset, size_t length, DataSink &sink) {
  16671. return sink.write(payload.data() + offset, length);
  16672. },
  16673. "text/plain");
  16674. check(cli, res);
  16675. }
  16676. // Without content length (chunked)
  16677. {
  16678. Client cli(HOST, port);
  16679. cli.set_keep_alive(true);
  16680. cli.set_follow_location(true);
  16681. auto res = cli.Post(
  16682. "/up",
  16683. [&](size_t /*offset*/, DataSink &sink) {
  16684. sink.write(payload.data(), payload.size());
  16685. sink.done();
  16686. return true;
  16687. },
  16688. "text/plain");
  16689. check(cli, res);
  16690. }
  16691. }
  16692. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16693. Server svr;
  16694. std::string target;
  16695. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16696. // Echo the still-encoded name back in the Location
  16697. const std::string prefix = "/start/";
  16698. res.status = StatusCode::Found_302;
  16699. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16700. });
  16701. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16702. target = req.target;
  16703. res.set_content("ok", "text/plain");
  16704. });
  16705. auto port = svr.bind_to_any_port(HOST);
  16706. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16707. auto se = detail::scope_exit([&] {
  16708. svr.stop();
  16709. thread.join();
  16710. ASSERT_FALSE(svr.is_running());
  16711. });
  16712. svr.wait_until_ready();
  16713. // Decoding the Location path would turn the first four into a path
  16714. // separator, a query delimiter, a fragment delimiter and a different
  16715. // percent-encoded octet. The rest must keep reaching the server as they are.
  16716. const std::vector<std::string> names = {
  16717. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16718. };
  16719. for (auto path_encode : {true, false}) {
  16720. Client cli(HOST, port);
  16721. cli.set_follow_location(true);
  16722. cli.set_path_encode(path_encode);
  16723. for (const auto &name : names) {
  16724. target.clear();
  16725. auto res = cli.Get("/start/" + name);
  16726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16727. EXPECT_EQ(StatusCode::OK_200, res->status);
  16728. EXPECT_EQ("/dest/" + name, target);
  16729. }
  16730. }
  16731. }
  16732. TEST(RedirectTest, NotModifiedIsReturned) {
  16733. Server svr;
  16734. svr.Get("/cached", [](const Request &, Response &res) {
  16735. res.status = StatusCode::NotModified_304;
  16736. });
  16737. auto port = svr.bind_to_any_port(HOST);
  16738. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16739. auto se = detail::scope_exit([&] {
  16740. svr.stop();
  16741. thread.join();
  16742. ASSERT_FALSE(svr.is_running());
  16743. });
  16744. svr.wait_until_ready();
  16745. Client cli(HOST, port);
  16746. cli.set_follow_location(true);
  16747. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  16748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16749. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  16750. }
  16751. TEST(RedirectTest, NoLocationIsReturned) {
  16752. Server svr;
  16753. svr.Get("/no-location", [](const Request &, Response &res) {
  16754. res.status = StatusCode::Found_302;
  16755. res.set_content("no location", "text/plain");
  16756. });
  16757. auto port = svr.bind_to_any_port(HOST);
  16758. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16759. auto se = detail::scope_exit([&] {
  16760. svr.stop();
  16761. thread.join();
  16762. ASSERT_FALSE(svr.is_running());
  16763. });
  16764. svr.wait_until_ready();
  16765. Client cli(HOST, port);
  16766. cli.set_follow_location(true);
  16767. auto res = cli.Get("/no-location");
  16768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16769. EXPECT_EQ(StatusCode::Found_302, res->status);
  16770. EXPECT_EQ("no location", res->body);
  16771. // The callbacks see the body of the response that is returned
  16772. auto handler_called = false;
  16773. auto progress_called = false;
  16774. std::string body;
  16775. auto res2 = cli.Get(
  16776. "/no-location",
  16777. [&](const Response &) {
  16778. handler_called = true;
  16779. return true;
  16780. },
  16781. [&](const char *data, size_t data_length) {
  16782. body.append(data, data_length);
  16783. return true;
  16784. },
  16785. [&](size_t, size_t) {
  16786. progress_called = true;
  16787. return true;
  16788. });
  16789. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16790. EXPECT_EQ(StatusCode::Found_302, res2->status);
  16791. EXPECT_TRUE(handler_called);
  16792. EXPECT_TRUE(progress_called);
  16793. EXPECT_EQ("no location", body);
  16794. }
  16795. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16796. Server svr;
  16797. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16798. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16799. });
  16800. svr.Get("/hello", [](const Request &req, Response &res) {
  16801. res.set_content(req.get_param_value("key"), "text/plain");
  16802. });
  16803. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16804. auto se = detail::scope_exit([&] {
  16805. svr.stop();
  16806. thread.join();
  16807. ASSERT_FALSE(svr.is_running());
  16808. });
  16809. svr.wait_until_ready();
  16810. {
  16811. Client cli(HOST, PORT);
  16812. cli.set_follow_location(true);
  16813. auto res = cli.Get("/");
  16814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16815. EXPECT_EQ(StatusCode::OK_200, res->status);
  16816. EXPECT_EQ("val&key2=val2", res->body);
  16817. }
  16818. }
  16819. #endif
  16820. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16821. Server svr;
  16822. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16823. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16824. });
  16825. svr.Get("/hello", [](const Request &req, Response &res) {
  16826. res.set_content(req.get_param_value("key"), "text/plain");
  16827. });
  16828. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16829. auto se = detail::scope_exit([&] {
  16830. svr.stop();
  16831. thread.join();
  16832. ASSERT_FALSE(svr.is_running());
  16833. });
  16834. svr.wait_until_ready();
  16835. {
  16836. Client cli(HOST, PORT);
  16837. cli.set_follow_location(true);
  16838. auto res = cli.Get("/");
  16839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16840. EXPECT_EQ(StatusCode::OK_200, res->status);
  16841. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16842. }
  16843. }
  16844. TEST(RedirectTest, RedirectWithPlusInPath) {
  16845. Server svr;
  16846. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16847. res.set_redirect("/a+b");
  16848. });
  16849. // Route pattern uses regex; escape + as \\+
  16850. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16851. res.set_content(req.path, "text/plain");
  16852. });
  16853. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16854. auto se = detail::scope_exit([&] {
  16855. svr.stop();
  16856. thread.join();
  16857. ASSERT_FALSE(svr.is_running());
  16858. });
  16859. svr.wait_until_ready();
  16860. {
  16861. Client cli(HOST, PORT);
  16862. cli.set_follow_location(true);
  16863. auto res = cli.Get("/");
  16864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16865. EXPECT_EQ(StatusCode::OK_200, res->status);
  16866. EXPECT_EQ("/a+b", res->body);
  16867. }
  16868. }
  16869. TEST(RedirectTest, ResolveRelativeLocation) {
  16870. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16871. const std::vector<std::pair<std::string, std::string>> cases = {
  16872. {"g", "/b/c/g"},
  16873. {"./g", "/b/c/g"},
  16874. {"g/", "/b/c/g/"},
  16875. {"?y", "/b/c/d;p?y"},
  16876. {"g?y", "/b/c/g?y"},
  16877. {"#s", "/b/c/d;p?q#s"},
  16878. {"g#s", "/b/c/g#s"},
  16879. {"g?y#s", "/b/c/g?y#s"},
  16880. {";x", "/b/c/;x"},
  16881. {"g;x", "/b/c/g;x"},
  16882. {".", "/b/c/"},
  16883. {"./", "/b/c/"},
  16884. {"..", "/b/"},
  16885. {"../", "/b/"},
  16886. {"../g", "/b/g"},
  16887. {"../..", "/"},
  16888. {"../../", "/"},
  16889. {"../../g", "/g"},
  16890. {"../../../g", "/g"},
  16891. {"g.", "/b/c/g."},
  16892. {".g", "/b/c/.g"},
  16893. {"g..", "/b/c/g.."},
  16894. {"..g", "/b/c/..g"},
  16895. {"./../g", "/b/g"},
  16896. {"./g/.", "/b/c/g/"},
  16897. {"g/./h", "/b/c/g/h"},
  16898. {"g/../h", "/b/c/h"},
  16899. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16900. {"g;x=1/../y", "/b/c/y"},
  16901. {"g?y/./x", "/b/c/g?y/./x"},
  16902. {"g#s/../x", "/b/c/g#s/../x"},
  16903. // Not relative-path references, so left for parse_url.
  16904. {"/g", "/g"},
  16905. {"//g", "//g"},
  16906. {"http://g/x", "http://g/x"},
  16907. {"g:h", "g:h"},
  16908. };
  16909. for (const auto &c : cases) {
  16910. EXPECT_EQ(c.second,
  16911. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16912. << c.first;
  16913. }
  16914. }
  16915. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16916. Server svr;
  16917. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16918. res.set_redirect(req.get_param_value("to"));
  16919. });
  16920. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16921. res.set_content(req.target, "text/plain");
  16922. });
  16923. svr.Get("/other", [](const Request &req, Response &res) {
  16924. res.set_content(req.target, "text/plain");
  16925. });
  16926. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16927. auto se = detail::scope_exit([&] {
  16928. svr.stop();
  16929. thread.join();
  16930. ASSERT_FALSE(svr.is_running());
  16931. });
  16932. svr.wait_until_ready();
  16933. const std::vector<std::pair<std::string, std::string>> cases = {
  16934. {"next", "/dir/next"},
  16935. {"./next?x=1", "/dir/next?x=1"},
  16936. {"../other", "/other"},
  16937. };
  16938. for (const auto &c : cases) {
  16939. Client cli(HOST, PORT);
  16940. cli.set_follow_location(true);
  16941. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16942. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16943. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16944. EXPECT_EQ(c.second, res->body) << c.first;
  16945. }
  16946. }
  16947. #ifdef CPPHTTPLIB_SSL_ENABLED
  16948. TEST(RedirectTest, Issue2185_Online) {
  16949. SSLClient client("github.com");
  16950. client.set_follow_location(true);
  16951. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16952. "Coollab-Windows.zip");
  16953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16954. EXPECT_EQ(StatusCode::OK_200, res->status);
  16955. EXPECT_EQ(9920427U, res->body.size());
  16956. }
  16957. #endif
  16958. TEST(VulnerabilityTest, CRLFInjection) {
  16959. Server svr;
  16960. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16961. res.set_content("Hello 1", "text/plain");
  16962. });
  16963. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16964. res.set_content("Hello 2", "text/plain");
  16965. });
  16966. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16967. res.set_content("Hello 3", "text/plain");
  16968. });
  16969. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16970. res.set_content("Hello 4", "text/plain");
  16971. });
  16972. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16973. for (const auto &x : req.headers) {
  16974. auto key = x.first;
  16975. EXPECT_STRNE("evil", key.c_str());
  16976. }
  16977. });
  16978. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16979. auto se = detail::scope_exit([&] {
  16980. svr.stop();
  16981. thread.join();
  16982. ASSERT_FALSE(svr.is_running());
  16983. });
  16984. svr.wait_until_ready();
  16985. {
  16986. Client cli(HOST, PORT);
  16987. cli.Post("/test1", "A=B",
  16988. "application/x-www-form-urlencoded\r\nevil: hello1");
  16989. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16990. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16991. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16992. }
  16993. }
  16994. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16995. auto server_thread = std::thread([] {
  16996. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16997. default_socket_options(srv);
  16998. sockaddr_in addr{};
  16999. addr.sin_family = AF_INET;
  17000. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17001. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17002. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17003. ::listen(srv, 1);
  17004. sockaddr_in cli_addr{};
  17005. socklen_t cli_len = sizeof(cli_addr);
  17006. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17007. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17008. std::string buf_all;
  17009. char buf[2048];
  17010. ssize_t n;
  17011. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17012. buf_all.append(buf, static_cast<size_t>(n));
  17013. size_t pos;
  17014. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17015. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17016. auto e = request_block.find("\r\n");
  17017. if (e != std::string::npos) {
  17018. auto request_line = request_block.substr(0, e);
  17019. std::string msg =
  17020. "CRLF injection detected in request line: '" + request_line + "'";
  17021. EXPECT_FALSE(true) << msg;
  17022. }
  17023. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17024. ::send(cli,
  17025. #ifdef _WIN32
  17026. static_cast<const char *>(resp.c_str()),
  17027. static_cast<int>(resp.size()),
  17028. #else
  17029. resp.c_str(), resp.size(),
  17030. #endif
  17031. 0);
  17032. buf_all.erase(0, pos + 4);
  17033. }
  17034. }
  17035. detail::close_socket(cli);
  17036. detail::close_socket(srv);
  17037. });
  17038. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17039. auto cli = Client("127.0.0.1", PORT + 1);
  17040. auto headers = Headers{
  17041. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17042. {"Connection", "keep-alive"}};
  17043. auto res = cli.Get("/hi", headers);
  17044. EXPECT_FALSE(res);
  17045. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17046. server_thread.join();
  17047. }
  17048. // A request rejected before any byte reaches the socket must fail right away
  17049. // instead of waiting for a response the server will never send.
  17050. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17051. // The kernel completes the TCP handshake from the listen backlog, so the
  17052. // client connects, but nothing ever reads, responds or closes.
  17053. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17054. default_socket_options(srv);
  17055. sockaddr_in addr{};
  17056. addr.sin_family = AF_INET;
  17057. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17058. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17059. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17060. ASSERT_EQ(0, ::listen(srv, 8));
  17061. auto cli = Client("127.0.0.1", PORT + 1);
  17062. cli.set_read_timeout(10, 0);
  17063. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17064. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17065. std::chrono::steady_clock::now() - start)
  17066. .count();
  17067. };
  17068. {
  17069. Request req;
  17070. req.method = "GE T";
  17071. req.path = "/";
  17072. auto start = std::chrono::steady_clock::now();
  17073. auto res = cli.send(req);
  17074. EXPECT_FALSE(res);
  17075. EXPECT_EQ(Error::Write, res.error());
  17076. EXPECT_LT(elapsed_ms(start), 1000);
  17077. }
  17078. {
  17079. auto start = std::chrono::steady_clock::now();
  17080. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17081. EXPECT_FALSE(res);
  17082. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17083. EXPECT_LT(elapsed_ms(start), 1000);
  17084. }
  17085. EXPECT_FALSE(cli.is_socket_open());
  17086. detail::close_socket(srv);
  17087. }
  17088. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17089. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17090. default_socket_options(srv);
  17091. sockaddr_in addr{};
  17092. addr.sin_family = AF_INET;
  17093. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17094. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17095. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17096. ASSERT_EQ(0, ::listen(srv, 1));
  17097. std::string received;
  17098. auto server_thread = std::thread([&] {
  17099. auto sock = ::accept(srv, nullptr, nullptr);
  17100. if (sock == INVALID_SOCKET) { return; }
  17101. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17102. char buf[2048];
  17103. ssize_t n;
  17104. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17105. received.append(buf, static_cast<size_t>(n));
  17106. }
  17107. detail::close_socket(sock);
  17108. });
  17109. {
  17110. auto cli = Client("127.0.0.1", PORT + 1);
  17111. // "Z" sorts after the default headers, so writing straight to the socket
  17112. // would have sent the request line and those headers before the rejection.
  17113. auto handle =
  17114. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17115. EXPECT_FALSE(handle.is_valid());
  17116. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17117. }
  17118. server_thread.join();
  17119. detail::close_socket(srv);
  17120. EXPECT_TRUE(received.empty()) << received;
  17121. }
  17122. TEST(PathParamsTest, StaticMatch) {
  17123. const auto pattern = "/users/all";
  17124. detail::PathParamsMatcher matcher(pattern);
  17125. Request request;
  17126. request.path = "/users/all";
  17127. ASSERT_TRUE(matcher.match(request));
  17128. std::unordered_map<std::string, std::string> expected_params = {};
  17129. EXPECT_EQ(request.path_params, expected_params);
  17130. }
  17131. TEST(PathParamsTest, StaticMismatch) {
  17132. const auto pattern = "/users/all";
  17133. detail::PathParamsMatcher matcher(pattern);
  17134. Request request;
  17135. request.path = "/users/1";
  17136. ASSERT_FALSE(matcher.match(request));
  17137. }
  17138. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17139. const auto pattern = "/users/:id/subscriptions";
  17140. detail::PathParamsMatcher matcher(pattern);
  17141. Request request;
  17142. request.path = "/users/42/subscriptions";
  17143. ASSERT_TRUE(matcher.match(request));
  17144. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17145. EXPECT_EQ(request.path_params, expected_params);
  17146. }
  17147. TEST(PathParamsTest, SingleParamInTheEnd) {
  17148. const auto pattern = "/users/:id";
  17149. detail::PathParamsMatcher matcher(pattern);
  17150. Request request;
  17151. request.path = "/users/24";
  17152. ASSERT_TRUE(matcher.match(request));
  17153. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17154. EXPECT_EQ(request.path_params, expected_params);
  17155. }
  17156. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17157. const auto pattern = "/users/:id/";
  17158. detail::PathParamsMatcher matcher(pattern);
  17159. Request request;
  17160. request.path = "/users/42/";
  17161. ASSERT_TRUE(matcher.match(request));
  17162. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17163. EXPECT_EQ(request.path_params, expected_params);
  17164. }
  17165. TEST(PathParamsTest, EmptyParam) {
  17166. const auto pattern = "/users/:id/";
  17167. detail::PathParamsMatcher matcher(pattern);
  17168. Request request;
  17169. request.path = "/users//";
  17170. ASSERT_TRUE(matcher.match(request));
  17171. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17172. EXPECT_EQ(request.path_params, expected_params);
  17173. }
  17174. TEST(PathParamsTest, FragmentMismatch) {
  17175. const auto pattern = "/users/:id/";
  17176. detail::PathParamsMatcher matcher(pattern);
  17177. Request request;
  17178. request.path = "/admins/24/";
  17179. ASSERT_FALSE(matcher.match(request));
  17180. }
  17181. TEST(PathParamsTest, ExtraFragments) {
  17182. const auto pattern = "/users/:id";
  17183. detail::PathParamsMatcher matcher(pattern);
  17184. Request request;
  17185. request.path = "/users/42/subscriptions";
  17186. ASSERT_FALSE(matcher.match(request));
  17187. }
  17188. TEST(PathParamsTest, MissingTrailingParam) {
  17189. const auto pattern = "/users/:id";
  17190. detail::PathParamsMatcher matcher(pattern);
  17191. Request request;
  17192. request.path = "/users";
  17193. ASSERT_FALSE(matcher.match(request));
  17194. }
  17195. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17196. const auto pattern = "/users/:id/subscriptions";
  17197. detail::PathParamsMatcher matcher(pattern);
  17198. Request request;
  17199. request.path = "/users/subscriptions";
  17200. ASSERT_FALSE(matcher.match(request));
  17201. }
  17202. TEST(PathParamsTest, MultipleParams) {
  17203. const auto pattern = "/users/:userid/subscriptions/:subid";
  17204. detail::PathParamsMatcher matcher(pattern);
  17205. Request request;
  17206. request.path = "/users/42/subscriptions/2";
  17207. ASSERT_TRUE(matcher.match(request));
  17208. std::unordered_map<std::string, std::string> expected_params = {
  17209. {"userid", "42"}, {"subid", "2"}};
  17210. EXPECT_EQ(request.path_params, expected_params);
  17211. }
  17212. TEST(PathParamsTest, SequenceOfParams) {
  17213. const auto pattern = "/values/:x/:y/:z";
  17214. detail::PathParamsMatcher matcher(pattern);
  17215. Request request;
  17216. request.path = "/values/1/2/3";
  17217. ASSERT_TRUE(matcher.match(request));
  17218. std::unordered_map<std::string, std::string> expected_params = {
  17219. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17220. EXPECT_EQ(request.path_params, expected_params);
  17221. }
  17222. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17223. const auto pattern = "/prefix:suffix";
  17224. detail::PathParamsMatcher matcher(pattern);
  17225. Request request;
  17226. request.path = "/prefix:suffix";
  17227. ASSERT_TRUE(matcher.match(request));
  17228. const std::unordered_map<std::string, std::string> expected_params = {};
  17229. EXPECT_EQ(request.path_params, expected_params);
  17230. }
  17231. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17232. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17233. // calling thread's stack on a long enough path for a quantified pattern;
  17234. // RegexMatcher must refuse to run regex matching on paths beyond
  17235. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17236. detail::RegexMatcher matcher("/files/(.*)");
  17237. Request within_limit;
  17238. within_limit.path = "/files/" + std::string(10, 'A');
  17239. EXPECT_TRUE(matcher.match(within_limit));
  17240. Request over_limit;
  17241. over_limit.path =
  17242. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17243. EXPECT_FALSE(matcher.match(over_limit));
  17244. }
  17245. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17246. Server svr;
  17247. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17248. res.set_content("ok", "text/plain");
  17249. });
  17250. auto port = svr.bind_to_any_port(HOST);
  17251. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17252. auto se = detail::scope_exit([&] {
  17253. svr.stop();
  17254. thread.join();
  17255. ASSERT_FALSE(svr.is_running());
  17256. });
  17257. svr.wait_until_ready();
  17258. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17259. // request URI limit; this used to be able to crash the process.
  17260. std::string path =
  17261. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17262. std::string req = "GET " + path +
  17263. " HTTP/1.1\r\n"
  17264. "Host: " +
  17265. std::string(HOST) + ":" + std::to_string(port) +
  17266. "\r\n"
  17267. "Connection: close\r\n"
  17268. "\r\n";
  17269. std::string response;
  17270. ASSERT_TRUE(send_request(5, req, &response, port));
  17271. EXPECT_NE(std::string::npos, response.find("404"));
  17272. }
  17273. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17274. Server svr;
  17275. auto handler = [](const Request & /*req*/, Response &res) {
  17276. res.set_content("hit", "text/plain");
  17277. };
  17278. // No regex metacharacter, so this one is compared literally
  17279. svr.Get("/literal/route", handler);
  17280. // '.' is a regex metacharacter, so this one must keep regex semantics
  17281. svr.Get("/a.c", handler);
  17282. auto port = svr.bind_to_any_port(HOST);
  17283. std::thread t([&]() { svr.listen_after_bind(); });
  17284. auto se = detail::scope_exit([&] {
  17285. svr.stop();
  17286. t.join();
  17287. ASSERT_FALSE(svr.is_running());
  17288. });
  17289. svr.wait_until_ready();
  17290. Client cli(HOST, port);
  17291. struct {
  17292. const char *path;
  17293. int status;
  17294. } cases[] = {
  17295. {"/literal/route", StatusCode::OK_200},
  17296. {"/literal/routes", StatusCode::NotFound_404},
  17297. {"/literal/rout", StatusCode::NotFound_404},
  17298. {"/abc", StatusCode::OK_200},
  17299. {"/a.c", StatusCode::OK_200},
  17300. };
  17301. for (const auto &x : cases) {
  17302. auto res = cli.Get(x.path);
  17303. ASSERT_TRUE(res) << x.path;
  17304. EXPECT_EQ(x.status, res->status) << x.path;
  17305. }
  17306. }
  17307. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17308. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17309. // from exhausting the stack, so it must only constrain routes that actually
  17310. // run a regular expression. A literal route is matched by comparison and
  17311. // stays usable at any length.
  17312. Server svr;
  17313. const std::string pattern =
  17314. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17315. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17316. res.set_content("hit", "text/plain");
  17317. });
  17318. auto port = svr.bind_to_any_port(HOST);
  17319. std::thread t([&]() { svr.listen_after_bind(); });
  17320. auto se = detail::scope_exit([&] {
  17321. svr.stop();
  17322. t.join();
  17323. ASSERT_FALSE(svr.is_running());
  17324. });
  17325. svr.wait_until_ready();
  17326. Client cli(HOST, port);
  17327. auto res = cli.Get(pattern);
  17328. ASSERT_TRUE(res);
  17329. EXPECT_EQ(StatusCode::OK_200, res->status);
  17330. }
  17331. TEST(ParseUrlTest, VariousPatterns) {
  17332. {
  17333. detail::UrlComponents uc;
  17334. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17335. EXPECT_EQ("http", uc.scheme);
  17336. EXPECT_EQ("example.com", uc.host);
  17337. EXPECT_EQ("8080", uc.port);
  17338. EXPECT_EQ("/path", uc.path);
  17339. EXPECT_EQ("?q=1", uc.query);
  17340. }
  17341. {
  17342. detail::UrlComponents uc;
  17343. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17344. EXPECT_EQ("https", uc.scheme);
  17345. EXPECT_EQ("example.com", uc.host);
  17346. EXPECT_TRUE(uc.port.empty());
  17347. EXPECT_EQ("/path", uc.path);
  17348. }
  17349. {
  17350. detail::UrlComponents uc;
  17351. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17352. EXPECT_EQ("::1", uc.host);
  17353. EXPECT_EQ("8080", uc.port);
  17354. EXPECT_EQ("/path", uc.path);
  17355. }
  17356. {
  17357. detail::UrlComponents uc;
  17358. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17359. }
  17360. {
  17361. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17362. // the path while the connection still targets the bracketed host.
  17363. detail::UrlComponents uc;
  17364. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17365. }
  17366. {
  17367. detail::UrlComponents uc;
  17368. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17369. }
  17370. {
  17371. detail::UrlComponents uc;
  17372. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17373. EXPECT_EQ("::1", uc.host);
  17374. EXPECT_TRUE(uc.port.empty());
  17375. EXPECT_EQ("/path", uc.path);
  17376. }
  17377. {
  17378. detail::UrlComponents uc;
  17379. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17380. EXPECT_TRUE(uc.scheme.empty());
  17381. EXPECT_EQ("example.com", uc.host);
  17382. EXPECT_EQ("/path", uc.path);
  17383. EXPECT_EQ("?q=1", uc.query);
  17384. }
  17385. {
  17386. detail::UrlComponents uc;
  17387. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17388. EXPECT_TRUE(uc.host.empty());
  17389. EXPECT_EQ("/path", uc.path);
  17390. EXPECT_EQ("?q=1", uc.query);
  17391. }
  17392. {
  17393. detail::UrlComponents uc;
  17394. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17395. EXPECT_EQ("example.com", uc.host);
  17396. EXPECT_EQ("8080", uc.port);
  17397. }
  17398. {
  17399. // Unix socket path — must not be parsed as host
  17400. detail::UrlComponents uc;
  17401. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17402. EXPECT_TRUE(uc.host.empty());
  17403. }
  17404. {
  17405. detail::UrlComponents uc;
  17406. ASSERT_TRUE(detail::parse_url("", uc));
  17407. EXPECT_TRUE(uc.host.empty());
  17408. EXPECT_TRUE(uc.path.empty());
  17409. }
  17410. {
  17411. detail::UrlComponents uc;
  17412. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17413. }
  17414. {
  17415. detail::UrlComponents uc;
  17416. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17417. }
  17418. {
  17419. // Accepted by parse_url; callers restrict to http/https
  17420. detail::UrlComponents uc;
  17421. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17422. EXPECT_EQ("ftp", uc.scheme);
  17423. }
  17424. {
  17425. detail::UrlComponents uc;
  17426. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17427. }
  17428. {
  17429. detail::UrlComponents uc;
  17430. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17431. }
  17432. }
  17433. TEST(ParseUrlTest, FragmentHandling) {
  17434. {
  17435. detail::UrlComponents uc;
  17436. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17437. EXPECT_EQ("/path", uc.path);
  17438. EXPECT_TRUE(uc.query.empty());
  17439. }
  17440. {
  17441. detail::UrlComponents uc;
  17442. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17443. EXPECT_TRUE(uc.path.empty());
  17444. EXPECT_TRUE(uc.query.empty());
  17445. }
  17446. }
  17447. TEST(ParseUrlTest, UserinfoHandling) {
  17448. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17449. // parsers would see evil.com as the host.
  17450. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17451. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17452. for (auto url : urls) {
  17453. detail::UrlComponents uc;
  17454. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17455. }
  17456. }
  17457. TEST(ParseUrlTest, IPv6EdgeCases) {
  17458. {
  17459. detail::UrlComponents uc;
  17460. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17461. EXPECT_TRUE(uc.scheme.empty());
  17462. EXPECT_EQ("::1", uc.host);
  17463. EXPECT_EQ("8080", uc.port);
  17464. }
  17465. {
  17466. // Zone ID '%25' is not in [a-fA-F0-9:]
  17467. detail::UrlComponents uc;
  17468. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17469. }
  17470. }
  17471. TEST(ParseUrlTest, SchemeEdgeCases) {
  17472. {
  17473. detail::UrlComponents uc;
  17474. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17475. }
  17476. {
  17477. detail::UrlComponents uc;
  17478. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17479. }
  17480. {
  17481. detail::UrlComponents uc;
  17482. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17483. }
  17484. }
  17485. TEST(ParseUrlTest, PortEdgeCases) {
  17486. {
  17487. detail::UrlComponents uc;
  17488. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17489. EXPECT_TRUE(uc.port.empty());
  17490. EXPECT_EQ("/path", uc.path);
  17491. }
  17492. {
  17493. // parse_url accepts any port string; validation is done by parse_port
  17494. detail::UrlComponents uc;
  17495. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17496. EXPECT_EQ("abc", uc.port);
  17497. }
  17498. }
  17499. TEST(ParseUrlTest, WebSocketPatterns) {
  17500. {
  17501. detail::UrlComponents uc;
  17502. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17503. EXPECT_EQ("ws", uc.scheme);
  17504. EXPECT_EQ("echo.example.com", uc.host);
  17505. EXPECT_EQ("8080", uc.port);
  17506. EXPECT_EQ("/ws", uc.path);
  17507. }
  17508. {
  17509. detail::UrlComponents uc;
  17510. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17511. EXPECT_EQ("wss", uc.scheme);
  17512. EXPECT_EQ("echo.example.com", uc.host);
  17513. EXPECT_TRUE(uc.port.empty());
  17514. EXPECT_EQ("/ws", uc.path);
  17515. }
  17516. }
  17517. TEST(ParseUrlTest, QueryOnly) {
  17518. detail::UrlComponents uc;
  17519. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17520. EXPECT_TRUE(uc.host.empty());
  17521. EXPECT_TRUE(uc.path.empty());
  17522. EXPECT_EQ("?q=1&r=2", uc.query);
  17523. }
  17524. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17525. detail::UrlComponents uc;
  17526. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17527. EXPECT_TRUE(uc.scheme.empty());
  17528. EXPECT_EQ("example.com", uc.host);
  17529. EXPECT_EQ("443", uc.port);
  17530. EXPECT_EQ("/path", uc.path);
  17531. }
  17532. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17533. // If ipv6 regex working, regex match codepath is taken.
  17534. // else port will default to 80 in Client impl
  17535. int clientImplMagicPort = 80;
  17536. int port = 4321;
  17537. // above ports must be different to avoid false negative
  17538. EXPECT_NE(clientImplMagicPort, port);
  17539. std::string ipV6TestURL = "http://[ff06::c3]";
  17540. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17541. CLIENT_PRIVATE_KEY_FILE);
  17542. EXPECT_EQ(cli.port(), port);
  17543. }
  17544. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17545. auto file_path = "./www/dir/index.html";
  17546. auto dir_path = "./www/dir";
  17547. detail::FileStat stat_file(file_path);
  17548. EXPECT_TRUE(stat_file.is_file());
  17549. EXPECT_FALSE(stat_file.is_dir());
  17550. detail::FileStat stat_dir(dir_path);
  17551. EXPECT_FALSE(stat_dir.is_file());
  17552. EXPECT_TRUE(stat_dir.is_dir());
  17553. }
  17554. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17555. // IPv4 with default HTTP port (80)
  17556. EXPECT_EQ("example.com",
  17557. detail::make_host_and_port_string("example.com", 80, false));
  17558. // IPv4 with default HTTPS port (443)
  17559. EXPECT_EQ("example.com",
  17560. detail::make_host_and_port_string("example.com", 443, true));
  17561. // IPv4 with non-default HTTP port
  17562. EXPECT_EQ("example.com:8080",
  17563. detail::make_host_and_port_string("example.com", 8080, false));
  17564. // IPv4 with non-default HTTPS port
  17565. EXPECT_EQ("example.com:8443",
  17566. detail::make_host_and_port_string("example.com", 8443, true));
  17567. // IPv6 with default HTTP port (80)
  17568. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17569. // IPv6 with default HTTPS port (443)
  17570. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17571. // IPv6 with non-default HTTP port
  17572. EXPECT_EQ("[::1]:8080",
  17573. detail::make_host_and_port_string("::1", 8080, false));
  17574. // IPv6 with non-default HTTPS port
  17575. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17576. // IPv6 full address with default port
  17577. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17578. detail::make_host_and_port_string(
  17579. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17580. // IPv6 full address with non-default port
  17581. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17582. detail::make_host_and_port_string(
  17583. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17584. // IPv6 localhost with non-default port
  17585. EXPECT_EQ("[::1]:3000",
  17586. detail::make_host_and_port_string("::1", 3000, false));
  17587. // IPv6 with zone ID (link-local address) with default port
  17588. EXPECT_EQ("[fe80::1%eth0]",
  17589. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17590. // IPv6 with zone ID (link-local address) with non-default port
  17591. EXPECT_EQ("[fe80::1%eth0]:8080",
  17592. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17593. // Edge case: Port 443 with is_ssl=false (should add port)
  17594. EXPECT_EQ("example.com:443",
  17595. detail::make_host_and_port_string("example.com", 443, false));
  17596. // Edge case: Port 80 with is_ssl=true (should add port)
  17597. EXPECT_EQ("example.com:80",
  17598. detail::make_host_and_port_string("example.com", 80, true));
  17599. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17600. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17601. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17602. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17603. // Security fix: Already bracketed IPv6 should not get double brackets
  17604. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17605. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17606. EXPECT_EQ("[::1]:8080",
  17607. detail::make_host_and_port_string("[::1]", 8080, false));
  17608. EXPECT_EQ("[2001:db8::1]:8080",
  17609. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17610. EXPECT_EQ("[fe80::1%eth0]",
  17611. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17612. EXPECT_EQ("[fe80::1%eth0]:8080",
  17613. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17614. // Edge case: Empty host (should return as-is)
  17615. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17616. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17617. // This is a known limitation but shouldn't crash
  17618. EXPECT_EQ("[host:name]",
  17619. detail::make_host_and_port_string("host:name", 80, false));
  17620. // Port number edge cases (no validation, but should not crash)
  17621. EXPECT_EQ("example.com:0",
  17622. detail::make_host_and_port_string("example.com", 0, false));
  17623. EXPECT_EQ("example.com:-1",
  17624. detail::make_host_and_port_string("example.com", -1, false));
  17625. EXPECT_EQ("example.com:65535",
  17626. detail::make_host_and_port_string("example.com", 65535, false));
  17627. EXPECT_EQ("example.com:65536",
  17628. detail::make_host_and_port_string("example.com", 65536, false));
  17629. }
  17630. #ifdef CPPHTTPLIB_SSL_ENABLED
  17631. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17632. httplib::SSLClient cli("roblox.com", 443);
  17633. cli.set_follow_location(true);
  17634. auto res = cli.Get("/");
  17635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17636. EXPECT_EQ(StatusCode::OK_200, res->status);
  17637. }
  17638. #endif
  17639. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17640. Server svr;
  17641. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17642. EXPECT_EQ(res.status, 400);
  17643. });
  17644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17645. auto se = detail::scope_exit([&] {
  17646. svr.stop();
  17647. thread.join();
  17648. ASSERT_FALSE(svr.is_running());
  17649. });
  17650. svr.wait_until_ready();
  17651. Client cli(HOST, PORT);
  17652. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17653. }
  17654. TEST(InvalidHeaderCharsTest, is_field_name) {
  17655. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17656. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17657. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17658. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17659. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17660. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17661. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17662. EXPECT_FALSE(detail::fields::is_field_name(""));
  17663. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17664. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17665. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17666. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17667. }
  17668. TEST(InvalidHeaderCharsTest, is_field_value) {
  17669. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17670. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17671. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17672. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17673. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17674. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17675. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17676. EXPECT_TRUE(detail::fields::is_field_value(""));
  17677. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17678. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17679. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17680. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17681. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17682. }
  17683. TEST(InvalidHeaderCharsTest, OnServer) {
  17684. Server svr;
  17685. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17686. std::string header = "Not Set";
  17687. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17688. res.set_header(header, "value");
  17689. res.set_content("Page Content Page Content", "text/plain");
  17690. });
  17691. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17692. std::string header = "Not Set";
  17693. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17694. res.set_header("X-Test", header);
  17695. res.set_content("Page Content Page Content", "text/plain");
  17696. });
  17697. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17698. auto se = detail::scope_exit([&] {
  17699. svr.stop();
  17700. thread.join();
  17701. ASSERT_FALSE(svr.is_running());
  17702. });
  17703. svr.wait_until_ready();
  17704. Client cli(HOST, PORT);
  17705. {
  17706. auto res = cli.Get(
  17707. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17709. EXPECT_EQ("Page Content Page Content", res->body);
  17710. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17711. }
  17712. {
  17713. auto res = cli.Get(
  17714. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17716. EXPECT_EQ("Page Content Page Content", res->body);
  17717. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17718. }
  17719. }
  17720. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17721. auto handled = false;
  17722. Server svr;
  17723. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17724. thread t = thread([&] { svr.listen(HOST, PORT); });
  17725. auto se = detail::scope_exit([&] {
  17726. svr.stop();
  17727. t.join();
  17728. ASSERT_FALSE(svr.is_running());
  17729. ASSERT_FALSE(handled);
  17730. });
  17731. svr.wait_until_ready();
  17732. auto req = "POST /test HTTP/1.1\r\n"
  17733. "Content-Length: x\r\n"
  17734. "\r\n";
  17735. std::string response;
  17736. ASSERT_TRUE(send_request(1, req, &response));
  17737. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17738. response.substr(0, response.find("\r\n")));
  17739. }
  17740. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17741. // case-insensitive, and a server that receives a 100-continue expectation in
  17742. // an HTTP/1.0 request MUST ignore it.
  17743. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17744. std::string response;
  17745. ASSERT_TRUE(send_request(1, req, &response, port));
  17746. *got_100 = response.find("100 Continue") != std::string::npos;
  17747. }
  17748. class ExpectTokenTest : public ::testing::Test {
  17749. protected:
  17750. void SetUp() override {
  17751. svr_.Post("/p", [](const Request &, Response &res) {
  17752. res.set_content("ok", "text/plain");
  17753. });
  17754. port_ = svr_.bind_to_any_port(HOST);
  17755. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17756. svr_.wait_until_ready();
  17757. }
  17758. void TearDown() override {
  17759. svr_.stop();
  17760. if (thread_.joinable()) { thread_.join(); }
  17761. }
  17762. std::string request(const char *version, const char *expect_value) const {
  17763. return std::string("POST /p ") + version +
  17764. "\r\n"
  17765. "Host: localhost\r\n"
  17766. "Content-Length: 2\r\n"
  17767. "Connection: close\r\n"
  17768. "Expect: " +
  17769. expect_value +
  17770. "\r\n"
  17771. "\r\n"
  17772. "hi";
  17773. }
  17774. Server svr_;
  17775. int port_ = 0;
  17776. thread thread_;
  17777. };
  17778. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17779. bool got_100 = false;
  17780. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17781. EXPECT_TRUE(got_100);
  17782. }
  17783. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17784. bool got_100 = true;
  17785. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17786. EXPECT_FALSE(got_100);
  17787. }
  17788. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17789. bool got_100 = false;
  17790. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17791. EXPECT_TRUE(got_100);
  17792. }
  17793. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17794. bool got_100 = false;
  17795. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17796. EXPECT_TRUE(got_100);
  17797. }
  17798. // `100 Continue` is sent only when the server starts reading the body, so a
  17799. // request rejected before that never invites the client to send it. The
  17800. // requests below carry the expectation but withhold the body, as a client
  17801. // waiting for `100 Continue` would.
  17802. // A POST that expects `100 Continue` and withholds its two-byte body.
  17803. static std::string expect_headers_only(const std::string &path) {
  17804. return "POST " + path +
  17805. " HTTP/1.1\r\n"
  17806. "Host: localhost\r\n"
  17807. "Content-Length: 2\r\n"
  17808. "Expect: 100-continue\r\n"
  17809. "\r\n";
  17810. }
  17811. class ExpectLazyContinueTest : public ::testing::Test {
  17812. protected:
  17813. void SetUp() override {
  17814. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17815. if (req.path == "/pre-routing") {
  17816. res.status = StatusCode::Unauthorized_401;
  17817. return Server::HandlerResponse::Handled;
  17818. }
  17819. return Server::HandlerResponse::Unhandled;
  17820. });
  17821. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17822. if (req.matched_route == "/pre-request") {
  17823. res.status = StatusCode::Forbidden_403;
  17824. return Server::HandlerResponse::Handled;
  17825. }
  17826. return Server::HandlerResponse::Unhandled;
  17827. });
  17828. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17829. res.set_content("ok", "text/plain");
  17830. });
  17831. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17832. res.set_content("ok", "text/plain");
  17833. });
  17834. svr_.Post("/reader-used", [](const Request &, Response &res,
  17835. const ContentReader &content_reader) {
  17836. std::string body;
  17837. content_reader([&](const char *data, size_t len) {
  17838. body.append(data, len);
  17839. return true;
  17840. });
  17841. res.set_content(body, "text/plain");
  17842. });
  17843. svr_.Post("/reader-unused",
  17844. [](const Request &, Response &res, const ContentReader &) {
  17845. res.set_content("ignored", "text/plain");
  17846. });
  17847. port_ = svr_.bind_to_any_port(HOST);
  17848. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17849. svr_.wait_until_ready();
  17850. }
  17851. void TearDown() override {
  17852. svr_.stop();
  17853. if (thread_.joinable()) { thread_.join(); }
  17854. }
  17855. // Sends `req` and reads until the server closes the connection. Returns
  17856. // false if the read had to wait for the client-side timeout instead.
  17857. bool send_until_closed(const std::string &req, std::string *resp) const {
  17858. auto start = std::chrono::steady_clock::now();
  17859. if (!send_request(3, req, resp, port_)) { return false; }
  17860. auto elapsed = std::chrono::steady_clock::now() - start;
  17861. return elapsed < std::chrono::seconds(2);
  17862. }
  17863. // The final response comes without `100 Continue`, and the server closes
  17864. // the connection since the body may or may not follow.
  17865. void expect_final_without_interim(const std::string &path,
  17866. const char *status_line) const {
  17867. std::string resp;
  17868. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17869. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17870. EXPECT_EQ(0u, resp.find(status_line));
  17871. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17872. }
  17873. Server svr_;
  17874. int port_ = 0;
  17875. thread thread_;
  17876. };
  17877. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17878. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17879. }
  17880. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17881. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17882. }
  17883. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17884. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17885. }
  17886. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17887. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17888. }
  17889. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17890. // The body follows once `100 Continue` has had time to arrive.
  17891. auto req = expect_headers_only("/reader-used");
  17892. req.insert(req.size() - 2, "Connection: close\r\n");
  17893. std::string resp;
  17894. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17895. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17896. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17897. EXPECT_NE(std::string::npos, resp.find("hi"));
  17898. }
  17899. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17900. // Large enough for the client to add `Expect: 100-continue` itself.
  17901. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17902. std::atomic<bool> body_sent{false};
  17903. Client cli(HOST, port_);
  17904. auto res = cli.Post(
  17905. "/pre-request", length,
  17906. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17907. body_sent = true;
  17908. std::string chunk(len, 'x');
  17909. sink.write(chunk.data(), chunk.size());
  17910. return true;
  17911. },
  17912. "application/octet-stream");
  17913. ASSERT_TRUE(res);
  17914. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17915. EXPECT_FALSE(body_sent);
  17916. }
  17917. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17918. Server svr;
  17919. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17920. return StatusCode::ExpectationFailed_417;
  17921. });
  17922. svr.Post("/p", [](const Request &, Response &res) {
  17923. res.set_content("ok", "text/plain");
  17924. });
  17925. auto port = svr.bind_to_any_port(HOST);
  17926. thread t = thread([&] { svr.listen_after_bind(); });
  17927. auto se = detail::scope_exit([&] {
  17928. svr.stop();
  17929. t.join();
  17930. });
  17931. svr.wait_until_ready();
  17932. std::string resp;
  17933. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17934. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17935. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17936. // Exactly one response: the route handler must not run after the 417.
  17937. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17938. }
  17939. #ifndef _WIN32
  17940. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17941. static constexpr char reject[] = "Unauthorized";
  17942. static constexpr char accept[] = "Upload accepted";
  17943. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17944. Server svr;
  17945. svr.set_expect_100_continue_handler(
  17946. [](const Request & /*req*/, Response &res) {
  17947. res.status = StatusCode::Unauthorized_401;
  17948. res.set_content(reject, "text/plain");
  17949. return res.status;
  17950. });
  17951. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17952. res.set_content(accept, "text/plain");
  17953. });
  17954. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17955. auto se = detail::scope_exit([&] {
  17956. svr.stop();
  17957. thread.join();
  17958. ASSERT_FALSE(svr.is_running());
  17959. });
  17960. svr.wait_until_ready();
  17961. {
  17962. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17963. curl_easy_init(), &curl_easy_cleanup};
  17964. ASSERT_NE(curl, nullptr);
  17965. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17966. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17967. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17968. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17969. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17970. &curl_slist_free_all};
  17971. ASSERT_NE(list, nullptr);
  17972. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17973. struct read_data {
  17974. uint64_t read_size;
  17975. uint64_t total_size;
  17976. } data = {0, total_size};
  17977. using read_callback_t =
  17978. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17979. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17980. void *userdata) -> size_t {
  17981. read_data *d = (read_data *)userdata;
  17982. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17983. std::fill_n(ptr, size * nmemb, 'A');
  17984. d->read_size += size * nmemb;
  17985. return size * nmemb;
  17986. };
  17987. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  17988. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17989. std::vector<char> buffer;
  17990. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17991. using write_callback_t =
  17992. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17993. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17994. void *userdata) -> size_t {
  17995. std::vector<char> *buf = (std::vector<char> *)userdata;
  17996. buf->reserve(buf->size() + size * nmemb + 1);
  17997. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17998. return size * nmemb;
  17999. };
  18000. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18001. {
  18002. const auto res = curl_easy_perform(curl.get());
  18003. ASSERT_EQ(res, CURLE_OK);
  18004. }
  18005. {
  18006. auto response_code = long{};
  18007. const auto res =
  18008. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18009. ASSERT_EQ(res, CURLE_OK);
  18010. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18011. }
  18012. {
  18013. auto dl = curl_off_t{};
  18014. const auto res =
  18015. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18016. ASSERT_EQ(res, CURLE_OK);
  18017. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18018. }
  18019. {
  18020. buffer.push_back('\0');
  18021. ASSERT_STRCASEEQ(buffer.data(), reject);
  18022. }
  18023. }
  18024. }
  18025. #endif
  18026. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18027. // Regression test for #2458.
  18028. //
  18029. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18030. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18031. // ticket can make the client socket spuriously readable during the
  18032. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18033. // the client withholds the body and then blocks reading a response that never
  18034. // comes, failing with `Failed to read connection`.
  18035. //
  18036. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18037. // within the timeout. This raw OpenSSL server deliberately never sends
  18038. // `100 Continue`; the client must still deliver the body and receive 200.
  18039. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18040. signal(SIGPIPE, SIG_IGN);
  18041. const auto port = PORT + 4;
  18042. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18043. ASSERT_NE(srv, INVALID_SOCKET);
  18044. int opt = 1;
  18045. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18046. sockaddr_in addr{};
  18047. addr.sin_family = AF_INET;
  18048. addr.sin_port = htons(static_cast<uint16_t>(port));
  18049. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18050. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18051. ASSERT_EQ(0, ::listen(srv, 1));
  18052. std::atomic<size_t> server_body_bytes{0};
  18053. auto server_thread = std::thread([&] {
  18054. sockaddr_in cli_addr{};
  18055. socklen_t cli_len = sizeof(cli_addr);
  18056. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18057. if (cli == INVALID_SOCKET) { return; }
  18058. // Bound the lifetime of the server side so a buggy client (which never
  18059. // sends the body) cannot make this thread block forever on join.
  18060. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18061. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18062. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18063. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18064. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18065. SSL *ssl = SSL_new(ctx);
  18066. SSL_set_fd(ssl, static_cast<int>(cli));
  18067. if (SSL_accept(ssl) > 0) {
  18068. // Read the request headers. Reading here also flushes the TLS 1.3
  18069. // session tickets to the client. Deliberately do NOT send
  18070. // `100 Continue`.
  18071. std::string buf;
  18072. char tmp[1024];
  18073. while (buf.find("\r\n\r\n") == std::string::npos) {
  18074. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18075. if (n <= 0) { break; }
  18076. buf.append(tmp, static_cast<size_t>(n));
  18077. }
  18078. // A correct client sends the body now; count what arrives.
  18079. auto pos = buf.find("\r\n\r\n");
  18080. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18081. while (body < 4096) {
  18082. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18083. if (n <= 0) { break; }
  18084. body += static_cast<size_t>(n);
  18085. }
  18086. server_body_bytes = body;
  18087. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18088. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18089. SSL_shutdown(ssl);
  18090. }
  18091. SSL_free(ssl);
  18092. detail::close_socket(cli);
  18093. SSL_CTX_free(ctx);
  18094. });
  18095. auto se = detail::scope_exit([&] {
  18096. server_thread.join();
  18097. detail::close_socket(srv);
  18098. });
  18099. SSLClient cli("127.0.0.1", port);
  18100. cli.enable_server_certificate_verification(false);
  18101. cli.set_connection_timeout(5, 0);
  18102. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18103. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18104. std::string body(4096, 'A');
  18105. auto res = cli.Put("/api/test", body, "application/json");
  18106. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18107. EXPECT_EQ(StatusCode::OK_200, res->status);
  18108. EXPECT_EQ(body.size(), server_body_bytes.load());
  18109. }
  18110. #endif
  18111. template <typename S, typename C>
  18112. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18113. svr.Get("/stream", [&](const Request &, Response &res) {
  18114. auto data = new std::string("01234567890123456789");
  18115. res.set_content_provider(
  18116. data->size(), "text/plain",
  18117. [&, data](size_t offset, size_t length, DataSink &sink) {
  18118. const size_t DATA_CHUNK_SIZE = 4;
  18119. const auto &d = *data;
  18120. std::this_thread::sleep_for(std::chrono::seconds(1));
  18121. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18122. return true;
  18123. },
  18124. [data](bool success) {
  18125. EXPECT_FALSE(success);
  18126. delete data;
  18127. });
  18128. });
  18129. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18130. auto i = new size_t(0);
  18131. res.set_content_provider(
  18132. "text/plain",
  18133. [i](size_t, DataSink &sink) {
  18134. if (*i < 5) {
  18135. std::this_thread::sleep_for(std::chrono::seconds(1));
  18136. sink.write("abcd", 4);
  18137. (*i)++;
  18138. } else {
  18139. sink.done();
  18140. }
  18141. return true;
  18142. },
  18143. [i](bool success) {
  18144. EXPECT_FALSE(success);
  18145. delete i;
  18146. });
  18147. });
  18148. svr.Get("/chunked", [&](const Request &, Response &res) {
  18149. auto i = new size_t(0);
  18150. res.set_chunked_content_provider(
  18151. "text/plain",
  18152. [i](size_t, DataSink &sink) {
  18153. if (*i < 5) {
  18154. std::this_thread::sleep_for(std::chrono::seconds(1));
  18155. sink.os << "abcd";
  18156. (*i)++;
  18157. } else {
  18158. sink.done();
  18159. }
  18160. return true;
  18161. },
  18162. [i](bool success) {
  18163. EXPECT_FALSE(success);
  18164. delete i;
  18165. });
  18166. });
  18167. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18168. auto se = detail::scope_exit([&] {
  18169. svr.stop();
  18170. listen_thread.join();
  18171. ASSERT_FALSE(svr.is_running());
  18172. });
  18173. svr.wait_until_ready();
  18174. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18175. {
  18176. auto start = std::chrono::steady_clock::now();
  18177. auto res = cli.Get("/stream");
  18178. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18179. std::chrono::steady_clock::now() - start)
  18180. .count();
  18181. ASSERT_FALSE(res);
  18182. EXPECT_EQ(Error::Read, res.error());
  18183. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18184. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18185. }
  18186. {
  18187. auto start = std::chrono::steady_clock::now();
  18188. auto res = cli.Get("/stream_without_length");
  18189. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18190. std::chrono::steady_clock::now() - start)
  18191. .count();
  18192. ASSERT_FALSE(res);
  18193. EXPECT_EQ(Error::Read, res.error());
  18194. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18195. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18196. }
  18197. {
  18198. auto start = std::chrono::steady_clock::now();
  18199. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18200. EXPECT_EQ("abcd", string(data, data_length));
  18201. return true;
  18202. });
  18203. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18204. std::chrono::steady_clock::now() - start)
  18205. .count();
  18206. ASSERT_FALSE(res);
  18207. EXPECT_EQ(Error::Read, res.error());
  18208. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18209. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18210. }
  18211. }
  18212. TEST(MaxTimeoutTest, ContentStream) {
  18213. time_t timeout = 2000;
  18214. time_t threshold = 200;
  18215. Server svr;
  18216. Client cli("localhost", PORT);
  18217. max_timeout_test(svr, cli, timeout, threshold);
  18218. }
  18219. #ifdef CPPHTTPLIB_SSL_ENABLED
  18220. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18221. time_t timeout = 2000;
  18222. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18224. SSLClient cli("localhost", PORT);
  18225. cli.enable_server_certificate_verification(false);
  18226. max_timeout_test(svr, cli, timeout, threshold);
  18227. }
  18228. #endif
  18229. class EventDispatcher {
  18230. public:
  18231. EventDispatcher() {}
  18232. bool wait_event(DataSink *sink) {
  18233. unique_lock<mutex> lk(m_);
  18234. int id = id_;
  18235. // Wait with timeout to prevent hanging if client disconnects
  18236. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18237. [&] { return cid_ == id; })) {
  18238. return false; // Timeout occurred
  18239. }
  18240. sink->write(message_.data(), message_.size());
  18241. return true;
  18242. }
  18243. void send_event(const string &message) {
  18244. lock_guard<mutex> lk(m_);
  18245. cid_ = id_++;
  18246. message_ = message;
  18247. cv_.notify_all();
  18248. }
  18249. private:
  18250. mutex m_;
  18251. condition_variable cv_;
  18252. atomic_int id_{0};
  18253. atomic_int cid_{-1};
  18254. string message_;
  18255. };
  18256. TEST(ClientInThreadTest, Issue2068) {
  18257. EventDispatcher ed;
  18258. Server svr;
  18259. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18260. res.set_chunked_content_provider("text/event-stream",
  18261. [&](size_t /*offset*/, DataSink &sink) {
  18262. return ed.wait_event(&sink);
  18263. });
  18264. });
  18265. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18266. svr.wait_until_ready();
  18267. thread event_thread([&] {
  18268. int id = 0;
  18269. while (svr.is_running()) {
  18270. this_thread::sleep_for(chrono::milliseconds(500));
  18271. std::stringstream ss;
  18272. ss << "data: " << id << "\n\n";
  18273. ed.send_event(ss.str());
  18274. id++;
  18275. }
  18276. });
  18277. auto se = detail::scope_exit([&] {
  18278. svr.stop();
  18279. listen_thread.join();
  18280. event_thread.join();
  18281. ASSERT_FALSE(svr.is_running());
  18282. });
  18283. {
  18284. auto client = detail::make_unique<Client>(HOST, PORT);
  18285. client->set_read_timeout(std::chrono::minutes(10));
  18286. std::atomic<bool> stop{false};
  18287. std::thread t([&] {
  18288. client->Get("/event1",
  18289. [&](const char *, size_t) -> bool { return !stop; });
  18290. });
  18291. std::this_thread::sleep_for(std::chrono::seconds(2));
  18292. stop = true;
  18293. client->stop();
  18294. t.join();
  18295. // Reset client after thread has finished
  18296. client.reset();
  18297. }
  18298. }
  18299. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18300. auto handled = false;
  18301. Server svr;
  18302. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18303. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18304. auto se = detail::scope_exit([&] {
  18305. svr.stop();
  18306. t.join();
  18307. ASSERT_FALSE(svr.is_running());
  18308. ASSERT_FALSE(handled);
  18309. });
  18310. svr.wait_until_ready();
  18311. // Two Content-Length headers with different values — must be rejected
  18312. auto req = "POST /test HTTP/1.1\r\n"
  18313. "Content-Length: 5\r\n"
  18314. "Content-Length: 10\r\n"
  18315. "\r\n"
  18316. "hello";
  18317. std::string response;
  18318. ASSERT_TRUE(send_request(1, req, &response));
  18319. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18320. response.substr(0, response.find("\r\n")));
  18321. }
  18322. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18323. auto handled = false;
  18324. Server svr;
  18325. svr.Post("/test", [&](const Request &, Response &res) {
  18326. handled = true;
  18327. res.set_content("ok", "text/plain");
  18328. });
  18329. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18330. auto se = detail::scope_exit([&] {
  18331. svr.stop();
  18332. t.join();
  18333. ASSERT_FALSE(svr.is_running());
  18334. ASSERT_TRUE(handled);
  18335. });
  18336. svr.wait_until_ready();
  18337. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18338. auto req = "POST /test HTTP/1.1\r\n"
  18339. "Host: localhost\r\n"
  18340. "Content-Length: 5\r\n"
  18341. "Content-Length: 5\r\n"
  18342. "\r\n"
  18343. "hello";
  18344. std::string response;
  18345. ASSERT_TRUE(send_request(1, req, &response));
  18346. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18347. }
  18348. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18349. Server svr;
  18350. svr.Get("/test", [](const Request &, Response &res) {
  18351. res.set_content("ok", "text/plain");
  18352. });
  18353. auto port = svr.bind_to_any_port(HOST);
  18354. thread t = thread([&] { svr.listen_after_bind(); });
  18355. auto se = detail::scope_exit([&] {
  18356. svr.stop();
  18357. t.join();
  18358. ASSERT_FALSE(svr.is_running());
  18359. });
  18360. svr.wait_until_ready();
  18361. auto status_line = [&](const std::string &host_lines) {
  18362. std::string res;
  18363. send_request(
  18364. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18365. &res, port);
  18366. return res.substr(0, res.find("\r\n"));
  18367. };
  18368. const char *accepted[] = {
  18369. "Host: localhost\r\n",
  18370. "Host: a.example:8080\r\n",
  18371. "Host: my_service\r\n",
  18372. "Host: [::1]:8080\r\n",
  18373. "Host: [fe80::1%25eth0]\r\n",
  18374. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18375. };
  18376. for (auto host_lines : accepted) {
  18377. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18378. }
  18379. const char *rejected[] = {
  18380. "Host: a.example\r\nHost: b.example\r\n",
  18381. "Host: a.example\r\nHost: a.example\r\n",
  18382. "Host: a@b.example\r\n",
  18383. "Host: a.example/b\r\n",
  18384. "Host: a.example\\b\r\n",
  18385. "Host: a.example?b\r\n",
  18386. "Host: a.example#b\r\n",
  18387. "Host: a.example b.example\r\n",
  18388. };
  18389. for (auto host_lines : rejected) {
  18390. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18391. << host_lines;
  18392. }
  18393. }
  18394. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18395. Server svr;
  18396. svr.Get("/", [](const Request &req, Response &res) {
  18397. EXPECT_EQ(2U, req.trailers.size());
  18398. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18399. // Denied
  18400. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18401. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18402. // Accepted
  18403. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18404. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18405. EXPECT_TRUE(req.has_trailer("X-World"));
  18406. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18407. res.set_content("ok", "text/plain");
  18408. });
  18409. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18410. auto se = detail::scope_exit([&] {
  18411. svr.stop();
  18412. t.join();
  18413. ASSERT_FALSE(svr.is_running());
  18414. });
  18415. svr.wait_until_ready();
  18416. const std::string req = "GET / HTTP/1.1\r\n"
  18417. "Transfer-Encoding: chunked\r\n"
  18418. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18419. "\r\n"
  18420. "0\r\n"
  18421. "Content-Length: 10\r\n"
  18422. "Host: internal.local\r\n"
  18423. "Content-Type: malicious/content\r\n"
  18424. "Cookie: any\r\n"
  18425. "Set-Cookie: any\r\n"
  18426. "X-Forwarded-For: attacker.com\r\n"
  18427. "X-Real-Ip: 1.1.1.1\r\n"
  18428. "X-Hello: hello\r\n"
  18429. "X-World: world\r\n"
  18430. "\r\n";
  18431. std::string res;
  18432. ASSERT_TRUE(send_request(1, req, &res));
  18433. }
  18434. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18435. // several field lines, and the combined value is what has to be parsed. A
  18436. // Trailer field split across lines therefore declares every name it lists;
  18437. // reading only the first line silently drops the trailers the later lines
  18438. // declare. The prohibited-trailer filter still applies to every line.
  18439. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18440. Server svr;
  18441. size_t observed_trailer_count = 0;
  18442. std::string observed_hello;
  18443. std::string observed_world;
  18444. bool observed_content_length = true;
  18445. svr.Get("/", [&](const Request &req, Response &res) {
  18446. observed_trailer_count = req.trailers.size();
  18447. observed_hello = req.get_trailer_value("X-Hello");
  18448. observed_world = req.get_trailer_value("X-World");
  18449. observed_content_length = req.has_trailer("Content-Length");
  18450. res.set_content("ok", "text/plain");
  18451. });
  18452. auto port = svr.bind_to_any_port(HOST);
  18453. thread t = thread([&]() { svr.listen_after_bind(); });
  18454. auto se = detail::scope_exit([&] {
  18455. svr.stop();
  18456. t.join();
  18457. ASSERT_FALSE(svr.is_running());
  18458. });
  18459. svr.wait_until_ready();
  18460. const std::string req = "GET / HTTP/1.1\r\n"
  18461. "Host: localhost\r\n"
  18462. "Transfer-Encoding: chunked\r\n"
  18463. "Trailer: X-Hello\r\n"
  18464. "Trailer: X-World, Content-Length\r\n"
  18465. "\r\n"
  18466. "0\r\n"
  18467. "X-Hello: hello\r\n"
  18468. "X-World: world\r\n"
  18469. "Content-Length: 10\r\n"
  18470. "\r\n";
  18471. std::string res;
  18472. ASSERT_TRUE(send_request(1, req, &res, port));
  18473. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18474. // Accepted: both field lines contribute to the declared set
  18475. EXPECT_EQ(2U, observed_trailer_count);
  18476. EXPECT_EQ(observed_hello, "hello");
  18477. EXPECT_EQ(observed_world, "world");
  18478. // Denied: a prohibited name stays prohibited on a later field line
  18479. EXPECT_FALSE(observed_content_length);
  18480. }
  18481. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18482. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18483. // unbounded run of fields that are never declared, because the counter would
  18484. // only advance for declared fields.
  18485. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18486. Server svr;
  18487. bool handler_called = false;
  18488. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18489. handler_called = true;
  18490. res.set_content("ok", "text/plain");
  18491. });
  18492. auto port = svr.bind_to_any_port(HOST);
  18493. thread t = thread([&]() { svr.listen_after_bind(); });
  18494. auto se = detail::scope_exit([&] {
  18495. svr.stop();
  18496. t.join();
  18497. ASSERT_FALSE(svr.is_running());
  18498. });
  18499. svr.wait_until_ready();
  18500. // Declare nothing, then send far more undeclared trailer fields than the
  18501. // header-count limit. Parsing must stop and reject the request rather than
  18502. // read every line.
  18503. std::string req = "GET / HTTP/1.1\r\n"
  18504. "Transfer-Encoding: chunked\r\n"
  18505. "\r\n"
  18506. "0\r\n";
  18507. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18508. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18509. }
  18510. req += "\r\n";
  18511. std::string res;
  18512. ASSERT_TRUE(send_request(1, req, &res, port));
  18513. // The request is rejected before the handler runs.
  18514. EXPECT_FALSE(handler_called);
  18515. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18516. }
  18517. // The set of declared trailer names is capped so a peer cannot grow it without
  18518. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18519. // declared past the cap is not honored, even if the field is actually sent.
  18520. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18521. Server svr;
  18522. // One name inside the cap and one past it, so the test tracks the cap rather
  18523. // than a fixed count.
  18524. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18525. const std::string within_cap_name = "X-T-0";
  18526. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18527. bool observed_within_cap = false;
  18528. bool observed_past_cap = false;
  18529. svr.Get("/", [&](const Request &req, Response &res) {
  18530. observed_within_cap = req.has_trailer(within_cap_name);
  18531. observed_past_cap = req.has_trailer(past_cap_name);
  18532. res.set_content("ok", "text/plain");
  18533. });
  18534. auto port = svr.bind_to_any_port(HOST);
  18535. thread t = thread([&]() { svr.listen_after_bind(); });
  18536. auto se = detail::scope_exit([&] {
  18537. svr.stop();
  18538. t.join();
  18539. ASSERT_FALSE(svr.is_running());
  18540. });
  18541. svr.wait_until_ready();
  18542. // Declare more trailer names than the cap in a single Trailer field, then
  18543. // actually send the first (within the cap) and the last (past it).
  18544. std::string trailer_decl = "Trailer: ";
  18545. for (int i = 0; i < declared_count; i++) {
  18546. if (i != 0) { trailer_decl += ", "; }
  18547. trailer_decl += "X-T-" + std::to_string(i);
  18548. }
  18549. trailer_decl += "\r\n";
  18550. const std::string req = "GET / HTTP/1.1\r\n"
  18551. "Host: localhost\r\n"
  18552. "Transfer-Encoding: chunked\r\n" +
  18553. trailer_decl +
  18554. "\r\n"
  18555. "0\r\n" +
  18556. within_cap_name + ": a\r\n" + past_cap_name +
  18557. ": b\r\n"
  18558. "\r\n";
  18559. std::string res;
  18560. ASSERT_TRUE(send_request(1, req, &res, port));
  18561. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18562. // A name within the cap is honored; one declared past the cap is dropped.
  18563. EXPECT_TRUE(observed_within_cap);
  18564. EXPECT_FALSE(observed_past_cap);
  18565. }
  18566. // A direct client that is not listed in trusted_proxies must not be able to
  18567. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18568. // the peer address on the actual TCP connection determines whether the
  18569. // header is honored.
  18570. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18571. Server svr;
  18572. // Deliberately does NOT include the loopback address the test client
  18573. // actually connects from, so the direct connection is not a trusted proxy.
  18574. svr.set_trusted_proxies({"203.0.113.66"});
  18575. std::string observed_remote_addr;
  18576. svr.Get("/ip", [&](const Request &req, Response &res) {
  18577. observed_remote_addr = req.remote_addr;
  18578. res.set_content("ok", "text/plain");
  18579. });
  18580. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18581. auto se = detail::scope_exit([&] {
  18582. svr.stop();
  18583. t.join();
  18584. ASSERT_FALSE(svr.is_running());
  18585. });
  18586. svr.wait_until_ready();
  18587. Client cli(HOST, PORT);
  18588. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18590. EXPECT_EQ(StatusCode::OK_200, res->status);
  18591. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18592. // ignored entirely and the real connection-level address retained.
  18593. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18594. observed_remote_addr == "127.0.0.1");
  18595. }
  18596. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18597. Server svr;
  18598. std::string observed_remote_addr;
  18599. std::string observed_xff;
  18600. svr.Get("/ip", [&](const Request &req, Response &res) {
  18601. observed_remote_addr = req.remote_addr;
  18602. observed_xff = req.get_header_value("X-Forwarded-For");
  18603. res.set_content("ok", "text/plain");
  18604. });
  18605. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18606. auto se = detail::scope_exit([&] {
  18607. svr.stop();
  18608. t.join();
  18609. ASSERT_FALSE(svr.is_running());
  18610. });
  18611. svr.wait_until_ready();
  18612. Client cli(HOST, PORT);
  18613. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18615. EXPECT_EQ(StatusCode::OK_200, res->status);
  18616. EXPECT_EQ(observed_xff, "203.0.113.66");
  18617. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18618. observed_remote_addr == "127.0.0.1");
  18619. }
  18620. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18621. Server svr;
  18622. svr.set_trusted_proxies({"203.0.113.66"});
  18623. std::string observed_remote_addr;
  18624. std::string observed_xff;
  18625. svr.Get("/ip", [&](const Request &req, Response &res) {
  18626. observed_remote_addr = req.remote_addr;
  18627. observed_xff = req.get_header_value("X-Forwarded-For");
  18628. res.set_content("ok", "text/plain");
  18629. });
  18630. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18631. auto se = detail::scope_exit([&] {
  18632. svr.stop();
  18633. t.join();
  18634. ASSERT_FALSE(svr.is_running());
  18635. });
  18636. svr.wait_until_ready();
  18637. Client cli(HOST, PORT);
  18638. auto res = cli.Get("/ip");
  18639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18640. EXPECT_EQ(StatusCode::OK_200, res->status);
  18641. EXPECT_EQ(observed_xff, "");
  18642. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18643. observed_remote_addr == "127.0.0.1");
  18644. }
  18645. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18646. Server svr;
  18647. // Include the loopback address the test client actually connects from, so
  18648. // the direct connection itself is recognized as the trusted proxy hop.
  18649. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18650. std::string observed_remote_addr;
  18651. std::string observed_xff;
  18652. svr.Get("/ip", [&](const Request &req, Response &res) {
  18653. observed_remote_addr = req.remote_addr;
  18654. observed_xff = req.get_header_value("X-Forwarded-For");
  18655. res.set_content("ok", "text/plain");
  18656. });
  18657. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18658. auto se = detail::scope_exit([&] {
  18659. svr.stop();
  18660. t.join();
  18661. ASSERT_FALSE(svr.is_running());
  18662. });
  18663. svr.wait_until_ready();
  18664. Client cli(HOST, PORT);
  18665. auto res = cli.Get(
  18666. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18668. EXPECT_EQ(StatusCode::OK_200, res->status);
  18669. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18670. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18671. }
  18672. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18673. Server svr;
  18674. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18675. std::string observed_remote_addr;
  18676. std::string observed_xff;
  18677. svr.Get("/ip", [&](const Request &req, Response &res) {
  18678. observed_remote_addr = req.remote_addr;
  18679. observed_xff = req.get_header_value("X-Forwarded-For");
  18680. res.set_content("ok", "text/plain");
  18681. });
  18682. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18683. auto se = detail::scope_exit([&] {
  18684. svr.stop();
  18685. t.join();
  18686. ASSERT_FALSE(svr.is_running());
  18687. });
  18688. svr.wait_until_ready();
  18689. Client cli(HOST, PORT);
  18690. auto res = cli.Get(
  18691. "/ip",
  18692. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18694. EXPECT_EQ(StatusCode::OK_200, res->status);
  18695. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18696. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18697. }
  18698. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18699. Server svr;
  18700. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18701. std::string observed_remote_addr;
  18702. std::string observed_xff;
  18703. svr.Get("/ip", [&](const Request &req, Response &res) {
  18704. observed_remote_addr = req.remote_addr;
  18705. observed_xff = req.get_header_value("X-Forwarded-For");
  18706. res.set_content("ok", "text/plain");
  18707. });
  18708. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18709. auto se = detail::scope_exit([&] {
  18710. svr.stop();
  18711. t.join();
  18712. ASSERT_FALSE(svr.is_running());
  18713. });
  18714. svr.wait_until_ready();
  18715. Client cli(HOST, PORT);
  18716. auto res = cli.Get(
  18717. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18719. EXPECT_EQ(StatusCode::OK_200, res->status);
  18720. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18721. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18722. // and must not be selected.
  18723. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18724. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18725. }
  18726. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18727. Server svr;
  18728. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18729. std::string observed_remote_addr;
  18730. svr.Get("/ip", [&](const Request &req, Response &res) {
  18731. observed_remote_addr = req.remote_addr;
  18732. res.set_content("ok", "text/plain");
  18733. });
  18734. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18735. auto se = detail::scope_exit([&] {
  18736. svr.stop();
  18737. t.join();
  18738. ASSERT_FALSE(svr.is_running());
  18739. });
  18740. svr.wait_until_ready();
  18741. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18742. // a forged address and the trusted proxy's own address; the forged value must
  18743. // not win over the address the trusted proxy actually recorded.
  18744. Client cli(HOST, PORT);
  18745. auto res = cli.Get(
  18746. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18748. EXPECT_EQ(StatusCode::OK_200, res->status);
  18749. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18750. }
  18751. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18752. Server svr;
  18753. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18754. std::string observed_remote_addr;
  18755. std::string observed_xff;
  18756. svr.Get("/ip", [&](const Request &req, Response &res) {
  18757. observed_remote_addr = req.remote_addr;
  18758. observed_xff = req.get_header_value("X-Forwarded-For");
  18759. res.set_content("ok", "text/plain");
  18760. });
  18761. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18762. auto se = detail::scope_exit([&] {
  18763. svr.stop();
  18764. t.join();
  18765. ASSERT_FALSE(svr.is_running());
  18766. });
  18767. svr.wait_until_ready();
  18768. Client cli(HOST, PORT);
  18769. auto res = cli.Get(
  18770. "/ip",
  18771. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18773. EXPECT_EQ(StatusCode::OK_200, res->status);
  18774. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18775. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18776. }
  18777. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18778. Server svr;
  18779. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18780. std::string observed_remote_addr;
  18781. std::string observed_xff;
  18782. svr.Get("/ip", [&](const Request &req, Response &res) {
  18783. observed_remote_addr = req.remote_addr;
  18784. observed_xff = req.get_header_value("X-Forwarded-For");
  18785. res.set_content("ok", "text/plain");
  18786. });
  18787. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18788. auto se = detail::scope_exit([&] {
  18789. svr.stop();
  18790. t.join();
  18791. ASSERT_FALSE(svr.is_running());
  18792. });
  18793. svr.wait_until_ready();
  18794. std::string raw_req =
  18795. "GET /ip HTTP/1.1\r\n"
  18796. "Host: localhost\r\n"
  18797. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18798. "Connection: close\r\n"
  18799. "\r\n";
  18800. std::string out;
  18801. ASSERT_TRUE(send_request(5, raw_req, &out));
  18802. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18803. // Header parser trims surrounding whitespace of the header value
  18804. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18805. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18806. }
  18807. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18808. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18809. // their own X-Forwarded-For as a separate field line rather than extending the
  18810. // one the client sent, so every occurrence has to be taken into account.
  18811. // Reading only the first one hands back the address the client chose.
  18812. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18813. Server svr;
  18814. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18815. std::string observed_remote_addr;
  18816. size_t observed_xff_count = 0;
  18817. svr.Get("/ip", [&](const Request &req, Response &res) {
  18818. observed_remote_addr = req.remote_addr;
  18819. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18820. res.set_content("ok", "text/plain");
  18821. });
  18822. auto port = svr.bind_to_any_port(HOST);
  18823. thread t = thread([&]() { svr.listen_after_bind(); });
  18824. auto se = detail::scope_exit([&] {
  18825. svr.stop();
  18826. t.join();
  18827. ASSERT_FALSE(svr.is_running());
  18828. });
  18829. svr.wait_until_ready();
  18830. // The client supplies the first field line; the trusted proxy appends the
  18831. // address it observed as a second one.
  18832. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18833. "Host: localhost\r\n"
  18834. "X-Forwarded-For: 1.2.3.4\r\n"
  18835. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18836. "Connection: close\r\n"
  18837. "\r\n";
  18838. std::string out;
  18839. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18840. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18841. EXPECT_EQ(observed_xff_count, 2U);
  18842. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18843. // The same chain spread over one field line per hop derives the same client
  18844. // address, i.e. the split and the comma-joined representations agree.
  18845. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18846. "Host: localhost\r\n"
  18847. "X-Forwarded-For: 1.2.3.4\r\n"
  18848. "X-Forwarded-For: 198.51.100.23\r\n"
  18849. "X-Forwarded-For: 192.0.2.45\r\n"
  18850. "Connection: close\r\n"
  18851. "\r\n";
  18852. out.clear();
  18853. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18854. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18855. EXPECT_EQ(observed_xff_count, 3U);
  18856. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18857. }
  18858. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18859. // crash the server (it used to call front() on an empty vector inside
  18860. // get_client_ip). The connection-level remote address must be retained instead.
  18861. static void run_malformed_xff_test(const std::string &xff_value) {
  18862. Server svr;
  18863. svr.set_trusted_proxies({"192.0.2.45"});
  18864. std::string observed_remote_addr;
  18865. svr.Get("/ip", [&](const Request &req, Response &res) {
  18866. observed_remote_addr = req.remote_addr;
  18867. res.set_content("ok", "text/plain");
  18868. });
  18869. int port = 0;
  18870. thread t = thread([&]() {
  18871. port = svr.bind_to_any_port(HOST);
  18872. svr.listen_after_bind();
  18873. });
  18874. auto se = detail::scope_exit([&] {
  18875. svr.stop();
  18876. t.join();
  18877. ASSERT_FALSE(svr.is_running());
  18878. });
  18879. svr.wait_until_ready();
  18880. Client cli(HOST, port);
  18881. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18883. EXPECT_EQ(StatusCode::OK_200, res->status);
  18884. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18885. observed_remote_addr == "127.0.0.1");
  18886. }
  18887. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18888. run_malformed_xff_test("");
  18889. }
  18890. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18891. run_malformed_xff_test(",");
  18892. }
  18893. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18894. run_malformed_xff_test(", , ,");
  18895. }
  18896. // The same rule applies to Accept: a request whose acceptable types are spread
  18897. // over several field lines must be negotiated against all of them.
  18898. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18899. // case-insensitive connection options. Comparing the whole field value against
  18900. // one option misses a client that sends several of them, and misses every
  18901. // casing but the one written in the comparison.
  18902. //
  18903. // Sends req, reads the response, then reuses the same socket for a second
  18904. // request to find out whether the server kept the connection.
  18905. static void probe_connection_reuse(int port, const std::string &req,
  18906. bool *announced_close, bool *reusable) {
  18907. auto error = Error::Success;
  18908. auto sock = detail::create_client_socket(
  18909. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18910. /*connection_timeout_sec=*/5, 0,
  18911. /*read_timeout_sec=*/1, 0,
  18912. /*write_timeout_sec=*/5, 0, std::string(), error);
  18913. ASSERT_NE(sock, INVALID_SOCKET);
  18914. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18915. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18916. "Host: localhost\r\n"
  18917. "Connection: close\r\n"
  18918. "\r\n";
  18919. std::string first_response;
  18920. std::string second_response;
  18921. detail::process_client_socket(
  18922. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18923. [&](Stream &strm) {
  18924. if (strm.write(req.data(), req.size()) !=
  18925. static_cast<ssize_t>(req.size())) {
  18926. return false;
  18927. }
  18928. char buf[512];
  18929. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18930. // Headers plus the two-byte body of the handler below
  18931. while (reader.getline()) {
  18932. first_response += reader.ptr();
  18933. if (first_response.find("ok") != std::string::npos) { break; }
  18934. }
  18935. if (strm.write(second.data(), second.size()) !=
  18936. static_cast<ssize_t>(second.size())) {
  18937. return true;
  18938. }
  18939. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18940. while (reader2.getline()) {
  18941. second_response += reader2.ptr();
  18942. if (second_response.find("ok") != std::string::npos) { break; }
  18943. }
  18944. return true;
  18945. });
  18946. *announced_close =
  18947. first_response.find("Connection: close") != std::string::npos;
  18948. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18949. }
  18950. class ConnectionTokenTest : public ::testing::Test {
  18951. protected:
  18952. void SetUp() override {
  18953. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18954. res.set_content("ok", "text/plain");
  18955. });
  18956. port_ = svr_.bind_to_any_port(HOST);
  18957. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18958. svr_.wait_until_ready();
  18959. }
  18960. void TearDown() override {
  18961. svr_.stop();
  18962. if (thread_.joinable()) { thread_.join(); }
  18963. }
  18964. Server svr_;
  18965. int port_ = 0;
  18966. thread thread_;
  18967. };
  18968. // "close" alongside another option still closes the connection, and the
  18969. // response says so rather than leaving the peer to discover it.
  18970. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18971. bool announced_close = false;
  18972. bool reusable = true;
  18973. probe_connection_reuse(port_,
  18974. "GET /keepalive HTTP/1.1\r\n"
  18975. "Host: localhost\r\n"
  18976. "Connection: keep-alive, close\r\n"
  18977. "\r\n",
  18978. &announced_close, &reusable);
  18979. EXPECT_TRUE(announced_close);
  18980. EXPECT_FALSE(reusable);
  18981. }
  18982. // "close" split over two field lines is the same list, so it is honored too.
  18983. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18984. bool announced_close = false;
  18985. bool reusable = true;
  18986. probe_connection_reuse(port_,
  18987. "GET /keepalive HTTP/1.1\r\n"
  18988. "Host: localhost\r\n"
  18989. "Connection: keep-alive\r\n"
  18990. "Connection: close\r\n"
  18991. "\r\n",
  18992. &announced_close, &reusable);
  18993. EXPECT_TRUE(announced_close);
  18994. EXPECT_FALSE(reusable);
  18995. }
  18996. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18997. // keep-alive in the spelling everyone actually sends keeps its connection.
  18998. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18999. bool announced_close = false;
  19000. bool reusable = false;
  19001. probe_connection_reuse(port_,
  19002. "GET /keepalive HTTP/1.0\r\n"
  19003. "Host: localhost\r\n"
  19004. "Connection: keep-alive\r\n"
  19005. "\r\n",
  19006. &announced_close, &reusable);
  19007. EXPECT_FALSE(announced_close);
  19008. EXPECT_TRUE(reusable);
  19009. }
  19010. // A token the value merely contains is not the token itself.
  19011. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19012. bool announced_close = false;
  19013. bool reusable = false;
  19014. probe_connection_reuse(port_,
  19015. "GET /keepalive HTTP/1.1\r\n"
  19016. "Host: localhost\r\n"
  19017. "Connection: notclose\r\n"
  19018. "\r\n",
  19019. &announced_close, &reusable);
  19020. EXPECT_FALSE(announced_close);
  19021. EXPECT_TRUE(reusable);
  19022. }
  19023. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19024. Server svr;
  19025. std::vector<std::string> observed_types;
  19026. svr.Get("/", [&](const Request &req, Response &res) {
  19027. observed_types = req.accept_content_types;
  19028. res.set_content("ok", "text/plain");
  19029. });
  19030. auto port = svr.bind_to_any_port(HOST);
  19031. thread t = thread([&]() { svr.listen_after_bind(); });
  19032. auto se = detail::scope_exit([&] {
  19033. svr.stop();
  19034. t.join();
  19035. ASSERT_FALSE(svr.is_running());
  19036. });
  19037. svr.wait_until_ready();
  19038. Client cli(HOST, port);
  19039. Headers headers;
  19040. headers.emplace("Accept", "text/plain;q=0.5");
  19041. headers.emplace("Accept", "application/json");
  19042. auto res = cli.Get("/", headers);
  19043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19044. EXPECT_EQ(StatusCode::OK_200, res->status);
  19045. // Sorted by q-value, so the second field line's type comes first
  19046. ASSERT_EQ(2U, observed_types.size());
  19047. EXPECT_EQ("application/json", observed_types[0]);
  19048. EXPECT_EQ("text/plain", observed_types[1]);
  19049. }
  19050. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19051. // empty field line must not contribute a bare comma to the combined value.
  19052. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19053. Server svr;
  19054. std::vector<std::string> observed_types;
  19055. svr.Get("/", [&](const Request &req, Response &res) {
  19056. observed_types = req.accept_content_types;
  19057. res.set_content("ok", "text/plain");
  19058. });
  19059. auto port = svr.bind_to_any_port(HOST);
  19060. thread t = thread([&]() { svr.listen_after_bind(); });
  19061. auto se = detail::scope_exit([&] {
  19062. svr.stop();
  19063. t.join();
  19064. ASSERT_FALSE(svr.is_running());
  19065. });
  19066. svr.wait_until_ready();
  19067. // Empty first field line, then a real one
  19068. std::string raw_req = "GET / HTTP/1.1\r\n"
  19069. "Host: localhost\r\n"
  19070. "Accept:\r\n"
  19071. "Accept: application/json\r\n"
  19072. "Connection: close\r\n"
  19073. "\r\n";
  19074. std::string out;
  19075. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19076. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19077. ASSERT_EQ(1U, observed_types.size());
  19078. EXPECT_EQ("application/json", observed_types[0]);
  19079. }
  19080. // The skip in get_combined_header_value() is what keeps an empty field line
  19081. // from contributing a bare comma. Only a trailing empty field line exercises
  19082. // it: a leading one is already covered by the "combined is still empty" check,
  19083. // and parse_accept_header() now ignores the empty element either way, so the
  19084. // request-level test above can no longer tell the two apart.
  19085. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19086. Headers headers;
  19087. headers.emplace("Accept", "text/html");
  19088. headers.emplace("Accept", "");
  19089. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19090. headers.clear();
  19091. headers.emplace("Accept", "");
  19092. headers.emplace("Accept", "application/json");
  19093. EXPECT_EQ("application/json",
  19094. detail::get_combined_header_value(headers, "Accept"));
  19095. }
  19096. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19097. // An encoding offered on a later Accept-Encoding field line is still offered.
  19098. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19099. Server svr;
  19100. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19101. res.set_content(std::string(1024, 'x'), "text/plain");
  19102. });
  19103. auto port = svr.bind_to_any_port(HOST);
  19104. thread t = thread([&]() { svr.listen_after_bind(); });
  19105. auto se = detail::scope_exit([&] {
  19106. svr.stop();
  19107. t.join();
  19108. ASSERT_FALSE(svr.is_running());
  19109. });
  19110. svr.wait_until_ready();
  19111. Client cli(HOST, port);
  19112. cli.set_decompress(false);
  19113. Headers headers;
  19114. headers.emplace("Accept-Encoding", "identity");
  19115. headers.emplace("Accept-Encoding", "gzip");
  19116. auto res = cli.Get("/", headers);
  19117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19118. EXPECT_EQ(StatusCode::OK_200, res->status);
  19119. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19120. }
  19121. #endif
  19122. #ifndef _WIN32
  19123. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19124. Server svr;
  19125. svr.Post("/post", [&](const Request &req, Response &res) {
  19126. res.set_content(req.body, "text/plain");
  19127. });
  19128. svr.Put("/put", [&](const Request &req, Response &res) {
  19129. res.set_content(req.body, "text/plain");
  19130. });
  19131. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19132. res.set_content(req.body, "text/plain");
  19133. });
  19134. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19135. res.set_content(req.body, "text/plain");
  19136. });
  19137. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19138. auto se = detail::scope_exit([&] {
  19139. svr.stop();
  19140. t.join();
  19141. ASSERT_FALSE(svr.is_running());
  19142. });
  19143. svr.wait_until_ready();
  19144. std::string resp;
  19145. // POST without Content-Length
  19146. ASSERT_TRUE(send_request(5,
  19147. "POST /post HTTP/1.1\r\n"
  19148. "Host: localhost\r\n"
  19149. "Connection: close\r\n"
  19150. "\r\n",
  19151. &resp));
  19152. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19153. // PUT without Content-Length
  19154. resp.clear();
  19155. ASSERT_TRUE(send_request(5,
  19156. "PUT /put HTTP/1.1\r\n"
  19157. "Host: localhost\r\n"
  19158. "Connection: close\r\n"
  19159. "\r\n",
  19160. &resp));
  19161. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19162. // PATCH without Content-Length
  19163. resp.clear();
  19164. ASSERT_TRUE(send_request(5,
  19165. "PATCH /patch HTTP/1.1\r\n"
  19166. "Host: localhost\r\n"
  19167. "Connection: close\r\n"
  19168. "\r\n",
  19169. &resp));
  19170. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19171. // DELETE without Content-Length
  19172. resp.clear();
  19173. ASSERT_TRUE(send_request(5,
  19174. "DELETE /delete HTTP/1.1\r\n"
  19175. "Host: localhost\r\n"
  19176. "Connection: close\r\n"
  19177. "\r\n",
  19178. &resp));
  19179. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19180. }
  19181. #endif
  19182. //==============================================================================
  19183. // open_stream() Tests
  19184. //==============================================================================
  19185. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19186. std::string result;
  19187. char buf[8192];
  19188. ssize_t n;
  19189. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19190. result.append(buf, static_cast<size_t>(n));
  19191. }
  19192. return result;
  19193. }
  19194. // Mock stream for unit tests
  19195. class MockStream : public Stream {
  19196. public:
  19197. std::string data;
  19198. size_t pos = 0;
  19199. ssize_t error_after = -1; // -1 = no error
  19200. explicit MockStream(const std::string &d, ssize_t err = -1)
  19201. : data(d), error_after(err) {}
  19202. bool is_readable() const override { return true; }
  19203. bool wait_readable() const override { return true; }
  19204. bool wait_writable() const override { return true; }
  19205. ssize_t read(char *ptr, size_t size) override {
  19206. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19207. if (pos >= data.size()) return 0;
  19208. size_t limit =
  19209. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19210. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19211. std::memcpy(ptr, data.data() + pos, to_read);
  19212. pos += to_read;
  19213. return static_cast<ssize_t>(to_read);
  19214. }
  19215. ssize_t write(const char *, size_t) override { return -1; }
  19216. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19217. ip = "127.0.0.1";
  19218. port = 0;
  19219. }
  19220. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19221. ip = "127.0.0.1";
  19222. port = 0;
  19223. }
  19224. socket_t socket() const override { return INVALID_SOCKET; }
  19225. time_t duration() const override { return 0; }
  19226. };
  19227. TEST(StreamHandleTest, Basic) {
  19228. ClientImpl::StreamHandle handle;
  19229. EXPECT_FALSE(handle.is_valid());
  19230. handle.response = detail::make_unique<Response>();
  19231. handle.error = Error::Connection;
  19232. EXPECT_FALSE(handle.is_valid());
  19233. handle.error = Error::Success;
  19234. EXPECT_TRUE(handle.is_valid());
  19235. }
  19236. TEST(BodyReaderTest, Basic) {
  19237. MockStream stream("Hello, World!");
  19238. detail::BodyReader reader;
  19239. reader.stream = &stream;
  19240. reader.content_length = 13;
  19241. char buf[32];
  19242. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19243. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19244. EXPECT_TRUE(reader.eof);
  19245. }
  19246. TEST(BodyReaderTest, NoStream) {
  19247. detail::BodyReader reader;
  19248. char buf[32];
  19249. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19250. EXPECT_EQ(Error::Connection, reader.last_error);
  19251. }
  19252. TEST(BodyReaderTest, Error) {
  19253. MockStream stream("Hello, World!", 5);
  19254. detail::BodyReader reader;
  19255. reader.stream = &stream;
  19256. reader.content_length = 13;
  19257. char buf[32];
  19258. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19259. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19260. EXPECT_EQ(Error::Read, reader.last_error);
  19261. }
  19262. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19263. // Mock-based StreamHandle tests relying on private internals are removed.
  19264. class OpenStreamTest : public ::testing::Test {
  19265. protected:
  19266. void SetUp() override {
  19267. svr_.Get("/hello", [](const Request &, Response &res) {
  19268. res.set_content("Hello World!", "text/plain");
  19269. });
  19270. svr_.Get("/large", [](const Request &, Response &res) {
  19271. res.set_content(std::string(10000, 'X'), "text/plain");
  19272. });
  19273. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19274. res.set_content("Hello World!", "image/jpeg");
  19275. res.set_header("Content-Encoding", "UTF-8");
  19276. });
  19277. svr_.Get("/chunked", [](const Request &, Response &res) {
  19278. res.set_chunked_content_provider("text/plain",
  19279. [](size_t offset, DataSink &sink) {
  19280. if (offset < 15) {
  19281. sink.write("chunk", 5);
  19282. return true;
  19283. }
  19284. sink.done();
  19285. return true;
  19286. });
  19287. });
  19288. svr_.Get("/compressible", [](const Request &, Response &res) {
  19289. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19290. DataSink &sink) {
  19291. if (offset < 100 * 1024) {
  19292. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19293. sink.write(chunk.data(), chunk.size());
  19294. return true;
  19295. }
  19296. sink.done();
  19297. return true;
  19298. });
  19299. });
  19300. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19301. [](const Request & /*req*/, Response &res) {
  19302. auto i = new int(0);
  19303. res.set_header("Trailer", "Content-Length, X-Allowed");
  19304. res.set_chunked_content_provider(
  19305. "text/plain",
  19306. [i](size_t /*offset*/, DataSink &sink) {
  19307. switch (*i) {
  19308. case 0: sink.os << "123"; break;
  19309. case 1: sink.os << "456"; break;
  19310. case 2: sink.os << "789"; break;
  19311. case 3: {
  19312. sink.done_with_trailer(
  19313. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19314. } break;
  19315. }
  19316. (*i)++;
  19317. return true;
  19318. },
  19319. [i](bool success) {
  19320. EXPECT_TRUE(success);
  19321. delete i;
  19322. });
  19323. });
  19324. // Echo headers endpoint for header-related tests
  19325. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19326. std::string body;
  19327. for (const auto &h : req.headers) {
  19328. body.append(h.first);
  19329. body.push_back(':');
  19330. body.append(h.second);
  19331. body.push_back('\n');
  19332. }
  19333. res.set_content(body, "text/plain");
  19334. });
  19335. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19336. std::string body;
  19337. for (const auto &h : req.headers) {
  19338. body.append(h.first);
  19339. body.push_back(':');
  19340. body.append(h.second);
  19341. body.push_back('\n');
  19342. }
  19343. res.set_content(body, "text/plain");
  19344. });
  19345. port_ = svr_.bind_to_any_port("127.0.0.1");
  19346. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19347. svr_.wait_until_ready();
  19348. }
  19349. void TearDown() override {
  19350. svr_.stop();
  19351. if (thread_.joinable()) thread_.join();
  19352. }
  19353. Server svr_;
  19354. std::thread thread_;
  19355. int port_ = 0;
  19356. };
  19357. TEST_F(OpenStreamTest, Basic) {
  19358. Client cli("127.0.0.1", port_);
  19359. auto handle = cli.open_stream("GET", "/hello");
  19360. EXPECT_TRUE(handle.is_valid());
  19361. EXPECT_EQ("Hello World!", read_all(handle));
  19362. }
  19363. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19364. Client cli("127.0.0.1", port_);
  19365. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19366. ASSERT_TRUE(handle.is_valid());
  19367. EXPECT_EQ("Hello World!", read_all(handle));
  19368. }
  19369. TEST_F(OpenStreamTest, SmallBuffer) {
  19370. Client cli("127.0.0.1", port_);
  19371. auto handle = cli.open_stream("GET", "/hello");
  19372. std::string result;
  19373. char buf[4];
  19374. ssize_t n;
  19375. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19376. result.append(buf, static_cast<size_t>(n));
  19377. EXPECT_EQ("Hello World!", result);
  19378. }
  19379. TEST_F(OpenStreamTest, DefaultHeaders) {
  19380. Client cli("127.0.0.1", port_);
  19381. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19382. {
  19383. auto handle = cli.open_stream("GET", "/echo-headers");
  19384. ASSERT_TRUE(handle.is_valid());
  19385. auto body = read_all(handle);
  19386. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19387. std::string::npos);
  19388. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19389. std::string::npos);
  19390. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19391. }
  19392. // open_stream POST with body and no explicit content_type should NOT add
  19393. // text/plain Content-Type (behavior differs from non-streaming path), but
  19394. // should include Content-Length
  19395. {
  19396. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19397. ASSERT_TRUE(handle.is_valid());
  19398. auto body = read_all(handle);
  19399. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19400. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19401. }
  19402. // open_stream POST with explicit Content-Type should preserve it
  19403. {
  19404. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19405. {{"Content-Type", "application/custom"}},
  19406. "{}", "application/custom");
  19407. ASSERT_TRUE(handle.is_valid());
  19408. auto body = read_all(handle);
  19409. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19410. }
  19411. // User-specified User-Agent must not be overwritten for stream API
  19412. {
  19413. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19414. {{"User-Agent", "MyAgent/1.2"}});
  19415. ASSERT_TRUE(handle.is_valid());
  19416. auto body = read_all(handle);
  19417. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19418. }
  19419. }
  19420. TEST_F(OpenStreamTest, Large) {
  19421. Client cli("127.0.0.1", port_);
  19422. auto handle = cli.open_stream("GET", "/large");
  19423. EXPECT_EQ(10000u, read_all(handle).size());
  19424. }
  19425. TEST_F(OpenStreamTest, ConnectionError) {
  19426. Client cli("127.0.0.1", 9999);
  19427. auto handle = cli.open_stream("GET", "/hello");
  19428. EXPECT_FALSE(handle.is_valid());
  19429. }
  19430. TEST_F(OpenStreamTest, Chunked) {
  19431. Client cli("127.0.0.1", port_);
  19432. auto handle = cli.open_stream("GET", "/chunked");
  19433. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19434. "Transfer-Encoding") == "chunked");
  19435. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19436. }
  19437. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19438. Client cli("127.0.0.1", port_);
  19439. auto handle =
  19440. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19441. ASSERT_TRUE(handle.is_valid());
  19442. // Consume body to allow trailers to be received/parsed
  19443. auto body = read_all(handle);
  19444. // Explicitly parse trailers (ensure trailers are available for assertion)
  19445. handle.parse_trailers_if_needed();
  19446. EXPECT_EQ(std::string("123456789"), body);
  19447. // The response should include a Trailer header declaring both names
  19448. ASSERT_TRUE(handle.response);
  19449. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19450. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19451. handle.response->get_header_value("Trailer"));
  19452. // Prohibited trailer must not be present
  19453. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19454. // Allowed trailer should be present
  19455. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19456. EXPECT_EQ(std::string("yes"),
  19457. handle.response->get_trailer_value("X-Allowed"));
  19458. // Verify trailers are NOT present as regular headers
  19459. EXPECT_EQ(std::string(""),
  19460. handle.response->get_header_value("Content-Length"));
  19461. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19462. }
  19463. // Accepts one connection on an OS-assigned port, which it hands over through
  19464. // port_promise, reads the request head and sends back response. after_send,
  19465. // if given, runs on the connection before it is closed.
  19466. static std::thread
  19467. serve_single_response(std::promise<int> &port_promise,
  19468. const std::string &response,
  19469. std::function<void(socket_t)> after_send = nullptr) {
  19470. return std::thread([&port_promise, response, after_send] {
  19471. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19472. default_socket_options(srv);
  19473. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19474. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19475. sockaddr_in addr{};
  19476. addr.sin_family = AF_INET;
  19477. addr.sin_port = htons(0); // Let OS assign a free port
  19478. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19479. int opt = 1;
  19480. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19481. #ifdef _WIN32
  19482. reinterpret_cast<const char *>(&opt),
  19483. #else
  19484. &opt,
  19485. #endif
  19486. sizeof(opt));
  19487. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19488. ::listen(srv, 1) != 0) {
  19489. port_promise.set_value(-1);
  19490. detail::close_socket(srv);
  19491. return;
  19492. }
  19493. socklen_t addr_len = sizeof(addr);
  19494. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19495. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19496. sockaddr_in cli_addr{};
  19497. socklen_t cli_len = sizeof(cli_addr);
  19498. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19499. if (cli != INVALID_SOCKET) {
  19500. // Read the complete HTTP request (until the blank line that terminates
  19501. // headers) before sending the response. If the server closes the socket
  19502. // while the client's request data is still unread in the kernel receive
  19503. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19504. // connection on both sides: it discards the client's receive buffer
  19505. // (which already holds our response) and causes any in-progress write on
  19506. // the client to fail with ECONNRESET. Reading all request data first
  19507. // ensures close() emits a graceful FIN.
  19508. {
  19509. char rbuf[256];
  19510. std::string req;
  19511. while (req.find("\r\n\r\n") == std::string::npos) {
  19512. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19513. if (n <= 0) { break; }
  19514. req.append(rbuf, static_cast<size_t>(n));
  19515. }
  19516. }
  19517. ::send(cli,
  19518. #ifdef _WIN32
  19519. static_cast<const char *>(response.c_str()),
  19520. static_cast<int>(response.size()),
  19521. #else
  19522. response.c_str(), response.size(),
  19523. #endif
  19524. 0);
  19525. if (after_send) { after_send(cli); }
  19526. detail::close_socket(cli);
  19527. }
  19528. detail::close_socket(srv);
  19529. });
  19530. }
  19531. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19532. #ifndef _WIN32
  19533. signal(SIGPIPE, SIG_IGN);
  19534. #endif
  19535. std::promise<int> port_promise;
  19536. auto port_future = port_promise.get_future();
  19537. auto server_thread =
  19538. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19539. "Content-Type: text/plain\r\n"
  19540. "Content-Length: not-a-number\r\n"
  19541. "Connection: close\r\n"
  19542. "\r\n"
  19543. "hello");
  19544. auto port = port_future.get();
  19545. ASSERT_GT(port, 0);
  19546. Client cli("127.0.0.1", port);
  19547. auto handle = cli.open_stream("GET", "/");
  19548. EXPECT_FALSE(handle.is_valid());
  19549. server_thread.join();
  19550. }
  19551. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19552. #ifndef _WIN32
  19553. signal(SIGPIPE, SIG_IGN);
  19554. #endif
  19555. std::promise<int> port_promise;
  19556. auto port_future = port_promise.get_future();
  19557. auto server_thread = serve_single_response(
  19558. port_promise, "HTTP/1.1 200 OK\r\n"
  19559. "Content-Type: text/plain\r\n"
  19560. "Content-Length: 99999999999999999999999999\r\n"
  19561. "Connection: close\r\n"
  19562. "\r\n"
  19563. "hello");
  19564. auto port = port_future.get();
  19565. ASSERT_GT(port, 0);
  19566. // Historically std::stoull would throw std::out_of_range here and crash
  19567. // the process, then parsing silently clamped to a bogus framing length and
  19568. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19569. // so the stream fails to open, matching the not-a-number case above. The
  19570. // process still must NOT terminate.
  19571. Client cli("127.0.0.1", port);
  19572. auto handle = cli.open_stream("GET", "/");
  19573. EXPECT_FALSE(handle.is_valid());
  19574. server_thread.join();
  19575. }
  19576. // Serves `response` to the single request `fn` makes with a fresh client.
  19577. template <typename Fn>
  19578. static void with_single_response(const std::string &response, Fn fn) {
  19579. #ifndef _WIN32
  19580. signal(SIGPIPE, SIG_IGN);
  19581. #endif
  19582. std::promise<int> port_promise;
  19583. auto port_future = port_promise.get_future();
  19584. auto server_thread = serve_single_response(port_promise, response);
  19585. auto se = detail::scope_exit([&] { server_thread.join(); });
  19586. auto port = port_future.get();
  19587. ASSERT_GT(port, 0);
  19588. Client cli("127.0.0.1", port);
  19589. fn(cli);
  19590. }
  19591. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19592. // Neither Content-Length nor chunked: the body ends at the close
  19593. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19594. "Connection: close\r\n"
  19595. "\r\n"
  19596. "hello";
  19597. with_single_response(close_delimited, [](Client &cli) {
  19598. auto handle = cli.open_stream("GET", "/");
  19599. ASSERT_TRUE(handle.is_valid());
  19600. EXPECT_EQ("hello", read_all(handle));
  19601. EXPECT_FALSE(handle.has_read_error());
  19602. });
  19603. // A close before the end of the Content-Length is still an error
  19604. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19605. "Content-Length: 10\r\n"
  19606. "\r\n"
  19607. "hello";
  19608. with_single_response(short_content_length, [](Client &cli) {
  19609. auto handle = cli.open_stream("GET", "/");
  19610. ASSERT_TRUE(handle.is_valid());
  19611. read_all(handle);
  19612. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19613. });
  19614. // So is a close before the last chunk
  19615. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19616. "Transfer-Encoding: chunked\r\n"
  19617. "\r\n"
  19618. "5\r\nhello\r\n";
  19619. with_single_response(short_chunked, [](Client &cli) {
  19620. auto handle = cli.open_stream("GET", "/");
  19621. ASSERT_TRUE(handle.is_valid());
  19622. read_all(handle);
  19623. EXPECT_TRUE(handle.has_read_error());
  19624. });
  19625. }
  19626. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19627. const char *responses[] = {
  19628. "HTTP/1.1 103 Early Hints\r\n"
  19629. "Link: </style.css>; rel=preload\r\n"
  19630. "\r\n"
  19631. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19632. "HTTP/1.1 100 Continue\r\n"
  19633. "X-Note: interim\r\n"
  19634. "\r\n"
  19635. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19636. };
  19637. for (auto response : responses) {
  19638. with_single_response(response, [](Client &cli) {
  19639. auto res = cli.Get("/");
  19640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19641. EXPECT_EQ(StatusCode::OK_200, res->status);
  19642. EXPECT_EQ("ok", res->body);
  19643. });
  19644. }
  19645. }
  19646. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19647. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19648. const std::string final_response =
  19649. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19650. std::string interims;
  19651. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19652. interims += interim;
  19653. }
  19654. with_single_response(interims + final_response, [](Client &cli) {
  19655. auto res = cli.Get("/");
  19656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19657. EXPECT_EQ("ok", res->body);
  19658. });
  19659. with_single_response(interims + interim + final_response, [](Client &cli) {
  19660. auto res = cli.Get("/");
  19661. ASSERT_FALSE(res);
  19662. EXPECT_EQ(Error::Read, res.error());
  19663. });
  19664. }
  19665. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19666. #ifndef _WIN32
  19667. signal(SIGPIPE, SIG_IGN);
  19668. #endif
  19669. // The server answers the head without asking for the body. Bytes it then
  19670. // reads on the connection would be taken for the body the request declared.
  19671. auto closed_by_client = false;
  19672. std::promise<int> port_promise;
  19673. auto server_thread = serve_single_response(
  19674. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19675. [&](socket_t sock) {
  19676. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19677. char buf[256];
  19678. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19679. });
  19680. Client cli("127.0.0.1", port_promise.get_future().get());
  19681. cli.set_keep_alive(true);
  19682. cli.set_read_timeout(1, 0);
  19683. // Long enough for the client to send Expect: 100-continue.
  19684. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19686. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19687. cli.Get("/second");
  19688. server_thread.join();
  19689. EXPECT_TRUE(closed_by_client);
  19690. }
  19691. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19692. // Long enough for the client to send Expect: 100-continue
  19693. with_single_response(
  19694. "HTTP/1.1 103 Early Hints\r\n"
  19695. "Link: </style.css>; rel=preload\r\n"
  19696. "\r\n"
  19697. "HTTP/1.1 401 Unauthorized\r\n"
  19698. "Content-Length: 0\r\n\r\n",
  19699. [](Client &cli) {
  19700. cli.set_read_timeout(2, 0);
  19701. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19703. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19704. });
  19705. }
  19706. #ifdef CPPHTTPLIB_SSL_ENABLED
  19707. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19708. #ifndef _WIN32
  19709. signal(SIGPIPE, SIG_IGN);
  19710. #endif
  19711. auto reused = false;
  19712. std::promise<int> port_promise;
  19713. auto server_thread = serve_single_response(
  19714. port_promise,
  19715. "HTTP/1.1 401 Unauthorized\r\n"
  19716. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19717. "Content-Length: 0\r\n\r\n",
  19718. [&](socket_t sock) {
  19719. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19720. char buf[256];
  19721. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19722. });
  19723. Client cli("127.0.0.1", port_promise.get_future().get());
  19724. cli.set_keep_alive(true);
  19725. cli.set_digest_auth("user", "pass");
  19726. cli.set_read_timeout(1, 0);
  19727. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19728. server_thread.join();
  19729. EXPECT_FALSE(reused);
  19730. }
  19731. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19732. // Any other answer to CONNECT would read as the origin's response.
  19733. struct {
  19734. const char *response;
  19735. bool passed_on;
  19736. } cases[] = {
  19737. {"HTTP/1.1 201 Created\r\n"
  19738. "Set-Cookie: session=from-proxy\r\n"
  19739. "Content-Length: 0\r\n\r\n",
  19740. false},
  19741. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19742. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19743. "Content-Length: 0\r\n\r\n",
  19744. true},
  19745. };
  19746. for (const auto &c : cases) {
  19747. std::promise<int> port_promise;
  19748. auto server_thread = serve_single_response(port_promise, c.response);
  19749. SSLClient cli("example.com", 443);
  19750. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19751. auto res = cli.Get("/");
  19752. server_thread.join();
  19753. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19754. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19755. if (res) {
  19756. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19757. }
  19758. }
  19759. }
  19760. #endif
  19761. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19762. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19763. // the chunked coding and drop Content-Length, so a front-end that trusts
  19764. // Content-Length would disagree about where the body ends (response
  19765. // smuggling). The client must reject such a response.
  19766. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19767. for (const char *te : {"chunked", "gzip, chunked"}) {
  19768. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19769. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19770. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19771. "5\r\nhello\r\n0\r\n\r\n";
  19772. with_single_response(response, [&](Client &cli) {
  19773. auto res = cli.Get("/");
  19774. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19775. EXPECT_EQ(Error::Read, res.error()) << te;
  19776. });
  19777. with_single_response(response, [&](Client &cli) {
  19778. auto handle = cli.open_stream("GET", "/");
  19779. EXPECT_FALSE(handle.is_valid()) << te;
  19780. EXPECT_EQ(Error::Read, handle.error) << te;
  19781. });
  19782. }
  19783. }
  19784. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19785. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19786. // closing the connection (unlike a request, which must be rejected).
  19787. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19788. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19789. "Transfer-Encoding: chunked\r\n"
  19790. "Connection: close\r\n"
  19791. "\r\n"
  19792. "5\r\nhello\r\n0\r\n\r\n",
  19793. "HTTP/1.1 200 OK\r\n"
  19794. "Transfer-Encoding: gzip\r\n"
  19795. "Connection: close\r\n"
  19796. "\r\n"
  19797. "hello"}) {
  19798. with_single_response(response, [&](Client &cli) {
  19799. auto res = cli.Get("/");
  19800. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19801. EXPECT_EQ("hello", res->body);
  19802. });
  19803. with_single_response(response, [&](Client &cli) {
  19804. auto handle = cli.open_stream("GET", "/");
  19805. ASSERT_TRUE(handle.is_valid()) << response;
  19806. EXPECT_EQ("hello", read_all(handle));
  19807. });
  19808. }
  19809. }
  19810. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19811. // framing headers describe nothing to read and must not be rejected.
  19812. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19813. const std::string framing = "Content-Length: 5\r\n"
  19814. "Transfer-Encoding: chunked\r\n"
  19815. "Connection: close\r\n"
  19816. "\r\n";
  19817. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19818. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19819. });
  19820. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19821. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19822. });
  19823. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19824. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19825. with_single_response(response, [&](Client &cli) {
  19826. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19827. });
  19828. with_single_response(response, [&](Client &cli) {
  19829. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19830. });
  19831. }
  19832. }
  19833. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19834. // response, is faulty framing, so the connection is not reused after it.
  19835. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19836. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19837. "Content-Length: 0\r\n"
  19838. "Transfer-Encoding: chunked\r\n"
  19839. "\r\n"
  19840. "5\r\nhello\r\n0\r\n\r\n",
  19841. "HTTP/1.0 200 Connection established\r\n"
  19842. "Connection: keep-alive\r\n"
  19843. "Transfer-Encoding: chunked\r\n"
  19844. "\r\n"
  19845. "5\r\nhello\r\n0\r\n\r\n"}) {
  19846. with_single_response(response, [&](Client &cli) {
  19847. cli.set_keep_alive(true);
  19848. auto res = cli.Get("/");
  19849. ASSERT_TRUE(res) << response;
  19850. EXPECT_EQ("hello", res->body);
  19851. EXPECT_FALSE(cli.is_socket_open()) << response;
  19852. });
  19853. }
  19854. }
  19855. // A payload max length of 0 means no limit, however the body is framed.
  19856. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19857. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19858. "Transfer-Encoding: chunked\r\n"
  19859. "\r\n"
  19860. "5\r\nhello\r\n0\r\n\r\n",
  19861. "HTTP/1.1 200 OK\r\n"
  19862. "Connection: close\r\n"
  19863. "\r\n"
  19864. "hello"}) {
  19865. with_single_response(response, [&](Client &cli) {
  19866. cli.set_payload_max_length(0);
  19867. auto res = cli.Get("/");
  19868. ASSERT_TRUE(res) << response;
  19869. EXPECT_EQ("hello", res->body) << response;
  19870. });
  19871. }
  19872. }
  19873. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19874. Server svr;
  19875. svr.set_payload_max_length(0);
  19876. svr.Post("/echo", [](const Request &req, Response &res) {
  19877. res.set_content(req.body, "text/plain");
  19878. });
  19879. auto port = svr.bind_to_any_port(HOST);
  19880. thread t = thread([&] { svr.listen_after_bind(); });
  19881. auto se = detail::scope_exit([&] {
  19882. svr.stop();
  19883. t.join();
  19884. ASSERT_FALSE(svr.is_running());
  19885. });
  19886. svr.wait_until_ready();
  19887. Client cli(HOST, port);
  19888. auto res = cli.Post(
  19889. "/echo",
  19890. [](size_t /*offset*/, DataSink &sink) {
  19891. sink.write("hello", 5);
  19892. sink.done();
  19893. return true;
  19894. },
  19895. "text/plain");
  19896. ASSERT_TRUE(res);
  19897. EXPECT_EQ(StatusCode::OK_200, res->status);
  19898. EXPECT_EQ("hello", res->body);
  19899. }
  19900. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19901. TEST_F(OpenStreamTest, Gzip) {
  19902. Client cli("127.0.0.1", port_);
  19903. auto handle = cli.open_stream("GET", "/compressible", {},
  19904. {{"Accept-Encoding", "gzip"}});
  19905. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19906. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19907. }
  19908. TEST_F(OpenStreamTest, TrailersWithGzip) {
  19909. Client cli("127.0.0.1", port_);
  19910. auto handle =
  19911. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  19912. {{"Accept-Encoding", "gzip"}});
  19913. ASSERT_TRUE(handle.is_valid());
  19914. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19915. EXPECT_EQ("123456789", read_all(handle));
  19916. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  19917. }
  19918. #endif
  19919. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19920. TEST_F(OpenStreamTest, Brotli) {
  19921. Client cli("127.0.0.1", port_);
  19922. auto handle =
  19923. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19924. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19925. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19926. }
  19927. #endif
  19928. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19929. TEST_F(OpenStreamTest, Zstd) {
  19930. Client cli("127.0.0.1", port_);
  19931. auto handle = cli.open_stream("GET", "/compressible", {},
  19932. {{"Accept-Encoding", "zstd"}});
  19933. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19934. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19935. }
  19936. #endif
  19937. #ifdef CPPHTTPLIB_SSL_ENABLED
  19938. class SSLOpenStreamTest : public ::testing::Test {
  19939. protected:
  19940. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19941. void SetUp() override {
  19942. svr_.Get("/hello", [](const Request &, Response &res) {
  19943. res.set_content("Hello SSL World!", "text/plain");
  19944. });
  19945. svr_.Get("/chunked", [](const Request &, Response &res) {
  19946. res.set_chunked_content_provider("text/plain",
  19947. [](size_t offset, DataSink &sink) {
  19948. if (offset < 15) {
  19949. sink.write("chunk", 5);
  19950. return true;
  19951. }
  19952. sink.done();
  19953. return true;
  19954. });
  19955. });
  19956. svr_.Post("/echo", [](const Request &req, Response &res) {
  19957. res.set_content(req.body, req.get_header_value("Content-Type"));
  19958. });
  19959. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19960. std::string body = req.body;
  19961. res.set_chunked_content_provider(
  19962. "text/plain", [body](size_t offset, DataSink &sink) {
  19963. if (offset < body.size()) {
  19964. sink.write(body.data() + offset, body.size() - offset);
  19965. }
  19966. sink.done();
  19967. return true;
  19968. });
  19969. });
  19970. port_ = svr_.bind_to_any_port("127.0.0.1");
  19971. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19972. svr_.wait_until_ready();
  19973. }
  19974. void TearDown() override {
  19975. svr_.stop();
  19976. if (thread_.joinable()) thread_.join();
  19977. }
  19978. SSLServer svr_;
  19979. std::thread thread_;
  19980. int port_ = 0;
  19981. };
  19982. TEST_F(SSLOpenStreamTest, Basic) {
  19983. SSLClient cli("127.0.0.1", port_);
  19984. cli.enable_server_certificate_verification(false);
  19985. auto handle = cli.open_stream("GET", "/hello");
  19986. ASSERT_TRUE(handle.is_valid());
  19987. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19988. }
  19989. TEST_F(SSLOpenStreamTest, Chunked) {
  19990. SSLClient cli("127.0.0.1", port_);
  19991. cli.enable_server_certificate_verification(false);
  19992. auto handle = cli.open_stream("GET", "/chunked");
  19993. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19994. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19995. "Transfer-Encoding") == "chunked");
  19996. auto body = read_all(handle);
  19997. EXPECT_EQ("chunkchunkchunk", body);
  19998. }
  19999. TEST_F(SSLOpenStreamTest, Post) {
  20000. SSLClient cli("127.0.0.1", port_);
  20001. cli.enable_server_certificate_verification(false);
  20002. auto handle =
  20003. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20004. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20005. EXPECT_EQ(200, handle.response->status);
  20006. auto body = read_all(handle);
  20007. EXPECT_EQ("Hello SSL POST", body);
  20008. }
  20009. TEST_F(SSLOpenStreamTest, PostChunked) {
  20010. SSLClient cli("127.0.0.1", port_);
  20011. cli.enable_server_certificate_verification(false);
  20012. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20013. "Chunked SSL Data", "text/plain");
  20014. ASSERT_TRUE(handle.is_valid());
  20015. EXPECT_EQ(200, handle.response->status);
  20016. auto body = read_all(handle);
  20017. EXPECT_EQ("Chunked SSL Data", body);
  20018. }
  20019. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20020. // Content-Length is terminated by the server closing the connection. When the
  20021. // SSL peer sends a close_notify after the body, the client must treat it as a
  20022. // clean EOF and return a successful response rather than an error.
  20023. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20025. ASSERT_TRUE(svr.is_valid());
  20026. svr.set_keep_alive_max_count(1);
  20027. const std::string expected_body = "Hello from connection-close response!";
  20028. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20029. res.set_content_provider("text/plain",
  20030. [&](size_t offset, DataSink &sink) -> bool {
  20031. if (offset < expected_body.size()) {
  20032. sink.write(expected_body.data() + offset,
  20033. expected_body.size() - offset);
  20034. }
  20035. sink.done();
  20036. return true;
  20037. });
  20038. });
  20039. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20040. auto se = detail::scope_exit([&] {
  20041. svr.stop();
  20042. listen_thread.join();
  20043. ASSERT_FALSE(svr.is_running());
  20044. });
  20045. svr.wait_until_ready();
  20046. SSLClient cli(HOST, PORT);
  20047. cli.enable_server_certificate_verification(false);
  20048. auto res = cli.Get("/no-content-length");
  20049. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20050. EXPECT_EQ(StatusCode::OK_200, res->status);
  20051. EXPECT_EQ(expected_body, res->body);
  20052. }
  20053. #endif // CPPHTTPLIB_SSL_ENABLED
  20054. //==============================================================================
  20055. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20056. // results for various scenarios.
  20057. //==============================================================================
  20058. TEST(ParityTest, GetVsOpenStream) {
  20059. Server svr;
  20060. const std::string path = "/parity";
  20061. const std::string content = "Parity test content: hello world";
  20062. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20063. res.set_content(content, "text/plain");
  20064. });
  20065. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20066. auto se = detail::scope_exit([&] {
  20067. svr.stop();
  20068. t.join();
  20069. ASSERT_FALSE(svr.is_running());
  20070. });
  20071. svr.wait_until_ready();
  20072. Client cli(HOST, PORT);
  20073. // Non-stream path
  20074. auto r1 = cli.Get(path);
  20075. ASSERT_TRUE(r1);
  20076. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20077. // Stream path
  20078. auto h = cli.open_stream("GET", path);
  20079. ASSERT_TRUE(h.is_valid());
  20080. EXPECT_EQ(r1->body, read_all(h));
  20081. }
  20082. // Helper to compress data with provided compressor type T
  20083. template <typename Compressor>
  20084. static std::string compress_payload_for_parity(const std::string &in) {
  20085. std::string out;
  20086. Compressor compressor;
  20087. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20088. [&](const char *data, size_t n) {
  20089. out.append(data, n);
  20090. return true;
  20091. });
  20092. EXPECT_TRUE(ok);
  20093. return out;
  20094. }
  20095. // Helper function for compression parity tests
  20096. template <typename Compressor>
  20097. static void test_compression_parity(const std::string &original,
  20098. const std::string &path,
  20099. const std::string &encoding) {
  20100. const std::string compressed =
  20101. compress_payload_for_parity<Compressor>(original);
  20102. Server svr;
  20103. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20104. res.set_content(compressed, "application/octet-stream");
  20105. res.set_header("Content-Encoding", encoding);
  20106. });
  20107. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20108. auto se = detail::scope_exit([&] {
  20109. svr.stop();
  20110. t.join();
  20111. ASSERT_FALSE(svr.is_running());
  20112. });
  20113. svr.wait_until_ready();
  20114. Client cli(HOST, PORT);
  20115. // Non-streaming
  20116. {
  20117. auto res = cli.Get(path);
  20118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20119. EXPECT_EQ(StatusCode::OK_200, res->status);
  20120. EXPECT_EQ(original, res->body);
  20121. }
  20122. // Streaming
  20123. {
  20124. auto h = cli.open_stream("GET", path);
  20125. ASSERT_TRUE(h.is_valid());
  20126. EXPECT_EQ(original, read_all(h));
  20127. }
  20128. }
  20129. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20130. TEST(ParityTest, Gzip) {
  20131. test_compression_parity<detail::gzip_compressor>(
  20132. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20133. }
  20134. #endif
  20135. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20136. TEST(ParityTest, Brotli) {
  20137. test_compression_parity<detail::brotli_compressor>(
  20138. "Hello, brotli parity test payload", "/parity-br", "br");
  20139. }
  20140. #endif
  20141. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20142. TEST(ParityTest, Zstd) {
  20143. test_compression_parity<detail::zstd_compressor>(
  20144. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20145. }
  20146. #endif
  20147. //==============================================================================
  20148. // New Stream API Tests
  20149. //==============================================================================
  20150. inline std::string read_body(httplib::stream::Result &result) {
  20151. std::string body;
  20152. while (result.next()) {
  20153. body.append(result.data(), result.size());
  20154. }
  20155. return body;
  20156. }
  20157. TEST(ClientConnectionTest, Basic) {
  20158. httplib::ClientConnection conn;
  20159. EXPECT_FALSE(conn.is_open());
  20160. conn.sock = 1;
  20161. EXPECT_TRUE(conn.is_open());
  20162. httplib::ClientConnection conn2(std::move(conn));
  20163. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20164. conn2.sock = INVALID_SOCKET;
  20165. }
  20166. // Unified test server for all stream::* tests
  20167. class StreamApiTest : public ::testing::Test {
  20168. protected:
  20169. void SetUp() override {
  20170. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20171. res.set_content("Hello World!", "text/plain");
  20172. });
  20173. svr_.Get("/echo-params",
  20174. [](const httplib::Request &req, httplib::Response &res) {
  20175. std::string r;
  20176. for (const auto &p : req.params) {
  20177. if (!r.empty()) r += "&";
  20178. r += p.first + "=" + p.second;
  20179. }
  20180. res.set_content(r, "text/plain");
  20181. });
  20182. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20183. res.set_content(req.body, req.get_header_value("Content-Type"));
  20184. });
  20185. svr_.Post("/echo-headers",
  20186. [](const httplib::Request &req, httplib::Response &res) {
  20187. std::string r;
  20188. for (const auto &h : req.headers)
  20189. r += h.first + ": " + h.second + "\n";
  20190. res.set_content(r, "text/plain");
  20191. });
  20192. svr_.Post("/echo-params",
  20193. [](const httplib::Request &req, httplib::Response &res) {
  20194. std::string r = "params:";
  20195. for (const auto &p : req.params)
  20196. r += p.first + "=" + p.second + ";";
  20197. res.set_content(r + " body:" + req.body, "text/plain");
  20198. });
  20199. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20200. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20201. });
  20202. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20203. res.set_content("PUT:" + req.body, "text/plain");
  20204. });
  20205. svr_.Patch("/echo",
  20206. [](const httplib::Request &req, httplib::Response &res) {
  20207. res.set_content("PATCH:" + req.body, "text/plain");
  20208. });
  20209. svr_.Delete(
  20210. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20211. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20212. "text/plain");
  20213. });
  20214. svr_.Get("/head-test",
  20215. [](const httplib::Request &, httplib::Response &res) {
  20216. res.set_content("body for HEAD", "text/plain");
  20217. });
  20218. svr_.Options("/options",
  20219. [](const httplib::Request &, httplib::Response &res) {
  20220. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20221. });
  20222. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20223. svr_.wait_until_ready();
  20224. }
  20225. void TearDown() override {
  20226. svr_.stop();
  20227. if (thread_.joinable()) thread_.join();
  20228. }
  20229. httplib::Server svr_;
  20230. std::thread thread_;
  20231. };
  20232. // stream::Get tests
  20233. TEST_F(StreamApiTest, GetBasic) {
  20234. httplib::Client cli(HOST, PORT);
  20235. auto result = httplib::stream::Get(cli, "/hello");
  20236. ASSERT_TRUE(result.is_valid());
  20237. EXPECT_EQ(200, result.status());
  20238. EXPECT_EQ("Hello World!", read_body(result));
  20239. }
  20240. TEST_F(StreamApiTest, GetWithParams) {
  20241. httplib::Client cli(HOST, PORT);
  20242. httplib::Params params{{"foo", "bar"}};
  20243. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20244. ASSERT_TRUE(result.is_valid());
  20245. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20246. }
  20247. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20248. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20249. httplib::Client cli(HOST, PORT);
  20250. cli.set_payload_max_length(0);
  20251. auto result = httplib::stream::Get(cli, "/hello");
  20252. ASSERT_TRUE(result.is_valid());
  20253. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20254. EXPECT_EQ("Hello World!", read_body(result));
  20255. }
  20256. #endif
  20257. TEST_F(StreamApiTest, GetConnectionError) {
  20258. httplib::Client cli(HOST, 9999);
  20259. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20260. }
  20261. TEST_F(StreamApiTest, Get404) {
  20262. httplib::Client cli(HOST, PORT);
  20263. auto result = httplib::stream::Get(cli, "/nonexistent");
  20264. EXPECT_TRUE(result.is_valid());
  20265. EXPECT_EQ(404, result.status());
  20266. }
  20267. // stream::Post tests
  20268. TEST_F(StreamApiTest, PostBasic) {
  20269. httplib::Client cli(HOST, PORT);
  20270. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20271. "application/json");
  20272. ASSERT_TRUE(result.is_valid());
  20273. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20274. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20275. }
  20276. TEST_F(StreamApiTest, PostWithHeaders) {
  20277. httplib::Client cli(HOST, PORT);
  20278. httplib::Headers headers{{"X-Custom", "value"}};
  20279. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20280. "text/plain");
  20281. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20282. }
  20283. TEST_F(StreamApiTest, PostWithParams) {
  20284. httplib::Client cli(HOST, PORT);
  20285. httplib::Params params{{"k", "v"}};
  20286. auto result =
  20287. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20288. auto body = read_body(result);
  20289. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20290. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20291. }
  20292. TEST_F(StreamApiTest, PostLarge) {
  20293. httplib::Client cli(HOST, PORT);
  20294. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20295. size_t total = 0;
  20296. while (result.next()) {
  20297. total += result.size();
  20298. }
  20299. EXPECT_EQ(100u * 1024u, total);
  20300. }
  20301. // stream::Put/Patch tests
  20302. TEST_F(StreamApiTest, PutAndPatch) {
  20303. httplib::Client cli(HOST, PORT);
  20304. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20305. EXPECT_EQ("PUT:test", read_body(put));
  20306. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20307. EXPECT_EQ("PATCH:test", read_body(patch));
  20308. }
  20309. // stream::Delete tests
  20310. TEST_F(StreamApiTest, Delete) {
  20311. httplib::Client cli(HOST, PORT);
  20312. auto del1 = httplib::stream::Delete(cli, "/resource");
  20313. EXPECT_EQ("Deleted", read_body(del1));
  20314. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20315. EXPECT_EQ("Deleted:data", read_body(del2));
  20316. }
  20317. // stream::Head/Options tests
  20318. TEST_F(StreamApiTest, HeadAndOptions) {
  20319. httplib::Client cli(HOST, PORT);
  20320. auto head = httplib::stream::Head(cli, "/head-test");
  20321. EXPECT_TRUE(head.is_valid());
  20322. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20323. auto opts = httplib::stream::Options(cli, "/options");
  20324. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20325. }
  20326. // SSL stream::* tests
  20327. #ifdef CPPHTTPLIB_SSL_ENABLED
  20328. class SSLStreamApiTest : public ::testing::Test {
  20329. protected:
  20330. void SetUp() override {
  20331. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20332. res.set_content("Hello SSL!", "text/plain");
  20333. });
  20334. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20335. res.set_content(req.body, "text/plain");
  20336. });
  20337. port_ = svr_.bind_to_any_port("127.0.0.1");
  20338. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20339. svr_.wait_until_ready();
  20340. }
  20341. void TearDown() override {
  20342. svr_.stop();
  20343. if (thread_.joinable()) thread_.join();
  20344. }
  20345. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20346. std::thread thread_;
  20347. int port_ = 0;
  20348. };
  20349. TEST_F(SSLStreamApiTest, GetAndPost) {
  20350. httplib::SSLClient cli("127.0.0.1", port_);
  20351. cli.enable_server_certificate_verification(false);
  20352. auto get = httplib::stream::Get(cli, "/hello");
  20353. EXPECT_EQ("Hello SSL!", read_body(get));
  20354. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20355. EXPECT_EQ("test", read_body(post));
  20356. }
  20357. #endif
  20358. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20359. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20360. // BodyReader
  20361. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20362. // Test that read timeout during streaming is detected
  20363. // Use a large content-length response where server delays mid-stream
  20364. Server svr;
  20365. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20366. // Send a large response with delay in the middle
  20367. res.set_content_provider(
  20368. 1000, // content_length
  20369. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20370. if (offset < 100) {
  20371. // Send first 100 bytes immediately
  20372. std::string data(100, 'A');
  20373. sink.write(data.c_str(), data.size());
  20374. return true;
  20375. }
  20376. // Then delay longer than client timeout
  20377. std::this_thread::sleep_for(std::chrono::seconds(3));
  20378. std::string data(900, 'B');
  20379. sink.write(data.c_str(), data.size());
  20380. return true;
  20381. });
  20382. });
  20383. auto port = 8091;
  20384. std::thread t([&]() { svr.listen("localhost", port); });
  20385. svr.wait_until_ready();
  20386. Client cli("localhost", port);
  20387. cli.set_read_timeout(1, 0); // 1 second timeout
  20388. auto handle = cli.open_stream("GET", "/slow-stream");
  20389. ASSERT_TRUE(handle.is_valid());
  20390. char buf[256];
  20391. ssize_t total = 0;
  20392. ssize_t n;
  20393. bool got_error = false;
  20394. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20395. total += n;
  20396. }
  20397. if (n < 0) {
  20398. got_error = true;
  20399. // Should be timeout or read error
  20400. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20401. handle.get_read_error() == Error::Read)
  20402. << "Actual error: " << to_string(handle.get_read_error());
  20403. }
  20404. // Either we got an error, or we got less data than expected
  20405. EXPECT_TRUE(got_error || total < 1000)
  20406. << "Expected timeout but got all " << total << " bytes";
  20407. svr.stop();
  20408. t.join();
  20409. }
  20410. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20411. // Test connection closed detection via BodyReader
  20412. Server svr;
  20413. std::atomic<bool> close_now{false};
  20414. svr.Get("/will-close", [&](const Request &, Response &res) {
  20415. res.set_content_provider(
  20416. 10000, // Large content_length that we won't fully send
  20417. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20418. if (offset < 100) {
  20419. std::string data(100, 'X');
  20420. sink.write(data.c_str(), data.size());
  20421. return true;
  20422. }
  20423. // Wait for signal then abort
  20424. while (!close_now) {
  20425. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20426. }
  20427. return false; // Abort - server will close connection
  20428. });
  20429. });
  20430. auto port = 8092;
  20431. std::thread t([&]() { svr.listen("localhost", port); });
  20432. svr.wait_until_ready();
  20433. Client cli("localhost", port);
  20434. auto handle = cli.open_stream("GET", "/will-close");
  20435. ASSERT_TRUE(handle.is_valid());
  20436. char buf[256];
  20437. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20438. EXPECT_GT(n, 0) << "First read should succeed";
  20439. // Signal server to close
  20440. close_now = true;
  20441. // Keep reading until error or EOF
  20442. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20443. // Keep reading
  20444. }
  20445. // Should get an error since content_length wasn't satisfied
  20446. if (n < 0) {
  20447. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20448. handle.get_read_error() == Error::Read)
  20449. << "Actual error: " << to_string(handle.get_read_error());
  20450. }
  20451. svr.stop();
  20452. t.join();
  20453. }
  20454. #ifdef CPPHTTPLIB_SSL_ENABLED
  20455. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20456. // Test that read timeout during SSL streaming is detected
  20457. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20458. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20459. res.set_content_provider(
  20460. 1000, "text/plain",
  20461. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20462. if (offset < 100) {
  20463. std::string data(100, 'A');
  20464. sink.write(data.c_str(), data.size());
  20465. return true;
  20466. }
  20467. std::this_thread::sleep_for(std::chrono::seconds(3));
  20468. std::string data(900, 'B');
  20469. sink.write(data.c_str(), data.size());
  20470. return true;
  20471. });
  20472. });
  20473. auto port = 8093;
  20474. std::thread t([&]() { svr.listen("localhost", port); });
  20475. svr.wait_until_ready();
  20476. SSLClient cli("localhost", port);
  20477. cli.enable_server_certificate_verification(false);
  20478. cli.set_read_timeout(1, 0); // 1 second timeout
  20479. auto handle = cli.open_stream("GET", "/slow-stream");
  20480. ASSERT_TRUE(handle.is_valid());
  20481. char buf[256];
  20482. ssize_t total = 0;
  20483. ssize_t n;
  20484. bool got_error = false;
  20485. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20486. total += n;
  20487. }
  20488. if (n < 0) {
  20489. got_error = true;
  20490. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20491. handle.get_read_error() == Error::Read)
  20492. << "Actual error: " << to_string(handle.get_read_error());
  20493. }
  20494. EXPECT_TRUE(got_error || total < 1000)
  20495. << "Expected timeout but got all " << total << " bytes";
  20496. svr.stop();
  20497. t.join();
  20498. }
  20499. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20500. // Test SSL connection closed detection
  20501. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20502. std::atomic<bool> close_now{false};
  20503. svr.Get("/will-close", [&](const Request &, Response &res) {
  20504. res.set_content_provider(
  20505. 10000, "text/plain",
  20506. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20507. if (offset < 100) {
  20508. std::string data(100, 'X');
  20509. sink.write(data.c_str(), data.size());
  20510. return true;
  20511. }
  20512. while (!close_now) {
  20513. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20514. }
  20515. return false;
  20516. });
  20517. });
  20518. auto port = 8094;
  20519. std::thread t([&]() { svr.listen("localhost", port); });
  20520. svr.wait_until_ready();
  20521. SSLClient cli("localhost", port);
  20522. cli.enable_server_certificate_verification(false);
  20523. auto handle = cli.open_stream("GET", "/will-close");
  20524. ASSERT_TRUE(handle.is_valid());
  20525. char buf[256];
  20526. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20527. EXPECT_GT(n, 0);
  20528. // Signal server to close
  20529. close_now = true;
  20530. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20531. // Keep reading
  20532. }
  20533. if (n < 0) {
  20534. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20535. handle.get_read_error() == Error::Read)
  20536. << "Actual error: " << to_string(handle.get_read_error());
  20537. }
  20538. svr.stop();
  20539. t.join();
  20540. }
  20541. #endif
  20542. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20543. using namespace httplib;
  20544. // Create a test file
  20545. const char *fname = "etag_testfile.txt";
  20546. const char *content = "etag-content";
  20547. {
  20548. std::ofstream ofs(fname);
  20549. ofs << content;
  20550. ASSERT_TRUE(ofs.good());
  20551. }
  20552. Server svr;
  20553. svr.set_mount_point("/static", ".");
  20554. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20555. svr.wait_until_ready();
  20556. Client cli(HOST, PORT);
  20557. // First request: should get 200 with ETag header
  20558. auto res1 = cli.Get("/static/etag_testfile.txt");
  20559. ASSERT_TRUE(res1);
  20560. ASSERT_EQ(200, res1->status);
  20561. ASSERT_TRUE(res1->has_header("ETag"));
  20562. std::string etag = res1->get_header_value("ETag");
  20563. EXPECT_FALSE(etag.empty());
  20564. // Verify ETag format: W/"hex-hex"
  20565. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20566. EXPECT_EQ('W', etag[0]);
  20567. EXPECT_EQ('/', etag[1]);
  20568. EXPECT_EQ('"', etag[2]);
  20569. EXPECT_EQ('"', etag.back());
  20570. // Exact match: expect 304 Not Modified
  20571. Headers h2 = {{"If-None-Match", etag}};
  20572. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20573. ASSERT_TRUE(res2);
  20574. EXPECT_EQ(304, res2->status);
  20575. // Wildcard match: expect 304 Not Modified
  20576. Headers h3 = {{"If-None-Match", "*"}};
  20577. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20578. ASSERT_TRUE(res3);
  20579. EXPECT_EQ(304, res3->status);
  20580. // Non-matching ETag: expect 200
  20581. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20582. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20583. ASSERT_TRUE(res4);
  20584. EXPECT_EQ(200, res4->status);
  20585. // Multiple ETags with one matching: expect 304
  20586. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20587. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20588. ASSERT_TRUE(res5);
  20589. EXPECT_EQ(304, res5->status);
  20590. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20591. // that equivalent to the single comma-separated list above, so the match on
  20592. // the second line must still be found.
  20593. Headers h6;
  20594. h6.emplace("If-None-Match", "W/\"other\"");
  20595. h6.emplace("If-None-Match", etag);
  20596. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20597. ASSERT_TRUE(res6);
  20598. EXPECT_EQ(304, res6->status);
  20599. svr.stop();
  20600. t.join();
  20601. std::remove(fname);
  20602. }
  20603. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20604. using namespace httplib;
  20605. Server svr;
  20606. svr.set_mount_point("/static", ".");
  20607. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20608. svr.wait_until_ready();
  20609. Client cli(HOST, PORT);
  20610. // Send If-None-Match: * to a non-existent file
  20611. Headers h = {{"If-None-Match", "*"}};
  20612. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20614. EXPECT_EQ(404, res->status);
  20615. svr.stop();
  20616. t.join();
  20617. }
  20618. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20619. using namespace httplib;
  20620. // Create a test file
  20621. const char *fname = "etag_boundary_testfile.txt";
  20622. const char *content = "boundary-test";
  20623. {
  20624. std::ofstream ofs(fname);
  20625. ofs << content;
  20626. ASSERT_TRUE(ofs.good());
  20627. }
  20628. Server svr;
  20629. svr.set_mount_point("/static", ".");
  20630. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20631. svr.wait_until_ready();
  20632. Client cli(HOST, PORT);
  20633. // Get the actual ETag
  20634. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20635. ASSERT_TRUE(res1);
  20636. ASSERT_EQ(200, res1->status);
  20637. ASSERT_TRUE(res1->has_header("ETag"));
  20638. std::string etag = res1->get_header_value("ETag");
  20639. // Test 1: Very long ETag value (longer than actual ETag)
  20640. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20641. Headers h1 = {{"If-None-Match", "W/"
  20642. "\"very-long-etag-value-that-is-much-longer-"
  20643. "than-the-actual-etag-value\""}};
  20644. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20645. ASSERT_TRUE(res2);
  20646. EXPECT_EQ(200, res2->status); // Should not match
  20647. // Test 2: Long string followed by wildcard
  20648. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20649. // string)
  20650. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20651. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20652. ASSERT_TRUE(res3);
  20653. EXPECT_EQ(304, res3->status); // Should match on "*"
  20654. // Test 3: Wildcard followed by long string
  20655. // Should match on "*" immediately and return 304
  20656. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20657. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20658. ASSERT_TRUE(res4);
  20659. EXPECT_EQ(304, res4->status); // Should match on "*"
  20660. // Test 4: Multiple long non-matching values
  20661. // Should NOT match and return 200 (test that all comparisons are safe)
  20662. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20663. "W/\"second-long-non-matching-value\", "
  20664. "W/\"third-long-non-matching-value\""}};
  20665. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20666. ASSERT_TRUE(res5);
  20667. EXPECT_EQ(200, res5->status); // Should not match
  20668. // Test 5: Single character that is not "*" (edge case)
  20669. Headers h5 = {{"If-None-Match", "X"}};
  20670. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20671. ASSERT_TRUE(res6);
  20672. EXPECT_EQ(200, res6->status); // Should not match
  20673. svr.stop();
  20674. t.join();
  20675. std::remove(fname);
  20676. }
  20677. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20678. using namespace httplib;
  20679. // Create a test file
  20680. const char *fname = "ims_testfile.txt";
  20681. const char *content = "if-modified-since-test";
  20682. {
  20683. std::ofstream ofs(fname);
  20684. ofs << content;
  20685. ASSERT_TRUE(ofs.good());
  20686. }
  20687. Server svr;
  20688. svr.set_mount_point("/static", ".");
  20689. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20690. svr.wait_until_ready();
  20691. Client cli(HOST, PORT);
  20692. // First request: should get 200 with Last-Modified header
  20693. auto res1 = cli.Get("/static/ims_testfile.txt");
  20694. ASSERT_TRUE(res1);
  20695. ASSERT_EQ(200, res1->status);
  20696. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20697. std::string last_modified = res1->get_header_value("Last-Modified");
  20698. EXPECT_FALSE(last_modified.empty());
  20699. // If-Modified-Since with same time: expect 304
  20700. Headers h2 = {{"If-Modified-Since", last_modified}};
  20701. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20702. ASSERT_TRUE(res2);
  20703. EXPECT_EQ(304, res2->status);
  20704. // If-Modified-Since with future time: expect 304
  20705. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20706. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20707. ASSERT_TRUE(res3);
  20708. EXPECT_EQ(304, res3->status);
  20709. // If-Modified-Since with past time: expect 200
  20710. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20711. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20712. ASSERT_TRUE(res4);
  20713. EXPECT_EQ(200, res4->status);
  20714. // If-None-Match takes precedence over If-Modified-Since
  20715. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20716. ASSERT_TRUE(res1->has_header("ETag"));
  20717. std::string etag = res1->get_header_value("ETag");
  20718. Headers h5 = {{"If-None-Match", etag},
  20719. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20720. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20721. ASSERT_TRUE(res5);
  20722. EXPECT_EQ(304, res5->status);
  20723. svr.stop();
  20724. t.join();
  20725. std::remove(fname);
  20726. }
  20727. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20728. using namespace httplib;
  20729. Server svr;
  20730. // Endpoint that returns compressible content
  20731. svr.Get("/compressible", [](const Request &, Response &res) {
  20732. // Return a large enough body to trigger compression
  20733. std::string body(1000, 'a');
  20734. res.set_content(body, "text/plain");
  20735. });
  20736. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20737. svr.wait_until_ready();
  20738. Client cli(HOST, PORT);
  20739. // Request with gzip support: should get Vary header when compressed
  20740. cli.set_compress(true);
  20741. auto res1 = cli.Get("/compressible");
  20742. ASSERT_TRUE(res1);
  20743. EXPECT_EQ(200, res1->status);
  20744. // If Content-Encoding is set, Vary should also be set
  20745. if (res1->has_header("Content-Encoding")) {
  20746. EXPECT_TRUE(res1->has_header("Vary"));
  20747. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20748. }
  20749. // Request without Accept-Encoding header: should not have compression
  20750. Headers h_no_compress;
  20751. auto res2 = cli.Get("/compressible", h_no_compress);
  20752. ASSERT_TRUE(res2);
  20753. EXPECT_EQ(200, res2->status);
  20754. // Verify Vary header is present when compression is applied
  20755. // (the exact behavior depends on server configuration)
  20756. svr.stop();
  20757. t.join();
  20758. }
  20759. TEST(ETagTest, IfRangeWithETag) {
  20760. using namespace httplib;
  20761. // Create a test file with known content
  20762. const char *fname = "if_range_testfile.txt";
  20763. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20764. {
  20765. std::ofstream ofs(fname);
  20766. ofs << content;
  20767. ASSERT_TRUE(ofs.good());
  20768. }
  20769. Server svr;
  20770. svr.set_mount_point("/static", ".");
  20771. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20772. svr.wait_until_ready();
  20773. Client cli(HOST, PORT);
  20774. // First request: get ETag
  20775. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20776. ASSERT_TRUE(res1);
  20777. ASSERT_EQ(200, res1->status);
  20778. ASSERT_TRUE(res1->has_header("ETag"));
  20779. std::string etag = res1->get_header_value("ETag");
  20780. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20781. // Since our server generates weak ETags (W/"..."), If-Range with our
  20782. // ETag should NOT result in partial content - it should return full content.
  20783. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20784. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20785. ASSERT_TRUE(res2);
  20786. // Weak ETag in If-Range -> full content (200), not partial (206)
  20787. EXPECT_EQ(200, res2->status);
  20788. EXPECT_EQ(content, res2->body);
  20789. EXPECT_FALSE(res2->has_header("Content-Range"));
  20790. // Range request with non-matching If-Range (ETag): should get 200 (full
  20791. // content)
  20792. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20793. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20794. ASSERT_TRUE(res3);
  20795. EXPECT_EQ(200, res3->status);
  20796. EXPECT_EQ(content, res3->body);
  20797. EXPECT_FALSE(res3->has_header("Content-Range"));
  20798. // Range request with strong ETag (hypothetical - our server doesn't generate
  20799. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20800. // should return full content)
  20801. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20802. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20803. ASSERT_TRUE(res4);
  20804. EXPECT_EQ(200, res4->status);
  20805. EXPECT_EQ(content, res4->body);
  20806. EXPECT_FALSE(res4->has_header("Content-Range"));
  20807. svr.stop();
  20808. t.join();
  20809. std::remove(fname);
  20810. }
  20811. TEST(ETagTest, IfRangeWithDate) {
  20812. using namespace httplib;
  20813. // Create a test file
  20814. const char *fname = "if_range_date_testfile.txt";
  20815. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20816. {
  20817. std::ofstream ofs(fname);
  20818. ofs << content;
  20819. ASSERT_TRUE(ofs.good());
  20820. }
  20821. Server svr;
  20822. svr.set_mount_point("/static", ".");
  20823. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20824. svr.wait_until_ready();
  20825. Client cli(HOST, PORT);
  20826. // First request: get Last-Modified
  20827. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20828. ASSERT_TRUE(res1);
  20829. ASSERT_EQ(200, res1->status);
  20830. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20831. std::string last_modified = res1->get_header_value("Last-Modified");
  20832. // Range request with matching If-Range (date): should get 206
  20833. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20834. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20835. ASSERT_TRUE(res2);
  20836. EXPECT_EQ(206, res2->status);
  20837. EXPECT_EQ("FGHIJ", res2->body);
  20838. // Range request with old If-Range date: should get 200 (full content)
  20839. Headers h3 = {{"Range", "bytes=5-9"},
  20840. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20841. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20842. ASSERT_TRUE(res3);
  20843. EXPECT_EQ(200, res3->status);
  20844. EXPECT_EQ(content, res3->body);
  20845. // Range request with future If-Range date: should get 206
  20846. Headers h4 = {{"Range", "bytes=0-4"},
  20847. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20848. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20849. ASSERT_TRUE(res4);
  20850. EXPECT_EQ(206, res4->status);
  20851. EXPECT_EQ("ABCDE", res4->body);
  20852. svr.stop();
  20853. t.join();
  20854. std::remove(fname);
  20855. }
  20856. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20857. using namespace httplib;
  20858. const char *fname = "etag_malformed.txt";
  20859. const char *content = "malformed-etag";
  20860. {
  20861. std::ofstream ofs(fname);
  20862. ofs << content;
  20863. ASSERT_TRUE(ofs.good());
  20864. }
  20865. Server svr;
  20866. svr.set_mount_point("/static", ".");
  20867. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20868. svr.wait_until_ready();
  20869. Client cli(HOST, PORT);
  20870. // baseline: should get 200 and an ETag
  20871. auto res1 = cli.Get("/static/etag_malformed.txt");
  20872. ASSERT_TRUE(res1);
  20873. ASSERT_EQ(200, res1->status);
  20874. ASSERT_TRUE(res1->has_header("ETag"));
  20875. // Malformed ETag value (missing quotes) should be treated as non-matching
  20876. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20877. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20878. ASSERT_TRUE(res_bad);
  20879. EXPECT_EQ(200, res_bad->status);
  20880. // Whitespace-only header value should be considered invalid / non-matching
  20881. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20882. "Host: localhost\r\n"
  20883. "If-None-Match: \r\n"
  20884. "Connection: close\r\n"
  20885. "\r\n";
  20886. std::string out;
  20887. ASSERT_TRUE(send_request(5, raw_req, &out));
  20888. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20889. svr.stop();
  20890. t.join();
  20891. std::remove(fname);
  20892. }
  20893. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20894. using namespace httplib;
  20895. const char *fname = "ims_invalid_format.txt";
  20896. const char *content = "ims-bad-format";
  20897. {
  20898. std::ofstream ofs(fname);
  20899. ofs << content;
  20900. ASSERT_TRUE(ofs.good());
  20901. }
  20902. Server svr;
  20903. svr.set_mount_point("/static", ".");
  20904. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20905. svr.wait_until_ready();
  20906. Client cli(HOST, PORT);
  20907. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20908. ASSERT_TRUE(res1);
  20909. ASSERT_EQ(200, res1->status);
  20910. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20911. // If-Modified-Since with invalid format should not result in 304
  20912. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20913. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20914. ASSERT_TRUE(res_bad);
  20915. EXPECT_EQ(200, res_bad->status);
  20916. // If-Range with invalid date format should be treated as mismatch -> full
  20917. // content (200)
  20918. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20919. {"If-Range", "invalid-date"}};
  20920. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20921. ASSERT_TRUE(res_ifrange);
  20922. EXPECT_EQ(200, res_ifrange->status);
  20923. svr.stop();
  20924. t.join();
  20925. std::remove(fname);
  20926. }
  20927. TEST(ETagTest, IfRangeWithMalformedETag) {
  20928. using namespace httplib;
  20929. const char *fname = "ifrange_malformed.txt";
  20930. const std::string content = "0123456789";
  20931. {
  20932. std::ofstream ofs(fname);
  20933. ofs << content;
  20934. ASSERT_TRUE(ofs.good());
  20935. }
  20936. Server svr;
  20937. svr.set_mount_point("/static", ".");
  20938. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20939. svr.wait_until_ready();
  20940. Client cli(HOST, PORT);
  20941. // First request: get ETag
  20942. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20943. ASSERT_TRUE(res1);
  20944. ASSERT_EQ(200, res1->status);
  20945. ASSERT_TRUE(res1->has_header("ETag"));
  20946. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20947. // full content (200)
  20948. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20949. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20950. ASSERT_TRUE(res2);
  20951. EXPECT_EQ(200, res2->status);
  20952. EXPECT_EQ(content, res2->body);
  20953. svr.stop();
  20954. t.join();
  20955. std::remove(fname);
  20956. }
  20957. TEST(ETagTest, ExtremeLargeDateValues) {
  20958. using namespace httplib;
  20959. const char *fname = "ims_extreme_date.txt";
  20960. const char *content = "ims-extreme-date";
  20961. {
  20962. std::ofstream ofs(fname);
  20963. ofs << content;
  20964. ASSERT_TRUE(ofs.good());
  20965. }
  20966. Server svr;
  20967. svr.set_mount_point("/static", ".");
  20968. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20969. svr.wait_until_ready();
  20970. Client cli(HOST, PORT);
  20971. auto res1 = cli.Get(std::string("/static/") + fname);
  20972. ASSERT_TRUE(res1);
  20973. ASSERT_EQ(200, res1->status);
  20974. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20975. // Extremely large year that may overflow date parsing routines.
  20976. Headers h_large_date = {
  20977. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20978. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20979. ASSERT_TRUE(res_bad);
  20980. // Expect server to treat this as invalid/mismatch and return full content
  20981. EXPECT_EQ(200, res_bad->status);
  20982. // If-Range with extremely large date should be treated as mismatch -> full
  20983. // content (200)
  20984. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20985. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20986. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20987. ASSERT_TRUE(res_ifrange);
  20988. EXPECT_EQ(200, res_ifrange->status);
  20989. svr.stop();
  20990. t.join();
  20991. std::remove(fname);
  20992. }
  20993. TEST(ETagTest, NegativeFileModificationTime) {
  20994. using namespace httplib;
  20995. const char *fname = "ims_negative_mtime.txt";
  20996. const std::string content = "negative-mtime";
  20997. {
  20998. std::ofstream ofs(fname);
  20999. ofs << content;
  21000. ASSERT_TRUE(ofs.good());
  21001. }
  21002. // Try to set file mtime to a negative value. This may fail on some
  21003. // platforms/filesystems; if it fails, the test will still verify server
  21004. // behaves safely by performing a regular conditional request.
  21005. #if defined(__APPLE__) || defined(__linux__)
  21006. bool set_negative = false;
  21007. do {
  21008. struct timeval times[2];
  21009. // access time: now
  21010. times[0].tv_sec = time(nullptr);
  21011. times[0].tv_usec = 0;
  21012. // modification time: negative (e.g., -1)
  21013. times[1].tv_sec = -1;
  21014. times[1].tv_usec = 0;
  21015. if (utimes(fname, times) == 0) { set_negative = true; }
  21016. } while (0);
  21017. #else
  21018. bool set_negative = false;
  21019. #endif
  21020. Server svr;
  21021. svr.set_mount_point("/static", ".");
  21022. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21023. svr.wait_until_ready();
  21024. Client cli(HOST, PORT);
  21025. auto res1 = cli.Get(std::string("/static/") + fname);
  21026. ASSERT_TRUE(res1);
  21027. ASSERT_EQ(200, res1->status);
  21028. bool has_last_modified = res1->has_header("Last-Modified");
  21029. std::string last_modified;
  21030. if (has_last_modified) {
  21031. last_modified = res1->get_header_value("Last-Modified");
  21032. }
  21033. if (set_negative) {
  21034. // If we successfully set a negative mtime, ensure server returns a
  21035. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21036. // with an old date and ensure server handles it without crash.
  21037. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21038. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21039. ASSERT_TRUE(res2);
  21040. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21041. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21042. } else {
  21043. // Could not set negative mtime on this platform; fall back to verifying
  21044. // that normal invalid/malformed dates are treated safely (non-304).
  21045. Headers h_bad_date = {
  21046. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21047. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21048. ASSERT_TRUE(res_bad);
  21049. EXPECT_EQ(200, res_bad->status);
  21050. }
  21051. svr.stop();
  21052. t.join();
  21053. std::remove(fname);
  21054. }
  21055. //==============================================================================
  21056. // Integration Tests with Server
  21057. //==============================================================================
  21058. class SSEIntegrationTest : public ::testing::Test {
  21059. protected:
  21060. void SetUp() override {
  21061. stop_server_.store(false);
  21062. events_.clear();
  21063. server_ = httplib::detail::make_unique<Server>();
  21064. setup_server();
  21065. start_server();
  21066. }
  21067. void TearDown() override {
  21068. stop_server_.store(true);
  21069. event_cv_.notify_all();
  21070. server_->stop();
  21071. if (server_thread_.joinable()) { server_thread_.join(); }
  21072. }
  21073. void setup_server() {
  21074. // Simple SSE endpoint
  21075. server_->Get("/events", [this](const Request &req, Response &res) {
  21076. auto last_id = req.get_header_value("Last-Event-ID");
  21077. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21078. res.set_chunked_content_provider(
  21079. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21080. std::unique_lock<std::mutex> lock(event_mutex_);
  21081. if (event_cv_.wait_for(
  21082. lock, std::chrono::milliseconds(200), [this] {
  21083. return !events_.empty() || stop_server_.load();
  21084. })) {
  21085. if (stop_server_.load()) { return false; }
  21086. if (!events_.empty()) {
  21087. std::string event = events_.front();
  21088. events_.erase(events_.begin());
  21089. sink.write(event.data(), event.size());
  21090. return true;
  21091. }
  21092. }
  21093. return !stop_server_.load();
  21094. });
  21095. });
  21096. // Endpoint that returns error
  21097. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21098. res.status = 500;
  21099. res.set_content("Internal Server Error", "text/plain");
  21100. });
  21101. // Endpoint for custom event types
  21102. server_->Get("/custom-events", [](const Request &, Response &res) {
  21103. res.set_chunked_content_provider(
  21104. "text/event-stream", [](size_t offset, DataSink &sink) {
  21105. if (offset == 0) {
  21106. std::string event = "event: update\ndata: updated\n\n"
  21107. "event: delete\ndata: deleted\n\n";
  21108. sink.write(event.data(), event.size());
  21109. }
  21110. return false; // End stream after sending
  21111. });
  21112. });
  21113. }
  21114. void start_server() {
  21115. port_ = server_->bind_to_any_port(HOST);
  21116. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21117. // Wait for server to start
  21118. while (!server_->is_running()) {
  21119. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21120. }
  21121. }
  21122. int get_port() const { return port_; }
  21123. void send_event(const std::string &event) {
  21124. std::lock_guard<std::mutex> lock(event_mutex_);
  21125. events_.push_back(event);
  21126. event_cv_.notify_all();
  21127. }
  21128. std::unique_ptr<Server> server_;
  21129. std::thread server_thread_;
  21130. std::mutex event_mutex_;
  21131. std::condition_variable event_cv_;
  21132. std::vector<std::string> events_;
  21133. std::atomic<bool> stop_server_{false};
  21134. std::string last_received_event_id_;
  21135. int port_ = 0;
  21136. };
  21137. //==============================================================================
  21138. // SSE Parsing Tests
  21139. //==============================================================================
  21140. class SSEParsingTest : public SSEIntegrationTest {
  21141. protected:
  21142. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21143. // A trailing sentinel event tells when the whole stream has been parsed.
  21144. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21145. auto body = stream + "event: end\ndata: end\n\n";
  21146. server_->Get("/parse", [body](const Request &, Response &res) {
  21147. res.set_content(body, "text/event-stream");
  21148. });
  21149. return collect("/parse");
  21150. }
  21151. // Runs SSEClient against path until an "end" event arrives and returns the
  21152. // messages dispatched before it
  21153. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21154. Client client(HOST, get_port());
  21155. sse::SSEClient sse(client, path);
  21156. std::mutex mutex;
  21157. std::condition_variable cv;
  21158. std::vector<sse::SSEMessage> messages;
  21159. auto done = false;
  21160. sse.on_message([&](const sse::SSEMessage &msg) {
  21161. std::lock_guard<std::mutex> lock(mutex);
  21162. // Ignore a replay from a reconnect that races with stop()
  21163. if (!done) { messages.push_back(msg); }
  21164. });
  21165. sse.on_event("end", [&](const sse::SSEMessage &) {
  21166. std::lock_guard<std::mutex> lock(mutex);
  21167. done = true;
  21168. cv.notify_all();
  21169. });
  21170. sse.set_reconnect_interval(100);
  21171. sse.start_async();
  21172. {
  21173. std::unique_lock<std::mutex> lock(mutex);
  21174. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21175. }
  21176. sse.stop();
  21177. EXPECT_TRUE(done);
  21178. return messages;
  21179. }
  21180. };
  21181. TEST_F(SSEParsingTest, SingleLineData) {
  21182. auto msgs = parse("data: hello\n\n");
  21183. ASSERT_EQ(msgs.size(), 1u);
  21184. EXPECT_EQ(msgs[0].data, "hello");
  21185. EXPECT_EQ(msgs[0].event, "message");
  21186. }
  21187. TEST_F(SSEParsingTest, MultiLineData) {
  21188. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21189. ASSERT_EQ(msgs.size(), 1u);
  21190. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21191. }
  21192. TEST_F(SSEParsingTest, CustomEventType) {
  21193. auto msgs = parse("event: update\ndata: payload\n\n");
  21194. ASSERT_EQ(msgs.size(), 1u);
  21195. EXPECT_EQ(msgs[0].event, "update");
  21196. EXPECT_EQ(msgs[0].data, "payload");
  21197. }
  21198. TEST_F(SSEParsingTest, EventIdHandling) {
  21199. auto msgs = parse("id: 12345\ndata: test\n\n");
  21200. ASSERT_EQ(msgs.size(), 1u);
  21201. EXPECT_EQ(msgs[0].id, "12345");
  21202. }
  21203. TEST_F(SSEParsingTest, EmptyEventId) {
  21204. auto msgs = parse("id:\ndata: test\n\n");
  21205. ASSERT_EQ(msgs.size(), 1u);
  21206. EXPECT_EQ(msgs[0].id, "");
  21207. }
  21208. TEST_F(SSEParsingTest, CommentsIgnored) {
  21209. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21210. ASSERT_EQ(msgs.size(), 1u);
  21211. EXPECT_EQ(msgs[0].data, "hello");
  21212. EXPECT_EQ(msgs[0].event, "message");
  21213. }
  21214. TEST_F(SSEParsingTest, ColonInValue) {
  21215. auto msgs = parse("data: hello:world:test\n\n");
  21216. ASSERT_EQ(msgs.size(), 1u);
  21217. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21218. }
  21219. TEST_F(SSEParsingTest, FieldNameOnly) {
  21220. // A line without a colon is a field name with an empty value
  21221. auto msgs = parse("data\n\n");
  21222. ASSERT_EQ(msgs.size(), 1u);
  21223. EXPECT_EQ(msgs[0].data, "");
  21224. }
  21225. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21226. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21227. ASSERT_EQ(msgs.size(), 1u);
  21228. EXPECT_EQ(msgs[0].event, "update");
  21229. EXPECT_EQ(msgs[0].data, "hello");
  21230. }
  21231. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21232. auto msgs = parse("data\r\n\r\n");
  21233. ASSERT_EQ(msgs.size(), 1u);
  21234. EXPECT_EQ(msgs[0].data, "");
  21235. }
  21236. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21237. auto msgs = parse("event: update\rdata: hello\r\r");
  21238. ASSERT_EQ(msgs.size(), 1u);
  21239. EXPECT_EQ(msgs[0].event, "update");
  21240. EXPECT_EQ(msgs[0].data, "hello");
  21241. }
  21242. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21243. // Chunk boundaries fall inside every \r\n and right before the first one
  21244. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21245. "\n\r", "\nevent: end\ndata: end\n\n"};
  21246. server_->Get("/split", [chunks](const Request &, Response &res) {
  21247. auto i = std::make_shared<size_t>(0);
  21248. res.set_chunked_content_provider(
  21249. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21250. if (*i == chunks.size()) {
  21251. sink.done();
  21252. } else {
  21253. sink.write(chunks[*i].data(), chunks[*i].size());
  21254. (*i)++;
  21255. }
  21256. return true;
  21257. });
  21258. });
  21259. auto msgs = collect("/split");
  21260. ASSERT_EQ(msgs.size(), 1u);
  21261. EXPECT_EQ(msgs[0].event, "update");
  21262. EXPECT_EQ(msgs[0].data, "hello");
  21263. }
  21264. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21265. // Only a BOM at the start of the stream is ignored
  21266. auto msgs = parse("\xEF\xBB\xBF"
  21267. "data: first\n\n"
  21268. "\xEF\xBB\xBF"
  21269. "data: second\n\n");
  21270. ASSERT_EQ(msgs.size(), 1u);
  21271. EXPECT_EQ(msgs[0].data, "first");
  21272. }
  21273. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21274. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21275. ASSERT_EQ(msgs.size(), 1u);
  21276. EXPECT_EQ(msgs[0].data, "hello");
  21277. EXPECT_EQ(msgs[0].event, "message");
  21278. }
  21279. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21280. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21281. ASSERT_EQ(msgs.size(), 2u);
  21282. EXPECT_EQ(msgs[0].data, "hello");
  21283. EXPECT_EQ(msgs[1].data, "hello");
  21284. }
  21285. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21286. // An event without data is not dispatched, and its type must not leak
  21287. // into the next event
  21288. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21289. ASSERT_EQ(msgs.size(), 1u);
  21290. EXPECT_EQ(msgs[0].event, "message");
  21291. EXPECT_EQ(msgs[0].data, "hello");
  21292. }
  21293. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21294. // Also when the empty field replaces an earlier type
  21295. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21296. ASSERT_EQ(msgs.size(), 2u);
  21297. EXPECT_EQ(msgs[0].event, "message");
  21298. EXPECT_EQ(msgs[1].event, "message");
  21299. }
  21300. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21301. // The first connection sends only an id; the second echoes back the
  21302. // Last-Event-ID it was reconnected with
  21303. std::atomic<int> connection_count{0};
  21304. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21305. if (connection_count++ == 0) {
  21306. res.set_content("id: 42\n\n", "text/event-stream");
  21307. } else {
  21308. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21309. "\n\nevent: end\ndata: end\n\n",
  21310. "text/event-stream");
  21311. }
  21312. });
  21313. auto msgs = collect("/id-only");
  21314. ASSERT_EQ(msgs.size(), 1u);
  21315. EXPECT_EQ(msgs[0].data, "42");
  21316. }
  21317. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21318. // The first connection sets an id and then clears it with an empty one; the
  21319. // second reports whether it was reconnected with a Last-Event-ID
  21320. std::atomic<int> connection_count{0};
  21321. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21322. if (connection_count++ == 0) {
  21323. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21324. "text/event-stream");
  21325. } else {
  21326. res.set_content(
  21327. std::string("data: ") +
  21328. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21329. "\n\nevent: end\ndata: end\n\n",
  21330. "text/event-stream");
  21331. }
  21332. });
  21333. auto msgs = collect("/id-clear");
  21334. ASSERT_EQ(msgs.size(), 3u);
  21335. EXPECT_EQ(msgs[0].id, "1");
  21336. EXPECT_EQ(msgs[1].id, "");
  21337. EXPECT_EQ(msgs[2].data, "not sent");
  21338. }
  21339. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21340. // The first connection sets an id and then sends ids that cannot be carried
  21341. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21342. // with
  21343. std::atomic<int> connection_count{0};
  21344. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21345. if (connection_count++ == 0) {
  21346. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21347. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21348. "text/event-stream");
  21349. } else {
  21350. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21351. "\n\nevent: end\ndata: end\n\n",
  21352. "text/event-stream");
  21353. }
  21354. });
  21355. auto msgs = collect("/id-unsendable");
  21356. ASSERT_EQ(msgs.size(), 1u);
  21357. EXPECT_EQ(msgs[0].data, "42");
  21358. }
  21359. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21360. auto msgs = parse("event: notification\nid: evt-42\n"
  21361. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21362. ASSERT_EQ(msgs.size(), 1u);
  21363. EXPECT_EQ(msgs[0].event, "notification");
  21364. EXPECT_EQ(msgs[0].id, "evt-42");
  21365. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21366. }
  21367. TEST(SSEMessageTest, Clear) {
  21368. sse::SSEMessage msg;
  21369. msg.event = "custom";
  21370. msg.data = "some data";
  21371. msg.id = "123";
  21372. msg.clear();
  21373. EXPECT_EQ(msg.event, "message");
  21374. EXPECT_EQ(msg.data, "");
  21375. EXPECT_EQ(msg.id, "");
  21376. }
  21377. //==============================================================================
  21378. // SSE Integration Tests
  21379. //==============================================================================
  21380. // Test: Successful connection and on_open callback
  21381. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21382. // Add a simple endpoint that sends one event and closes
  21383. server_->Get("/simple-event", [](const Request &, Response &res) {
  21384. res.set_chunked_content_provider(
  21385. "text/event-stream", [](size_t offset, DataSink &sink) {
  21386. if (offset == 0) {
  21387. std::string event = "data: hello\n\n";
  21388. sink.write(event.data(), event.size());
  21389. }
  21390. return false; // Close stream after sending
  21391. });
  21392. });
  21393. Client client("localhost", get_port());
  21394. sse::SSEClient sse(client, "/simple-event");
  21395. std::atomic<bool> open_called{false};
  21396. std::atomic<bool> message_received{false};
  21397. sse.on_open([&open_called]() { open_called.store(true); });
  21398. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21399. if (msg.data == "hello") { message_received.store(true); }
  21400. });
  21401. sse.set_reconnect_interval(100);
  21402. sse.set_max_reconnect_attempts(1);
  21403. // Start async
  21404. sse.start_async();
  21405. // Wait for message to be processed
  21406. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21407. sse.stop();
  21408. EXPECT_TRUE(open_called.load());
  21409. EXPECT_TRUE(message_received.load());
  21410. }
  21411. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21412. // A data line that never ends.
  21413. server_->Get("/endless-line", [](const Request &, Response &res) {
  21414. res.set_chunked_content_provider(
  21415. "text/event-stream", [](size_t offset, DataSink &sink) {
  21416. if (offset == 0) { sink.write("data: ", 6); }
  21417. std::string chunk(64 * 1024, 'A');
  21418. return sink.write(chunk.data(), chunk.size());
  21419. });
  21420. });
  21421. Client client("localhost", get_port());
  21422. sse::SSEClient sse(client, "/endless-line");
  21423. std::atomic<bool> too_long{false};
  21424. sse.on_error([&](Error err) {
  21425. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21426. });
  21427. sse.set_max_reconnect_attempts(1);
  21428. sse.start_async();
  21429. for (int i = 0; i < 500 && !too_long; i++) {
  21430. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21431. }
  21432. sse.stop();
  21433. EXPECT_TRUE(too_long);
  21434. }
  21435. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21436. // Far more in all than the client's payload limit below.
  21437. server_->Get("/many-events", [](const Request &, Response &res) {
  21438. res.set_chunked_content_provider(
  21439. "text/event-stream", [](size_t offset, DataSink &sink) {
  21440. if (offset == 0) {
  21441. std::string events;
  21442. for (int i = 0; i < 1000; i++) {
  21443. events += "data: message\n\n";
  21444. }
  21445. sink.write(events.data(), events.size());
  21446. }
  21447. return false;
  21448. });
  21449. });
  21450. Client client("localhost", get_port());
  21451. client.set_payload_max_length(1024);
  21452. sse::SSEClient sse(client, "/many-events");
  21453. std::atomic<int> messages{0};
  21454. std::atomic<bool> too_large{false};
  21455. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21456. sse.on_error([&](Error err) {
  21457. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21458. });
  21459. sse.set_max_reconnect_attempts(1);
  21460. sse.start_async();
  21461. for (int i = 0; i < 500 && messages < 1000; i++) {
  21462. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21463. }
  21464. sse.stop();
  21465. EXPECT_GE(messages.load(), 1000);
  21466. EXPECT_FALSE(too_large);
  21467. }
  21468. // Test: on_message callback
  21469. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21470. // Endpoint that sends multiple events then closes
  21471. server_->Get("/multi-event", [](const Request &, Response &res) {
  21472. res.set_chunked_content_provider(
  21473. "text/event-stream", [](size_t offset, DataSink &sink) {
  21474. if (offset == 0) {
  21475. std::string events = "data: message1\n\ndata: message2\n\n";
  21476. sink.write(events.data(), events.size());
  21477. }
  21478. return false;
  21479. });
  21480. });
  21481. Client client("localhost", get_port());
  21482. sse::SSEClient sse(client, "/multi-event");
  21483. std::vector<std::string> received_messages;
  21484. std::mutex messages_mutex;
  21485. sse.on_message([&](const sse::SSEMessage &msg) {
  21486. std::lock_guard<std::mutex> lock(messages_mutex);
  21487. received_messages.push_back(msg.data);
  21488. });
  21489. sse.set_reconnect_interval(100);
  21490. sse.set_max_reconnect_attempts(1);
  21491. sse.start_async();
  21492. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21493. sse.stop();
  21494. std::lock_guard<std::mutex> lock(messages_mutex);
  21495. EXPECT_GE(received_messages.size(), 2u);
  21496. if (received_messages.size() >= 2) {
  21497. EXPECT_EQ(received_messages[0], "message1");
  21498. EXPECT_EQ(received_messages[1], "message2");
  21499. }
  21500. }
  21501. // Test: on_event for specific types
  21502. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21503. Client client("localhost", get_port());
  21504. sse::SSEClient sse(client, "/custom-events");
  21505. std::atomic<bool> update_received{false};
  21506. std::atomic<bool> delete_received{false};
  21507. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21508. if (msg.data == "updated") { update_received.store(true); }
  21509. });
  21510. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21511. if (msg.data == "deleted") { delete_received.store(true); }
  21512. });
  21513. sse.set_max_reconnect_attempts(1);
  21514. sse.start_async();
  21515. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21516. sse.stop();
  21517. EXPECT_TRUE(update_received.load());
  21518. EXPECT_TRUE(delete_received.load());
  21519. }
  21520. // Test: on_error callback on connection failure
  21521. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21522. // Connect to a non-existent port
  21523. Client client("localhost", 59999);
  21524. sse::SSEClient sse(client, "/events");
  21525. std::atomic<bool> error_called{false};
  21526. Error received_error = Error::Success;
  21527. sse.on_error([&](Error err) {
  21528. error_called.store(true);
  21529. received_error = err;
  21530. });
  21531. sse.set_reconnect_interval(50);
  21532. sse.set_max_reconnect_attempts(1);
  21533. sse.start_async();
  21534. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21535. sse.stop();
  21536. EXPECT_TRUE(error_called.load());
  21537. EXPECT_NE(received_error, Error::Success);
  21538. }
  21539. // Test: Last-Event-ID header sent on reconnect
  21540. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21541. // Endpoint that sends event with ID
  21542. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21543. res.set_chunked_content_provider(
  21544. "text/event-stream", [](size_t offset, DataSink &sink) {
  21545. if (offset == 0) {
  21546. std::string event = "id: evt-123\ndata: test\n\n";
  21547. sink.write(event.data(), event.size());
  21548. }
  21549. return false;
  21550. });
  21551. });
  21552. Client client("localhost", get_port());
  21553. sse::SSEClient sse(client, "/event-with-id");
  21554. std::atomic<bool> id_received{false};
  21555. sse.on_message([&](const sse::SSEMessage &msg) {
  21556. if (!msg.id.empty()) { id_received.store(true); }
  21557. });
  21558. sse.set_reconnect_interval(100);
  21559. sse.set_max_reconnect_attempts(1);
  21560. sse.start_async();
  21561. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21562. sse.stop();
  21563. EXPECT_TRUE(id_received.load());
  21564. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21565. }
  21566. // Test: Manual stop
  21567. TEST_F(SSEIntegrationTest, ManualStop) {
  21568. // Endpoint that sends one event and stays open briefly. The server outlives
  21569. // this test body, so the provider uses the fixture's flag, not a local.
  21570. server_->Get("/stay-open", [this](const Request &, Response &res) {
  21571. res.set_chunked_content_provider(
  21572. "text/event-stream", [this](size_t offset, DataSink &sink) {
  21573. if (offset == 0) {
  21574. std::string event = "data: connected\n\n";
  21575. sink.write(event.data(), event.size());
  21576. }
  21577. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  21578. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21579. }
  21580. return false;
  21581. });
  21582. });
  21583. Client client("localhost", get_port());
  21584. sse::SSEClient sse(client, "/stay-open");
  21585. std::atomic<bool> connected{false};
  21586. sse.on_open([&connected]() { connected.store(true); });
  21587. sse.set_reconnect_interval(100);
  21588. sse.set_max_reconnect_attempts(1);
  21589. sse.start_async();
  21590. // Wait for connection to establish
  21591. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21592. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21593. }
  21594. EXPECT_TRUE(connected.load());
  21595. EXPECT_TRUE(sse.is_connected());
  21596. // Signal handler to stop
  21597. stop_server_.store(true);
  21598. // Stop SSE client
  21599. sse.stop();
  21600. EXPECT_FALSE(sse.is_connected());
  21601. }
  21602. // Sends one event, then nothing until stop is set
  21603. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  21604. return [&stop](const Request &, Response &res) {
  21605. res.set_chunked_content_provider(
  21606. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  21607. if (offset == 0) {
  21608. std::string event = "data: hello\n\n";
  21609. sink.write(event.data(), event.size());
  21610. }
  21611. while (!stop.load()) {
  21612. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21613. }
  21614. return false;
  21615. });
  21616. };
  21617. }
  21618. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  21619. static void check_stop_interrupts_blocked_read(Client &client) {
  21620. client.set_read_timeout(30, 0);
  21621. for (auto by_destructor : {false, true}) {
  21622. std::atomic<bool> received{false};
  21623. std::chrono::steady_clock::time_point start;
  21624. {
  21625. sse::SSEClient sse(client, "/idle-stream");
  21626. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  21627. sse.start_async();
  21628. for (int i = 0; i < 500 && !received.load(); ++i) {
  21629. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21630. }
  21631. ASSERT_TRUE(received.load());
  21632. // Let the client block in the next read
  21633. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  21634. start = std::chrono::steady_clock::now();
  21635. if (!by_destructor) { sse.stop(); }
  21636. }
  21637. EXPECT_LT(std::chrono::steady_clock::now() - start,
  21638. std::chrono::seconds(2));
  21639. }
  21640. }
  21641. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  21642. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  21643. Client client("localhost", get_port());
  21644. check_stop_interrupts_blocked_read(client);
  21645. }
  21646. #ifdef CPPHTTPLIB_SSL_ENABLED
  21647. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  21648. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21649. std::atomic<bool> done{false};
  21650. svr.Get("/idle-stream", idle_event_stream(done));
  21651. auto port = svr.bind_to_any_port(HOST);
  21652. std::thread t([&] { svr.listen_after_bind(); });
  21653. auto se = detail::scope_exit([&] {
  21654. done.store(true);
  21655. svr.stop();
  21656. t.join();
  21657. });
  21658. svr.wait_until_ready();
  21659. Client client("https://localhost:" + std::to_string(port));
  21660. client.enable_server_certificate_verification(false);
  21661. check_stop_interrupts_blocked_read(client);
  21662. }
  21663. #endif
  21664. // Test: SSEClient with custom headers
  21665. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21666. // Setup a server endpoint that checks for custom header
  21667. std::atomic<bool> header_received{false};
  21668. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21669. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21670. header_received.store(true);
  21671. }
  21672. res.set_chunked_content_provider("text/event-stream",
  21673. [](size_t, DataSink &) { return false; });
  21674. });
  21675. Client client("localhost", get_port());
  21676. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21677. sse::SSEClient sse(client, "/header-check", headers);
  21678. sse.set_max_reconnect_attempts(1);
  21679. sse.start_async();
  21680. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21681. sse.stop();
  21682. EXPECT_TRUE(header_received.load());
  21683. }
  21684. // Test: Reconnect interval configuration
  21685. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21686. Client client("localhost", get_port());
  21687. sse::SSEClient sse(client, "/events");
  21688. auto &result = sse.set_reconnect_interval(500);
  21689. // Builder pattern should return reference to self
  21690. EXPECT_EQ(&result, &sse);
  21691. }
  21692. // Test: Max reconnect attempts
  21693. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21694. // Connect to non-existent port to force reconnects
  21695. Client client("localhost", 59998);
  21696. sse::SSEClient sse(client, "/events");
  21697. std::atomic<int> error_count{0};
  21698. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21699. sse.set_reconnect_interval(50);
  21700. sse.set_max_reconnect_attempts(2);
  21701. auto start = std::chrono::steady_clock::now();
  21702. sse.start(); // Blocking call
  21703. auto end = std::chrono::steady_clock::now();
  21704. // Should have stopped after 2 failed attempts
  21705. EXPECT_GE(error_count.load(), 2);
  21706. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21707. auto duration =
  21708. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21709. #ifdef _WIN32
  21710. // Windows is much slower for socket connection failures
  21711. EXPECT_LT(duration.count(), 7000);
  21712. #else
  21713. EXPECT_LT(duration.count(), 1000);
  21714. #endif
  21715. }
  21716. // Test: Multi-line data in integration
  21717. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21718. // Endpoint with multi-line data
  21719. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21720. res.set_chunked_content_provider(
  21721. "text/event-stream", [](size_t offset, DataSink &sink) {
  21722. if (offset == 0) {
  21723. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21724. sink.write(event.data(), event.size());
  21725. }
  21726. return false;
  21727. });
  21728. });
  21729. Client client("localhost", get_port());
  21730. sse::SSEClient sse(client, "/multiline-data");
  21731. std::string received_data;
  21732. std::mutex data_mutex;
  21733. sse.on_message([&](const sse::SSEMessage &msg) {
  21734. std::lock_guard<std::mutex> lock(data_mutex);
  21735. received_data = msg.data;
  21736. });
  21737. sse.set_reconnect_interval(100);
  21738. sse.set_max_reconnect_attempts(1);
  21739. sse.start_async();
  21740. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21741. sse.stop();
  21742. std::lock_guard<std::mutex> lock(data_mutex);
  21743. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21744. }
  21745. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21746. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21747. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21748. DataSink &sink) {
  21749. if (offset == 0) {
  21750. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21751. sink.write(events.data(), events.size());
  21752. }
  21753. return false;
  21754. });
  21755. });
  21756. Client client("localhost", get_port());
  21757. sse::SSEClient sse(client, "/empty-data-lines");
  21758. std::mutex mutex;
  21759. std::condition_variable cv;
  21760. std::vector<std::string> received;
  21761. sse.on_message([&](const sse::SSEMessage &msg) {
  21762. std::lock_guard<std::mutex> lock(mutex);
  21763. received.push_back(msg.data);
  21764. cv.notify_all();
  21765. });
  21766. sse.set_max_reconnect_attempts(1);
  21767. sse.start_async();
  21768. {
  21769. std::unique_lock<std::mutex> lock(mutex);
  21770. cv.wait_for(lock, std::chrono::seconds(2),
  21771. [&] { return received.size() >= 3; });
  21772. }
  21773. sse.stop();
  21774. ASSERT_GE(received.size(), 3u);
  21775. EXPECT_EQ(received[0], "");
  21776. EXPECT_EQ(received[1], "\nhello");
  21777. EXPECT_EQ(received[2], "");
  21778. }
  21779. // Test: Auto-reconnect after server disconnection
  21780. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21781. std::atomic<int> connection_count{0};
  21782. std::atomic<int> message_count{0};
  21783. // Endpoint that sends one event and closes, forcing reconnect
  21784. server_->Get("/reconnect-test",
  21785. [&connection_count](const Request &, Response &res) {
  21786. connection_count.fetch_add(1);
  21787. res.set_chunked_content_provider(
  21788. "text/event-stream", [](size_t offset, DataSink &sink) {
  21789. if (offset == 0) {
  21790. std::string event = "data: hello\n\n";
  21791. sink.write(event.data(), event.size());
  21792. }
  21793. return false; // Close connection after sending
  21794. });
  21795. });
  21796. Client client("localhost", get_port());
  21797. sse::SSEClient sse(client, "/reconnect-test");
  21798. sse.on_message([&message_count](const sse::SSEMessage &) {
  21799. message_count.fetch_add(1);
  21800. });
  21801. sse.set_reconnect_interval(100);
  21802. sse.set_max_reconnect_attempts(3);
  21803. sse.start_async();
  21804. // Wait long enough for multiple reconnects
  21805. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21806. sse.stop();
  21807. // Should have connected multiple times (initial + reconnects)
  21808. EXPECT_GE(connection_count.load(), 2);
  21809. // Should have received messages from multiple connections
  21810. EXPECT_GE(message_count.load(), 2);
  21811. }
  21812. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  21813. std::atomic<int> connection_count{0};
  21814. // Neither Content-Length nor chunked: the close ends the stream
  21815. server_->Get("/close-delimited",
  21816. [&connection_count](const Request &, Response &res) {
  21817. connection_count.fetch_add(1);
  21818. res.set_content_provider(
  21819. "text/event-stream", [](size_t offset, DataSink &sink) {
  21820. if (offset == 0) {
  21821. std::string event = "data: hello\n\n";
  21822. sink.write(event.data(), event.size());
  21823. } else {
  21824. sink.done();
  21825. }
  21826. return true;
  21827. });
  21828. });
  21829. Client client("localhost", get_port());
  21830. sse::SSEClient sse(client, "/close-delimited");
  21831. std::atomic<int> error_count{0};
  21832. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  21833. sse.set_reconnect_interval(100);
  21834. sse.start_async();
  21835. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  21836. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21837. }
  21838. sse.stop();
  21839. // Reconnects as after any end of the stream, but reports no error
  21840. EXPECT_GE(connection_count.load(), 2);
  21841. EXPECT_EQ(0, error_count.load());
  21842. }
  21843. // Test: A retry field that is not all ASCII digits is ignored
  21844. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21845. std::atomic<int> connection_count{0};
  21846. server_->Get("/bad-retry",
  21847. [&connection_count](const Request &, Response &res) {
  21848. connection_count.fetch_add(1);
  21849. res.set_chunked_content_provider(
  21850. "text/event-stream", [](size_t offset, DataSink &sink) {
  21851. if (offset == 0) {
  21852. std::string event = "retry: -1\ndata: hello\n\n";
  21853. sink.write(event.data(), event.size());
  21854. }
  21855. return false;
  21856. });
  21857. });
  21858. Client client("localhost", get_port());
  21859. sse::SSEClient sse(client, "/bad-retry");
  21860. sse.set_reconnect_interval(10000);
  21861. sse.start_async();
  21862. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21863. sse.stop();
  21864. EXPECT_EQ(connection_count.load(), 1);
  21865. }
  21866. // Test: A retry field of all ASCII digits sets the reconnection time
  21867. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21868. std::mutex mutex;
  21869. std::condition_variable cv;
  21870. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21871. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21872. {
  21873. std::lock_guard<std::mutex> lock(mutex);
  21874. connected_at.push_back(std::chrono::steady_clock::now());
  21875. cv.notify_all();
  21876. }
  21877. res.set_chunked_content_provider(
  21878. "text/event-stream", [](size_t offset, DataSink &sink) {
  21879. if (offset == 0) {
  21880. std::string event = "retry: 0\ndata: hello\n\n";
  21881. sink.write(event.data(), event.size());
  21882. }
  21883. return false;
  21884. });
  21885. });
  21886. Client client("localhost", get_port());
  21887. sse::SSEClient sse(client, "/zero-retry");
  21888. sse.set_reconnect_interval(10000);
  21889. sse.start_async();
  21890. {
  21891. std::unique_lock<std::mutex> lock(mutex);
  21892. cv.wait_for(lock, std::chrono::seconds(5),
  21893. [&] { return connected_at.size() >= 2; });
  21894. }
  21895. sse.stop();
  21896. // The server-supplied interval is applied, but never below 100ms, so
  21897. // "retry: 0" does not cause a busy reconnect loop
  21898. std::lock_guard<std::mutex> lock(mutex);
  21899. ASSERT_GE(connected_at.size(), 2u);
  21900. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21901. connected_at[1] - connected_at[0])
  21902. .count();
  21903. EXPECT_GE(interval_ms, 100);
  21904. }
  21905. // Test: Last-Event-ID sent on reconnect
  21906. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21907. std::atomic<int> connection_count{0};
  21908. std::vector<std::string> received_last_event_ids;
  21909. std::mutex id_mutex;
  21910. // Endpoint that checks Last-Event-ID header and sends event with ID
  21911. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21912. int conn = connection_count.fetch_add(1);
  21913. // Capture the Last-Event-ID header from each connection
  21914. {
  21915. std::lock_guard<std::mutex> lock(id_mutex);
  21916. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21917. }
  21918. res.set_chunked_content_provider(
  21919. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21920. if (offset == 0) {
  21921. std::string event =
  21922. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21923. sink.write(event.data(), event.size());
  21924. }
  21925. return false;
  21926. });
  21927. });
  21928. Client client("localhost", get_port());
  21929. sse::SSEClient sse(client, "/reconnect-with-id");
  21930. sse.set_reconnect_interval(100);
  21931. sse.set_max_reconnect_attempts(3);
  21932. sse.start_async();
  21933. // Wait for at least 2 connections
  21934. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21935. sse.stop();
  21936. // Verify behavior
  21937. std::lock_guard<std::mutex> lock(id_mutex);
  21938. EXPECT_GE(received_last_event_ids.size(), 2u);
  21939. // First connection should have no Last-Event-ID
  21940. if (!received_last_event_ids.empty()) {
  21941. EXPECT_EQ(received_last_event_ids[0], "");
  21942. }
  21943. // Second connection should have Last-Event-ID from first connection
  21944. if (received_last_event_ids.size() >= 2) {
  21945. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21946. }
  21947. }
  21948. // Test: set_headers updates headers used on reconnect
  21949. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21950. std::vector<std::string> received_tokens;
  21951. std::mutex token_mutex;
  21952. // Endpoint that captures Authorization header
  21953. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21954. {
  21955. std::lock_guard<std::mutex> lock(token_mutex);
  21956. received_tokens.push_back(req.get_header_value("Authorization"));
  21957. }
  21958. res.set_chunked_content_provider(
  21959. "text/event-stream", [](size_t offset, DataSink &sink) {
  21960. if (offset == 0) {
  21961. std::string event = "data: hello\n\n";
  21962. sink.write(event.data(), event.size());
  21963. }
  21964. return false; // Close connection to trigger reconnect
  21965. });
  21966. });
  21967. Client client("localhost", get_port());
  21968. Headers headers = {{"Authorization", "Bearer old-token"}};
  21969. sse::SSEClient sse(client, "/auth-check", headers);
  21970. // Update headers on each successful connection
  21971. sse.on_open(
  21972. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21973. sse.set_reconnect_interval(100);
  21974. sse.set_max_reconnect_attempts(3);
  21975. sse.start_async();
  21976. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21977. sse.stop();
  21978. std::lock_guard<std::mutex> lock(token_mutex);
  21979. ASSERT_GE(received_tokens.size(), 2u);
  21980. // First connection uses original header
  21981. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21982. // Second connection uses updated header from set_headers
  21983. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21984. }
  21985. // Test: 401 allows reconnection (so on_error can refresh headers)
  21986. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21987. std::atomic<int> connection_count{0};
  21988. // Endpoint: returns 401 on first attempt, 200 on second
  21989. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21990. int conn = connection_count.fetch_add(1);
  21991. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21992. res.status = StatusCode::Unauthorized_401;
  21993. res.set_content("Unauthorized", "text/plain");
  21994. return;
  21995. }
  21996. res.set_chunked_content_provider(
  21997. "text/event-stream", [](size_t offset, DataSink &sink) {
  21998. if (offset == 0) {
  21999. std::string event = "data: authenticated\n\n";
  22000. sink.write(event.data(), event.size());
  22001. }
  22002. return false;
  22003. });
  22004. });
  22005. Client client("localhost", get_port());
  22006. Headers headers = {{"Authorization", "Bearer expired"}};
  22007. sse::SSEClient sse(client, "/auth-retry", headers);
  22008. std::atomic<bool> message_received{false};
  22009. // Refresh token on error
  22010. sse.on_error(
  22011. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22012. sse.on_message([&](const sse::SSEMessage &msg) {
  22013. if (msg.data == "authenticated") { message_received.store(true); }
  22014. });
  22015. sse.set_reconnect_interval(100);
  22016. sse.set_max_reconnect_attempts(3);
  22017. sse.start_async();
  22018. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22019. sse.stop();
  22020. // Should have reconnected after 401 and succeeded with new token
  22021. EXPECT_GE(connection_count.load(), 2);
  22022. EXPECT_TRUE(message_received.load());
  22023. }
  22024. TEST(Issue2318Test, EmptyHostString) {
  22025. {
  22026. httplib::Client cli_empty("", PORT);
  22027. auto res = cli_empty.Get("/");
  22028. ASSERT_FALSE(res);
  22029. EXPECT_EQ(httplib::Error::Connection, res.error());
  22030. }
  22031. {
  22032. httplib::Client cli(" ", PORT);
  22033. auto res = cli.Get("/");
  22034. ASSERT_FALSE(res);
  22035. EXPECT_EQ(httplib::Error::Connection, res.error());
  22036. }
  22037. }
  22038. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22039. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22040. Server svr;
  22041. // Set a small payload limit (1KB)
  22042. svr.set_payload_max_length(1024);
  22043. svr.Post("/test", [&](const Request &req, Response &res) {
  22044. res.set_content("Body size: " + std::to_string(req.body.size()),
  22045. "text/plain");
  22046. });
  22047. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22048. auto se = detail::scope_exit([&] {
  22049. svr.stop();
  22050. listen_thread.join();
  22051. });
  22052. svr.wait_until_ready();
  22053. // Create data that compresses well but exceeds limit when decompressed
  22054. // 8KB of repeated null bytes compresses to a very small size
  22055. std::string original_data(8 * 1024, '\0');
  22056. // Compress the data using gzip
  22057. std::string compressed_data;
  22058. detail::gzip_compressor compressor;
  22059. compressor.compress(original_data.data(), original_data.size(), true,
  22060. [&](const char *data, size_t size) {
  22061. compressed_data.append(data, size);
  22062. return true;
  22063. });
  22064. // Verify compression worked (compressed should be much smaller)
  22065. ASSERT_LT(compressed_data.size(), original_data.size());
  22066. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22067. // Send compressed data with Content-Encoding: gzip
  22068. Client cli(HOST, PORT);
  22069. Headers headers = {{"Content-Encoding", "gzip"}};
  22070. auto res =
  22071. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22072. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22074. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22075. }
  22076. #endif
  22077. // ============================================================================
  22078. // OpenSSL-Specific Tests
  22079. // ============================================================================
  22080. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22081. X509 *readCertificate(const std::string &strFileName) {
  22082. std::ifstream inStream(strFileName);
  22083. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22084. std::istreambuf_iterator<char>());
  22085. if (strCertPEM.empty()) return (nullptr);
  22086. BIO *pbCert = BIO_new(BIO_s_mem());
  22087. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22088. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22089. BIO_free(pbCert);
  22090. return (pCert);
  22091. }
  22092. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22093. std::ifstream inStream(strFileName);
  22094. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22095. std::istreambuf_iterator<char>());
  22096. if (strPrivateKeyPEM.empty()) return (nullptr);
  22097. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22098. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22099. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22100. BIO_free(pbPrivKey);
  22101. return (pPrivateKey);
  22102. }
  22103. TEST(BindServerTest, UpdateCerts) {
  22104. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22105. int port = svr.bind_to_any_port("0.0.0.0");
  22106. ASSERT_TRUE(svr.is_valid());
  22107. ASSERT_TRUE(port > 0);
  22108. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22109. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22110. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22111. ASSERT_TRUE(cert != nullptr);
  22112. ASSERT_TRUE(ca_cert != nullptr);
  22113. ASSERT_TRUE(key != nullptr);
  22114. X509_STORE *cert_store = X509_STORE_new();
  22115. X509_STORE_add_cert(cert_store, ca_cert);
  22116. // svr.update_certs(cert, key, cert_store); // deprecated
  22117. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22118. CLIENT_CA_CERT_FILE);
  22119. ASSERT_TRUE(svr.is_valid());
  22120. svr.stop();
  22121. X509_STORE_free(cert_store);
  22122. X509_free(cert);
  22123. X509_free(ca_cert);
  22124. EVP_PKEY_free(key);
  22125. }
  22126. // Test that update_certs() updates client CA list correctly
  22127. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22128. // Start with file-based constructor
  22129. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22130. ASSERT_TRUE(svr.is_valid());
  22131. // Initially no client CA list should be set
  22132. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22133. ASSERT_TRUE(ssl_ctx != nullptr);
  22134. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22135. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22136. // Now update with client CA (PEM string)
  22137. std::string cert_pem, key_pem, ca_pem;
  22138. read_file(SERVER_CERT_FILE, cert_pem);
  22139. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22140. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22141. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22142. ASSERT_TRUE(svr.is_valid());
  22143. // Now client CA list should be set
  22144. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22145. ASSERT_TRUE(ca_list_after != nullptr);
  22146. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22147. }
  22148. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22149. // Test that the file-path SSLServer constructor properly sets the client CA
  22150. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22151. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22152. ASSERT_TRUE(svr.is_valid());
  22153. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22154. ASSERT_TRUE(ssl_ctx != nullptr);
  22155. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22156. ASSERT_TRUE(ca_list != nullptr);
  22157. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22158. }
  22159. #endif
  22160. // ============================================================================
  22161. // MbedTLS-Specific Tests
  22162. // ============================================================================
  22163. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22164. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22165. using namespace httplib::tls;
  22166. // Track if callback was invoked
  22167. bool callback_invoked = false;
  22168. // The callback receives void* ctx which is actually MbedTlsContext*
  22169. // We can access the mbedtls_ssl_config via the context
  22170. auto setup_callback = [&callback_invoked](void *ctx) {
  22171. callback_invoked = true;
  22172. // Cast to MbedTlsContext* to access the ssl config
  22173. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22174. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22175. // Use static variables to hold certificate data (simplified for test)
  22176. static mbedtls_x509_crt own_cert;
  22177. static mbedtls_pk_context own_key;
  22178. static mbedtls_x509_crt ca_chain;
  22179. static bool initialized = false;
  22180. if (!initialized) {
  22181. mbedtls_x509_crt_init(&own_cert);
  22182. mbedtls_pk_init(&own_key);
  22183. mbedtls_x509_crt_init(&ca_chain);
  22184. // Load server certificate
  22185. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22186. return false;
  22187. }
  22188. // Load server private key.
  22189. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22190. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22191. #if MBEDTLS_VERSION_MAJOR == 3
  22192. ,
  22193. mbedtls_ctr_drbg_random, nullptr
  22194. #endif
  22195. ) != 0) {
  22196. return false;
  22197. }
  22198. // Load CA chain for client verification
  22199. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22200. return false;
  22201. }
  22202. initialized = true;
  22203. }
  22204. // Configure the SSL config
  22205. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22206. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22207. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22208. // Set minimum TLS version using mbedTLS native API
  22209. #if MBEDTLS_VERSION_MAJOR >= 3
  22210. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22211. #else
  22212. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22213. MBEDTLS_SSL_MINOR_VERSION_3);
  22214. #endif
  22215. return true;
  22216. };
  22217. SSLServer svr(setup_callback);
  22218. ASSERT_TRUE(svr.is_valid());
  22219. ASSERT_TRUE(callback_invoked);
  22220. svr.Get("/test", [&](const Request &req, Response &res) {
  22221. res.set_content("test", "text/plain");
  22222. auto cert = req.peer_cert();
  22223. ASSERT_TRUE(static_cast<bool>(cert));
  22224. auto common_name = cert.subject_cn();
  22225. EXPECT_EQ("Common Name", common_name);
  22226. });
  22227. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22228. auto se = detail::scope_exit([&] {
  22229. svr.stop();
  22230. t.join();
  22231. ASSERT_FALSE(svr.is_running());
  22232. });
  22233. svr.wait_until_ready();
  22234. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22235. cli.enable_server_certificate_verification(false);
  22236. cli.set_connection_timeout(30);
  22237. auto res = cli.Get("/test");
  22238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22239. ASSERT_EQ(StatusCode::OK_200, res->status);
  22240. }
  22241. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22242. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22243. // keep-alive SSL session, which reads through that config in
  22244. // mbedtls_ssl_close_notify.
  22245. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22247. ASSERT_TRUE(svr.is_valid());
  22248. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22249. res.set_content("test", "text/plain");
  22250. });
  22251. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22252. auto se = detail::scope_exit([&] {
  22253. svr.stop();
  22254. t.join();
  22255. ASSERT_FALSE(svr.is_running());
  22256. });
  22257. svr.wait_until_ready();
  22258. {
  22259. SSLClient cli(HOST, PORT);
  22260. cli.enable_server_certificate_verification(false);
  22261. cli.set_keep_alive(true);
  22262. auto res = cli.Get("/test");
  22263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22264. ASSERT_EQ(StatusCode::OK_200, res->status);
  22265. // cli is destructed here with the keep-alive SSL session still open.
  22266. }
  22267. }
  22268. #endif
  22269. // WebSocket Tests
  22270. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22271. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22272. // defining the meaning of these bits has been negotiated.
  22273. auto make_frame = [](uint8_t first_byte) {
  22274. std::string frame;
  22275. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22276. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22277. frame += "Hello";
  22278. return frame;
  22279. };
  22280. // RSV1 set (0x40)
  22281. {
  22282. detail::BufferStream strm;
  22283. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22284. ws::Opcode opcode;
  22285. std::string payload;
  22286. bool fin;
  22287. EXPECT_EQ(
  22288. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22289. ws::impl::FrameRead::Fail);
  22290. }
  22291. // RSV2 set (0x20)
  22292. {
  22293. detail::BufferStream strm;
  22294. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22295. ws::Opcode opcode;
  22296. std::string payload;
  22297. bool fin;
  22298. EXPECT_EQ(
  22299. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22300. ws::impl::FrameRead::Fail);
  22301. }
  22302. // RSV3 set (0x10)
  22303. {
  22304. detail::BufferStream strm;
  22305. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22306. ws::Opcode opcode;
  22307. std::string payload;
  22308. bool fin;
  22309. EXPECT_EQ(
  22310. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22311. ws::impl::FrameRead::Fail);
  22312. }
  22313. // No RSV bits set - should succeed
  22314. {
  22315. detail::BufferStream strm;
  22316. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22317. ws::Opcode opcode;
  22318. std::string payload;
  22319. bool fin;
  22320. EXPECT_EQ(
  22321. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22322. ws::impl::FrameRead::Ok);
  22323. EXPECT_EQ(ws::Opcode::Text, opcode);
  22324. EXPECT_EQ("Hello", payload);
  22325. EXPECT_TRUE(fin);
  22326. }
  22327. }
  22328. TEST(WebSocketTest, ControlFrameValidation) {
  22329. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22330. // payload length <= 125.
  22331. // Ping with FIN=0 - must be rejected
  22332. {
  22333. detail::BufferStream strm;
  22334. std::string frame;
  22335. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22336. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22337. strm.write(frame.data(), frame.size());
  22338. ws::Opcode opcode;
  22339. std::string payload;
  22340. bool fin;
  22341. EXPECT_EQ(
  22342. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22343. ws::impl::FrameRead::Fail);
  22344. }
  22345. // Close with FIN=0 - must be rejected
  22346. {
  22347. detail::BufferStream strm;
  22348. std::string frame;
  22349. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22350. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22351. strm.write(frame.data(), frame.size());
  22352. ws::Opcode opcode;
  22353. std::string payload;
  22354. bool fin;
  22355. EXPECT_EQ(
  22356. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22357. ws::impl::FrameRead::Fail);
  22358. }
  22359. // Ping with payload_len=126 (extended length) - must be rejected
  22360. {
  22361. detail::BufferStream strm;
  22362. std::string frame;
  22363. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22364. frame += static_cast<char>(126); // payload_len=126 (>125)
  22365. frame += static_cast<char>(0x00); // extended length high byte
  22366. frame += static_cast<char>(126); // extended length low byte
  22367. frame += std::string(126, 'x');
  22368. strm.write(frame.data(), frame.size());
  22369. ws::Opcode opcode;
  22370. std::string payload;
  22371. bool fin;
  22372. EXPECT_EQ(
  22373. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22374. ws::impl::FrameRead::Fail);
  22375. }
  22376. // Ping with FIN=1 and payload_len=125 - should succeed
  22377. {
  22378. detail::BufferStream strm;
  22379. std::string frame;
  22380. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22381. frame += static_cast<char>(125); // payload_len=125
  22382. frame += std::string(125, 'x');
  22383. strm.write(frame.data(), frame.size());
  22384. ws::Opcode opcode;
  22385. std::string payload;
  22386. bool fin;
  22387. EXPECT_EQ(
  22388. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22389. ws::impl::FrameRead::Ok);
  22390. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22391. EXPECT_EQ(125u, payload.size());
  22392. EXPECT_TRUE(fin);
  22393. }
  22394. }
  22395. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22396. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22397. // length MUST be 0.
  22398. // MSB set - must be rejected
  22399. {
  22400. detail::BufferStream strm;
  22401. std::string frame;
  22402. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22403. frame += static_cast<char>(127); // 64-bit extended length
  22404. frame += static_cast<char>(0x80); // MSB set (invalid)
  22405. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22406. strm.write(frame.data(), frame.size());
  22407. ws::Opcode opcode;
  22408. std::string payload;
  22409. bool fin;
  22410. EXPECT_EQ(
  22411. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22412. ws::impl::FrameRead::Fail);
  22413. }
  22414. // MSB clear - should pass length parsing (will be rejected by max_len,
  22415. // but that's a different check; use a small length to verify)
  22416. {
  22417. detail::BufferStream strm;
  22418. std::string frame;
  22419. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22420. frame += static_cast<char>(127); // 64-bit extended length
  22421. frame += std::string(7, '\0'); // high bytes = 0
  22422. frame += static_cast<char>(0x03); // length = 3
  22423. frame += "abc";
  22424. strm.write(frame.data(), frame.size());
  22425. ws::Opcode opcode;
  22426. std::string payload;
  22427. bool fin;
  22428. EXPECT_EQ(
  22429. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22430. ws::impl::FrameRead::Ok);
  22431. EXPECT_EQ(ws::Opcode::Text, opcode);
  22432. EXPECT_EQ("abc", payload);
  22433. }
  22434. }
  22435. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22436. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22437. // Valid UTF-8
  22438. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22439. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22440. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22441. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22442. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22443. // Invalid UTF-8
  22444. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22445. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22446. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22447. EXPECT_FALSE(
  22448. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22449. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22450. }
  22451. TEST(WebSocketTest, ConnectAndDisconnect) {
  22452. Server svr;
  22453. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22454. std::string msg;
  22455. while (ws.read(msg)) {}
  22456. });
  22457. auto port = svr.bind_to_any_port(HOST);
  22458. std::thread t([&]() { svr.listen_after_bind(); });
  22459. svr.wait_until_ready();
  22460. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22461. auto res = client.connect();
  22462. ASSERT_TRUE(res);
  22463. EXPECT_EQ(Error::Success, res.error());
  22464. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22465. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22466. EXPECT_TRUE(client.is_open());
  22467. client.close();
  22468. EXPECT_FALSE(client.is_open());
  22469. svr.stop();
  22470. t.join();
  22471. }
  22472. TEST(WebSocketTest, ValidURL) {
  22473. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22474. EXPECT_TRUE(ws1.is_valid());
  22475. ws::WebSocketClient ws2("ws://example.com/path");
  22476. EXPECT_TRUE(ws2.is_valid());
  22477. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22478. EXPECT_TRUE(ws3.is_valid());
  22479. #ifdef CPPHTTPLIB_SSL_ENABLED
  22480. ws::WebSocketClient wss1("wss://example.com/path");
  22481. EXPECT_TRUE(wss1.is_valid());
  22482. ws::WebSocketClient wss2("wss://example.com:443/path");
  22483. EXPECT_TRUE(wss2.is_valid());
  22484. #endif
  22485. }
  22486. TEST(WebSocketTest, InvalidURL) {
  22487. // No scheme
  22488. ws::WebSocketClient ws1("localhost:8080/path");
  22489. EXPECT_FALSE(ws1.is_valid());
  22490. // No path
  22491. ws::WebSocketClient ws2("ws://localhost:8080");
  22492. EXPECT_FALSE(ws2.is_valid());
  22493. // Empty string
  22494. ws::WebSocketClient ws3("");
  22495. EXPECT_FALSE(ws3.is_valid());
  22496. // Missing host
  22497. ws::WebSocketClient ws4("ws://:8080/path");
  22498. EXPECT_FALSE(ws4.is_valid());
  22499. // Port number overflow — should not crash
  22500. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22501. EXPECT_FALSE(ws5.is_valid());
  22502. // Port out of range
  22503. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22504. EXPECT_FALSE(ws6.is_valid());
  22505. }
  22506. TEST(WebSocketTest, UnsupportedScheme) {
  22507. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22508. ws::WebSocketClient ws1("http://localhost:8080/path");
  22509. EXPECT_FALSE(ws1.is_valid());
  22510. ws::WebSocketClient ws2("https://localhost:8080/path");
  22511. EXPECT_FALSE(ws2.is_valid());
  22512. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22513. EXPECT_FALSE(ws3.is_valid());
  22514. #else
  22515. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22516. std::invalid_argument);
  22517. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22518. std::invalid_argument);
  22519. #endif
  22520. }
  22521. TEST(WebSocketTest, ConnectWhenInvalid) {
  22522. ws::WebSocketClient ws("not a valid url");
  22523. EXPECT_FALSE(ws.is_valid());
  22524. auto res = ws.connect();
  22525. EXPECT_FALSE(res);
  22526. EXPECT_EQ(Error::Connection, res.error());
  22527. EXPECT_EQ(-1, res.status());
  22528. }
  22529. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22530. // Grab a port that is free, then close it again so nothing listens there
  22531. Server svr;
  22532. auto port = svr.bind_to_any_port(HOST);
  22533. svr.stop();
  22534. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22535. auto res = client.connect();
  22536. ASSERT_FALSE(res);
  22537. EXPECT_EQ(Error::Connection, res.error());
  22538. EXPECT_EQ(-1, res.status());
  22539. }
  22540. TEST(WebSocketTest, DefaultPort) {
  22541. ws::WebSocketClient ws1("ws://example.com/path");
  22542. EXPECT_TRUE(ws1.is_valid());
  22543. // ws:// defaults to port 80 (verified by successful parse)
  22544. #ifdef CPPHTTPLIB_SSL_ENABLED
  22545. ws::WebSocketClient ws2("wss://example.com/path");
  22546. EXPECT_TRUE(ws2.is_valid());
  22547. // wss:// defaults to port 443 (verified by successful parse)
  22548. #endif
  22549. }
  22550. TEST(WebSocketTest, IPv6LiteralAddress) {
  22551. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22552. EXPECT_TRUE(ws1.is_valid());
  22553. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22554. EXPECT_TRUE(ws2.is_valid());
  22555. }
  22556. TEST(WebSocketTest, ComplexPath) {
  22557. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22558. EXPECT_TRUE(ws1.is_valid());
  22559. ws::WebSocketClient ws2("ws://localhost:8080/");
  22560. EXPECT_TRUE(ws2.is_valid());
  22561. }
  22562. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22563. Server svr;
  22564. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22565. std::string msg;
  22566. while (ws.read(msg)) {}
  22567. });
  22568. auto port = svr.bind_to_any_port(HOST);
  22569. std::thread t([&]() { svr.listen_after_bind(); });
  22570. svr.wait_until_ready();
  22571. auto another_host = "example.com";
  22572. auto wrong_ip = "192.0.2.1";
  22573. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22574. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22575. ASSERT_TRUE(client.connect());
  22576. EXPECT_TRUE(client.is_open());
  22577. client.close();
  22578. svr.stop();
  22579. t.join();
  22580. }
  22581. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22582. Server svr;
  22583. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22584. std::string msg;
  22585. while (ws.read(msg)) {}
  22586. });
  22587. auto port = svr.bind_to_any_port(HOST);
  22588. std::thread t([&]() { svr.listen_after_bind(); });
  22589. svr.wait_until_ready();
  22590. auto wrong_ip = "192.0.2.1";
  22591. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22592. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22593. client.set_connection_timeout(1);
  22594. client.set_read_timeout(1);
  22595. client.set_write_timeout(1);
  22596. EXPECT_FALSE(client.connect());
  22597. EXPECT_FALSE(client.is_open());
  22598. svr.stop();
  22599. t.join();
  22600. }
  22601. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22602. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22603. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22604. // (RFC 6761) is only a map key and the Host header value.
  22605. auto host = "target.invalid";
  22606. Server svr;
  22607. std::string received_host;
  22608. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22609. received_host = req.get_header_value("Host");
  22610. std::string msg;
  22611. while (ws.read(msg)) {}
  22612. });
  22613. auto port = svr.bind_to_any_port(HOST);
  22614. std::thread t([&]() { svr.listen_after_bind(); });
  22615. // ASSERT_* below returns from the test body, which would leave t joinable
  22616. // and make ~thread call std::terminate.
  22617. auto se = detail::scope_exit([&] {
  22618. svr.stop();
  22619. if (t.joinable()) { t.join(); }
  22620. });
  22621. svr.wait_until_ready();
  22622. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22623. std::to_string(port) + "/ws");
  22624. client.set_hostname_addr_map({{host, HOST}});
  22625. ASSERT_TRUE(client.connect());
  22626. EXPECT_TRUE(client.is_open());
  22627. client.close();
  22628. svr.stop();
  22629. t.join();
  22630. // The mapping only redirects the connection; the identity stays host_.
  22631. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22632. }
  22633. class WebSocketIntegrationTest : public ::testing::Test {
  22634. protected:
  22635. void SetUp() override {
  22636. server_ = httplib::detail::make_unique<Server>();
  22637. setup_server();
  22638. start_server();
  22639. }
  22640. void TearDown() override {
  22641. server_->stop();
  22642. if (server_thread_.joinable()) { server_thread_.join(); }
  22643. }
  22644. void setup_server() {
  22645. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22646. std::string msg;
  22647. ws::ReadResult ret;
  22648. while ((ret = ws.read(msg))) {
  22649. if (ret == ws::Binary) {
  22650. ws.send(msg.data(), msg.size());
  22651. } else {
  22652. ws.send(msg);
  22653. }
  22654. }
  22655. });
  22656. server_->WebSocket("/ws-echo-string",
  22657. [](const Request &, ws::WebSocket &ws) {
  22658. std::string msg;
  22659. while (ws.read(msg)) {
  22660. ws.send("echo: " + msg);
  22661. }
  22662. });
  22663. server_->WebSocket(
  22664. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22665. // Echo back request metadata
  22666. ws.send("path:" + req.path);
  22667. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22668. std::string msg;
  22669. while (ws.read(msg)) {}
  22670. });
  22671. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22672. std::string msg;
  22673. ws.read(msg); // wait for a message
  22674. ws.close();
  22675. });
  22676. server_->WebSocket("/ws-close-status",
  22677. [](const Request &, ws::WebSocket &ws) {
  22678. std::string msg;
  22679. ws.read(msg); // wait for a message
  22680. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22681. });
  22682. server_->WebSocket(
  22683. "/ws-subprotocol",
  22684. [](const Request &, ws::WebSocket &ws) {
  22685. std::string msg;
  22686. while (ws.read(msg)) {
  22687. ws.send(msg);
  22688. }
  22689. },
  22690. [](const std::vector<std::string> &protocols) -> std::string {
  22691. for (const auto &p : protocols) {
  22692. if (p == "graphql-ws") { return p; }
  22693. }
  22694. return "";
  22695. });
  22696. server_->WebSocket(
  22697. "/ws-subprotocol-unoffered",
  22698. [](const Request &, ws::WebSocket &ws) {
  22699. std::string msg;
  22700. while (ws.read(msg)) {
  22701. ws.send(msg);
  22702. }
  22703. },
  22704. [](const std::vector<std::string> &) -> std::string {
  22705. return "admin";
  22706. });
  22707. }
  22708. void start_server() {
  22709. port_ = server_->bind_to_any_port(HOST);
  22710. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22711. server_->wait_until_ready();
  22712. }
  22713. std::unique_ptr<Server> server_;
  22714. std::thread server_thread_;
  22715. int port_ = 0;
  22716. };
  22717. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22718. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22719. "/ws-echo");
  22720. ASSERT_TRUE(client.connect());
  22721. ASSERT_TRUE(client.is_open());
  22722. ASSERT_TRUE(client.send("Hello WebSocket"));
  22723. std::string msg;
  22724. EXPECT_EQ(ws::Text, client.read(msg));
  22725. EXPECT_EQ("Hello WebSocket", msg);
  22726. client.close();
  22727. }
  22728. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22729. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22730. "/ws-echo");
  22731. ASSERT_TRUE(client.connect());
  22732. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22733. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22734. std::string msg;
  22735. EXPECT_EQ(ws::Binary, client.read(msg));
  22736. EXPECT_EQ(binary_data, msg);
  22737. client.close();
  22738. }
  22739. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22740. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22741. "/ws-echo");
  22742. ASSERT_TRUE(client.connect());
  22743. for (int i = 0; i < 10; i++) {
  22744. auto text = "message " + std::to_string(i);
  22745. ASSERT_TRUE(client.send(text));
  22746. std::string msg;
  22747. ASSERT_TRUE(client.read(msg));
  22748. EXPECT_EQ(text, msg);
  22749. }
  22750. client.close();
  22751. }
  22752. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22753. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22754. "/ws-close");
  22755. ASSERT_TRUE(client.connect());
  22756. // Send a message to trigger the server to close
  22757. ASSERT_TRUE(client.send("trigger close"));
  22758. // The server will close, so read should return false
  22759. std::string msg;
  22760. EXPECT_FALSE(client.read(msg));
  22761. EXPECT_FALSE(client.is_open());
  22762. }
  22763. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22764. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22765. "/ws-echo");
  22766. ASSERT_TRUE(client.connect());
  22767. // 128KB message
  22768. std::string large_data(128 * 1024, 'X');
  22769. ASSERT_TRUE(client.send(large_data));
  22770. std::string msg;
  22771. ASSERT_TRUE(client.read(msg));
  22772. EXPECT_EQ(large_data, msg);
  22773. client.close();
  22774. }
  22775. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22776. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22777. "/ws-echo");
  22778. ASSERT_TRUE(client.connect());
  22779. const int num_threads = 4;
  22780. std::vector<std::thread> threads;
  22781. std::atomic<int> send_count{0};
  22782. for (int t = 0; t < num_threads; t++) {
  22783. threads.emplace_back([&client, &send_count, t]() {
  22784. for (int i = 0; i < 5; i++) {
  22785. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22786. if (client.send(text)) { send_count++; }
  22787. }
  22788. });
  22789. }
  22790. for (auto &th : threads) {
  22791. th.join();
  22792. }
  22793. int received = 0;
  22794. std::string msg;
  22795. while (received < send_count.load()) {
  22796. if (!client.read(msg)) { break; }
  22797. received++;
  22798. }
  22799. EXPECT_EQ(send_count.load(), received);
  22800. client.close();
  22801. }
  22802. TEST_F(WebSocketIntegrationTest, ReadString) {
  22803. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22804. "/ws-echo-string");
  22805. ASSERT_TRUE(client.connect());
  22806. ASSERT_TRUE(client.send("hello"));
  22807. std::string msg;
  22808. ASSERT_TRUE(client.read(msg));
  22809. EXPECT_EQ("echo: hello", msg);
  22810. ASSERT_TRUE(client.send("world"));
  22811. ASSERT_TRUE(client.read(msg));
  22812. EXPECT_EQ("echo: world", msg);
  22813. client.close();
  22814. }
  22815. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22816. Headers headers = {{"X-Test-Header", "test-value"}};
  22817. ws::WebSocketClient client(
  22818. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22819. ASSERT_TRUE(client.connect());
  22820. std::string msg;
  22821. ASSERT_TRUE(client.read(msg));
  22822. EXPECT_EQ("path:/ws-request-info", msg);
  22823. ASSERT_TRUE(client.read(msg));
  22824. EXPECT_EQ("header:test-value", msg);
  22825. client.close();
  22826. }
  22827. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22828. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22829. "/ws-echo");
  22830. client.set_read_timeout(1, 0); // 1 second
  22831. ASSERT_TRUE(client.connect());
  22832. // Don't send anything — server echo handler waits for a message, so read()
  22833. // should time out. The connection survives it: nothing was consumed.
  22834. std::string msg;
  22835. EXPECT_EQ(client.read(msg), ws::Timeout);
  22836. EXPECT_TRUE(client.is_open());
  22837. // And it is still usable afterwards.
  22838. EXPECT_TRUE(client.send("after timeout"));
  22839. EXPECT_EQ(client.read(msg), ws::Text);
  22840. EXPECT_EQ(msg, "after timeout");
  22841. }
  22842. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22843. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22844. "/ws-echo");
  22845. client.set_read_timeout(1, 0);
  22846. ASSERT_TRUE(client.connect());
  22847. ASSERT_TRUE(client.send("first"));
  22848. std::string msg;
  22849. ASSERT_EQ(client.read(msg), ws::Text);
  22850. ASSERT_EQ(msg, "first");
  22851. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22852. // not be used with a read timeout: it would reprocess the previous message.
  22853. EXPECT_EQ(client.read(msg), ws::Timeout);
  22854. EXPECT_EQ(msg, "first");
  22855. }
  22856. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22857. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22858. "/ws-echo");
  22859. ASSERT_TRUE(client.connect());
  22860. // Setting it once the connection is open reaches the live stream, not just
  22861. // the seed for the next connect().
  22862. client.set_read_timeout(1, 0);
  22863. std::string msg;
  22864. EXPECT_EQ(client.read(msg), ws::Timeout);
  22865. EXPECT_TRUE(client.is_open());
  22866. }
  22867. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22868. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22869. "/ws-echo");
  22870. client.set_read_timeout(5, 0);
  22871. ASSERT_TRUE(client.connect());
  22872. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22873. // The server should reject it and close the connection.
  22874. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22875. client.send(oversized);
  22876. // The server's read() should have failed due to payload limit,
  22877. // so our read() should return false (connection closed).
  22878. std::string msg;
  22879. EXPECT_FALSE(client.read(msg));
  22880. }
  22881. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22882. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22883. "/ws-echo");
  22884. client.set_read_timeout(10, 0);
  22885. ASSERT_TRUE(client.connect());
  22886. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22887. // This should succeed.
  22888. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22889. ASSERT_TRUE(client.send(at_limit));
  22890. std::string msg;
  22891. ASSERT_TRUE(client.read(msg));
  22892. EXPECT_EQ(at_limit.size(), msg.size());
  22893. client.close();
  22894. }
  22895. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22896. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22897. "/nonexistent");
  22898. auto res = client.connect();
  22899. EXPECT_FALSE(res);
  22900. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22901. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22902. EXPECT_FALSE(client.is_open());
  22903. }
  22904. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22905. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22906. "/ws-echo");
  22907. ASSERT_TRUE(client.connect());
  22908. ASSERT_TRUE(client.send(""));
  22909. std::string msg;
  22910. EXPECT_EQ(ws::Text, client.read(msg));
  22911. EXPECT_EQ("", msg);
  22912. client.close();
  22913. }
  22914. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22915. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22916. "/ws-echo");
  22917. // First connection
  22918. ASSERT_TRUE(client.connect());
  22919. ASSERT_TRUE(client.send("first"));
  22920. std::string msg;
  22921. ASSERT_TRUE(client.read(msg));
  22922. EXPECT_EQ("first", msg);
  22923. client.close();
  22924. EXPECT_FALSE(client.is_open());
  22925. // Reconnect using the same client object
  22926. ASSERT_TRUE(client.connect());
  22927. ASSERT_TRUE(client.is_open());
  22928. ASSERT_TRUE(client.send("second"));
  22929. ASSERT_TRUE(client.read(msg));
  22930. EXPECT_EQ("second", msg);
  22931. client.close();
  22932. }
  22933. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22934. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22935. "/ws-close-status");
  22936. ASSERT_TRUE(client.connect());
  22937. // Trigger the server to close with GoingAway status
  22938. ASSERT_TRUE(client.send("trigger"));
  22939. // read() should return false after receiving the close frame
  22940. std::string msg;
  22941. EXPECT_FALSE(client.read(msg));
  22942. EXPECT_FALSE(client.is_open());
  22943. }
  22944. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22945. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22946. "/ws-echo");
  22947. ASSERT_TRUE(client.connect());
  22948. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22949. EXPECT_FALSE(client.is_open());
  22950. }
  22951. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22952. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22953. ws::WebSocketClient client(
  22954. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22955. ASSERT_TRUE(client.connect());
  22956. // Server should have selected graphql-ws
  22957. EXPECT_EQ("graphql-ws", client.subprotocol());
  22958. client.close();
  22959. }
  22960. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22961. Headers headers;
  22962. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22963. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22964. ws::WebSocketClient client(
  22965. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22966. ASSERT_TRUE(client.connect());
  22967. // The offer on the second field line counts too, so graphql-ws is selected
  22968. EXPECT_EQ("graphql-ws", client.subprotocol());
  22969. client.close();
  22970. }
  22971. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22972. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22973. ws::WebSocketClient client(
  22974. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22975. ASSERT_TRUE(client.connect());
  22976. // Server should not have selected any subprotocol
  22977. EXPECT_TRUE(client.subprotocol().empty());
  22978. client.close();
  22979. }
  22980. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22981. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22982. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22983. "/ws-subprotocol-unoffered",
  22984. headers);
  22985. ASSERT_TRUE(client.connect());
  22986. EXPECT_TRUE(client.subprotocol().empty());
  22987. client.close();
  22988. }
  22989. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22990. // Connect without requesting any subprotocol
  22991. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22992. "/ws-subprotocol");
  22993. ASSERT_TRUE(client.connect());
  22994. EXPECT_TRUE(client.subprotocol().empty());
  22995. client.close();
  22996. }
  22997. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22998. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22999. "/ws-echo");
  23000. client.set_tcp_nodelay(true);
  23001. client.set_connection_timeout(3, 0);
  23002. bool socket_options_called = false;
  23003. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23004. ASSERT_TRUE(client.connect());
  23005. ASSERT_TRUE(client.is_open());
  23006. EXPECT_TRUE(socket_options_called);
  23007. ASSERT_TRUE(client.send("hello"));
  23008. std::string msg;
  23009. auto result = client.read(msg);
  23010. EXPECT_EQ(result, ws::ReadResult::Text);
  23011. EXPECT_EQ(msg, "hello");
  23012. client.close();
  23013. }
  23014. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23015. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23016. "/ws-echo");
  23017. client.set_connection_timeout(std::chrono::seconds(3));
  23018. client.set_write_timeout(std::chrono::seconds(3));
  23019. // A sub-second remainder exercises the seconds/microseconds split.
  23020. client.set_read_timeout(std::chrono::milliseconds(1500));
  23021. ASSERT_TRUE(client.connect());
  23022. auto start = std::chrono::steady_clock::now();
  23023. std::string msg;
  23024. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23025. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23026. std::chrono::steady_clock::now() - start)
  23027. .count();
  23028. // Above 1s so that dropping the microseconds half of the split fails here.
  23029. // Ignoring the setter altogether would not reach this line at all: a client
  23030. // waits forever by default.
  23031. EXPECT_GE(elapsed, 1400);
  23032. EXPECT_LT(elapsed, 30000);
  23033. }
  23034. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23035. Server svr;
  23036. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23037. if (!req.has_header("Authorization")) {
  23038. res.status = StatusCode::Unauthorized_401;
  23039. res.set_content("Unauthorized", "text/plain");
  23040. return Server::HandlerResponse::Handled;
  23041. }
  23042. return Server::HandlerResponse::Unhandled;
  23043. });
  23044. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23045. std::string msg;
  23046. while (ws.read(msg)) {
  23047. ws.send(msg);
  23048. }
  23049. });
  23050. auto port = svr.bind_to_any_port("localhost");
  23051. std::thread t([&]() { svr.listen_after_bind(); });
  23052. svr.wait_until_ready();
  23053. // Without Authorization header - should be rejected before upgrade
  23054. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23055. EXPECT_FALSE(client1.connect());
  23056. // The rejection is framed like any other HTTP response
  23057. {
  23058. Client cli("localhost", port);
  23059. Headers headers = {{"Upgrade", "websocket"},
  23060. {"Connection", "Upgrade"},
  23061. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23062. {"Sec-WebSocket-Version", "13"}};
  23063. auto res = cli.Get("/ws", headers);
  23064. ASSERT_TRUE(res);
  23065. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23066. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23067. EXPECT_EQ("Unauthorized", res->body);
  23068. }
  23069. // With Authorization header - should succeed
  23070. Headers headers = {{"Authorization", "Bearer token123"}};
  23071. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23072. headers);
  23073. ASSERT_TRUE(client2.connect());
  23074. ASSERT_TRUE(client2.send("hello"));
  23075. std::string msg;
  23076. ASSERT_TRUE(client2.read(msg));
  23077. EXPECT_EQ("hello", msg);
  23078. client2.close();
  23079. svr.stop();
  23080. t.join();
  23081. }
  23082. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23083. Server svr;
  23084. std::atomic<int> pre_routing_calls{0};
  23085. std::atomic<int> pre_request_calls{0};
  23086. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23087. pre_routing_calls++;
  23088. if (req.path == "/handled") {
  23089. res.set_content("handled", "text/plain");
  23090. return Server::HandlerResponse::Handled;
  23091. }
  23092. return Server::HandlerResponse::Unhandled;
  23093. });
  23094. svr.set_pre_request_handler([&](const Request &, Response &) {
  23095. pre_request_calls++;
  23096. return Server::HandlerResponse::Unhandled;
  23097. });
  23098. svr.Get("/http", [](const Request &, Response &res) {
  23099. res.set_content("http", "text/plain");
  23100. });
  23101. svr.WebSocket("/ws",
  23102. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23103. auto port = svr.bind_to_any_port("localhost");
  23104. std::thread t([&]() { svr.listen_after_bind(); });
  23105. auto se = detail::scope_exit([&] {
  23106. svr.stop();
  23107. t.join();
  23108. });
  23109. svr.wait_until_ready();
  23110. Headers upgrade = {{"Upgrade", "websocket"},
  23111. {"Connection", "Upgrade"},
  23112. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23113. {"Sec-WebSocket-Version", "13"}};
  23114. auto get = [&](const char *path) {
  23115. pre_routing_calls = 0;
  23116. return Client("localhost", port).Get(path, upgrade);
  23117. };
  23118. // No WebSocket route, but an HTTP one
  23119. auto res = get("/http");
  23120. ASSERT_TRUE(res);
  23121. EXPECT_EQ(StatusCode::OK_200, res->status);
  23122. EXPECT_EQ("http", res->body);
  23123. EXPECT_EQ(1, pre_routing_calls);
  23124. EXPECT_EQ(1, pre_request_calls);
  23125. // No route at all
  23126. res = get("/none");
  23127. ASSERT_TRUE(res);
  23128. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23129. EXPECT_EQ(1, pre_routing_calls);
  23130. // Answered by the pre-routing handler
  23131. res = get("/handled");
  23132. ASSERT_TRUE(res);
  23133. EXPECT_EQ(StatusCode::OK_200, res->status);
  23134. EXPECT_EQ("handled", res->body);
  23135. EXPECT_EQ(1, pre_routing_calls);
  23136. // A WebSocket route
  23137. pre_routing_calls = 0;
  23138. pre_request_calls = 0;
  23139. {
  23140. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23141. "/ws");
  23142. ASSERT_TRUE(client.connect());
  23143. std::string msg;
  23144. ASSERT_TRUE(client.read(msg));
  23145. EXPECT_EQ("ws", msg);
  23146. client.close();
  23147. }
  23148. EXPECT_EQ(1, pre_routing_calls);
  23149. EXPECT_EQ(1, pre_request_calls);
  23150. }
  23151. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23152. Server svr;
  23153. std::atomic<int> pre_request_calls{0};
  23154. std::atomic<bool> route_matched{false};
  23155. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23156. pre_request_calls++;
  23157. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23158. if (req.get_header_value("Authorization") != "Bearer token123") {
  23159. res.status = StatusCode::Unauthorized_401;
  23160. res.set_content("Unauthorized", "text/plain");
  23161. return Server::HandlerResponse::Handled;
  23162. }
  23163. return Server::HandlerResponse::Unhandled;
  23164. });
  23165. std::atomic<bool> handler_called{false};
  23166. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23167. handler_called = true;
  23168. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23169. });
  23170. auto port = svr.bind_to_any_port("localhost");
  23171. std::thread t([&]() { svr.listen_after_bind(); });
  23172. svr.wait_until_ready();
  23173. // Without Authorization header - should be rejected before upgrade
  23174. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23175. "/ws/1");
  23176. EXPECT_FALSE(client1.connect());
  23177. EXPECT_FALSE(handler_called);
  23178. EXPECT_EQ(1, pre_request_calls);
  23179. EXPECT_TRUE(route_matched);
  23180. // The rejection is an ordinary HTTP response, not a protocol switch
  23181. {
  23182. Client cli("localhost", port);
  23183. Headers headers = {{"Upgrade", "websocket"},
  23184. {"Connection", "Upgrade"},
  23185. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23186. {"Sec-WebSocket-Version", "13"}};
  23187. auto res = cli.Get("/ws/1", headers);
  23188. ASSERT_TRUE(res);
  23189. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23190. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23191. EXPECT_EQ("Unauthorized", res->body);
  23192. }
  23193. EXPECT_FALSE(handler_called);
  23194. // With Authorization header - should succeed
  23195. Headers headers = {{"Authorization", "Bearer token123"}};
  23196. ws::WebSocketClient client2(
  23197. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23198. ASSERT_TRUE(client2.connect());
  23199. std::string msg;
  23200. ASSERT_TRUE(client2.read(msg));
  23201. EXPECT_EQ("/ws/:id 2", msg);
  23202. EXPECT_TRUE(handler_called);
  23203. client2.close();
  23204. svr.stop();
  23205. t.join();
  23206. }
  23207. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23208. Server svr;
  23209. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23210. // A read timeout is how a handler gets control back. Without it, a handler
  23211. // parked in read() can never write on the connection it is reading.
  23212. ws.set_read_timeout(std::chrono::milliseconds(100));
  23213. std::string msg;
  23214. while (ws.is_open()) {
  23215. auto r = ws.read(msg);
  23216. if (r == httplib::ws::Timeout) {
  23217. ws.send("tick");
  23218. continue;
  23219. }
  23220. if (r == httplib::ws::Fail) { break; }
  23221. ws.send(msg);
  23222. }
  23223. });
  23224. auto port = svr.bind_to_any_port("localhost");
  23225. std::thread t([&]() { svr.listen_after_bind(); });
  23226. svr.wait_until_ready();
  23227. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23228. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23229. ASSERT_TRUE(client.connect());
  23230. // The client sends nothing, so anything it receives came out of the
  23231. // handler's timeout path.
  23232. std::string msg;
  23233. ASSERT_EQ(client.read(msg), ws::Text);
  23234. EXPECT_EQ("tick", msg);
  23235. client.close();
  23236. svr.stop();
  23237. t.join();
  23238. }
  23239. // Stream::read may return fewer bytes than asked for. This is that contract at
  23240. // its worst -- one byte per call -- which is what a frame header straddling a
  23241. // read buffer's boundary looks like to the frame parser.
  23242. class WsByteAtATimeStream : public Stream {
  23243. public:
  23244. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23245. bool is_readable() const override { return true; }
  23246. bool wait_readable() const override { return true; }
  23247. bool wait_writable() const override { return true; }
  23248. ssize_t read(char *ptr, size_t size) override {
  23249. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23250. *ptr = data_[pos_++];
  23251. return 1;
  23252. }
  23253. ssize_t write(const char *, size_t size) override {
  23254. return static_cast<ssize_t>(size);
  23255. }
  23256. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23257. ip = "127.0.0.1";
  23258. port = 0;
  23259. }
  23260. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23261. ip = "127.0.0.1";
  23262. port = 0;
  23263. }
  23264. socket_t socket() const override { return INVALID_SOCKET; }
  23265. time_t duration() const override { return 0; }
  23266. private:
  23267. std::string data_;
  23268. size_t pos_ = 0;
  23269. };
  23270. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23271. // The payload uses the 16-bit extended length, so the header, the length
  23272. // and the mask key are all multi-byte fields here. Each used to be read
  23273. // with a single read() call, which fails as soon as one is split. The
  23274. // payload is also a little over one read chunk, so it is read in two.
  23275. std::string body;
  23276. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23277. body += static_cast<char>(i % 251);
  23278. }
  23279. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23280. std::string frame;
  23281. frame += static_cast<char>(0x81); // FIN + Text
  23282. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23283. frame += static_cast<char>(body.size() >> 8);
  23284. frame += static_cast<char>(body.size() & 0xff);
  23285. for (size_t i = 0; i < 4; i++) {
  23286. frame += static_cast<char>(mask[i]);
  23287. }
  23288. for (size_t i = 0; i < body.size(); i++) {
  23289. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23290. }
  23291. WsByteAtATimeStream strm(frame);
  23292. ws::Opcode opcode;
  23293. std::string payload;
  23294. bool fin = false;
  23295. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23296. /*expect_masked=*/true, body.size()),
  23297. ws::impl::FrameRead::Ok);
  23298. EXPECT_TRUE(fin);
  23299. EXPECT_EQ(opcode, ws::Opcode::Text);
  23300. EXPECT_EQ(payload, body);
  23301. }
  23302. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23303. std::string body(2000, 'x');
  23304. std::string frame;
  23305. frame += static_cast<char>(0x82); // FIN + Binary
  23306. frame += static_cast<char>(126); // 16-bit length follows
  23307. frame += static_cast<char>(body.size() >> 8);
  23308. frame += static_cast<char>(body.size() & 0xff);
  23309. frame += body;
  23310. detail::BufferStream strm;
  23311. strm.write(frame.data(), frame.size());
  23312. ws::Opcode opcode;
  23313. std::string payload;
  23314. bool fin;
  23315. EXPECT_EQ(
  23316. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23317. ws::impl::FrameRead::Ok);
  23318. EXPECT_EQ(body, payload);
  23319. }
  23320. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23321. // The header announces the largest payload allowed, and only 3 bytes of it
  23322. // ever arrive.
  23323. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23324. std::string frame;
  23325. frame += static_cast<char>(0x82); // FIN + Binary
  23326. frame += static_cast<char>(127); // 64-bit length follows
  23327. for (int shift = 56; shift >= 0; shift -= 8) {
  23328. frame += static_cast<char>((len >> shift) & 0xff);
  23329. }
  23330. frame += "abc";
  23331. detail::BufferStream strm;
  23332. strm.write(frame.data(), frame.size());
  23333. ws::Opcode opcode;
  23334. std::string payload;
  23335. bool fin;
  23336. EXPECT_EQ(
  23337. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23338. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23339. ws::impl::FrameRead::Fail);
  23340. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23341. }
  23342. TEST(WebSocketTest, QueryStringInHandshake) {
  23343. Server svr;
  23344. std::mutex mtx;
  23345. std::string received_target;
  23346. std::string received_token;
  23347. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23348. {
  23349. std::lock_guard<std::mutex> lock(mtx);
  23350. received_target = req.target;
  23351. if (req.has_param("token")) {
  23352. received_token = req.get_param_value("token");
  23353. }
  23354. }
  23355. std::string msg;
  23356. while (ws.read(msg)) {
  23357. ws.send(msg);
  23358. }
  23359. });
  23360. auto port = svr.bind_to_any_port("localhost");
  23361. std::thread t([&]() { svr.listen_after_bind(); });
  23362. svr.wait_until_ready();
  23363. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23364. "/ws?token=ABC&session=123");
  23365. ASSERT_TRUE(client.connect());
  23366. // Round-trip ensures the handler has run and captured the request.
  23367. ASSERT_TRUE(client.send("hello"));
  23368. std::string msg;
  23369. ASSERT_TRUE(client.read(msg));
  23370. EXPECT_EQ("hello", msg);
  23371. client.close();
  23372. {
  23373. std::lock_guard<std::mutex> lock(mtx);
  23374. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23375. EXPECT_EQ("ABC", received_token);
  23376. }
  23377. svr.stop();
  23378. t.join();
  23379. }
  23380. // Run a handshake against a throwaway server and hand the request the server
  23381. // received back to the caller, so tests can assert on the headers the client
  23382. // actually put on the wire.
  23383. static void capture_websocket_handshake_request(
  23384. const Headers &client_headers,
  23385. std::function<void(const Request &, int port)> verify) {
  23386. Server svr;
  23387. std::mutex mtx;
  23388. Request received;
  23389. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23390. {
  23391. std::lock_guard<std::mutex> lock(mtx);
  23392. received = req;
  23393. }
  23394. std::string msg;
  23395. while (ws.read(msg)) {
  23396. ws.send(msg);
  23397. }
  23398. });
  23399. auto port = svr.bind_to_any_port("localhost");
  23400. std::thread t([&]() { svr.listen_after_bind(); });
  23401. auto se = detail::scope_exit([&] {
  23402. svr.stop();
  23403. t.join();
  23404. });
  23405. svr.wait_until_ready();
  23406. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23407. client_headers);
  23408. ASSERT_TRUE(client.connect());
  23409. ASSERT_TRUE(client.send("hello"));
  23410. std::string msg;
  23411. ASSERT_TRUE(client.read(msg));
  23412. client.close();
  23413. {
  23414. std::lock_guard<std::mutex> lock(mtx);
  23415. verify(received, port);
  23416. }
  23417. }
  23418. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23419. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23420. // Non-default port must be present in the Host header. Default ports
  23421. // (80/443) are omitted; that logic is covered by
  23422. // MakeHostAndPortStringTest.
  23423. EXPECT_EQ("localhost:" + std::to_string(port),
  23424. req.get_header_value("Host"));
  23425. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23426. req.get_header_value("User-Agent"));
  23427. EXPECT_FALSE(req.has_header("Accept"));
  23428. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23429. EXPECT_FALSE(req.has_header("Content-Length"));
  23430. });
  23431. }
  23432. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23433. capture_websocket_handshake_request(
  23434. {{"Host", "example.com"},
  23435. {"User-Agent", "custom-agent"},
  23436. {"X-Custom", "value"}},
  23437. [](const Request &req, int) {
  23438. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23439. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23440. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23441. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23442. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23443. });
  23444. }
  23445. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23446. capture_websocket_handshake_request(
  23447. {{"Upgrade", "bogus"},
  23448. {"Connection", "close"},
  23449. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23450. {"Sec-WebSocket-Version", "8"}},
  23451. [](const Request &req, int) {
  23452. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23453. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23454. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23455. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23456. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23457. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23458. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23459. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23460. req.get_header_value("Sec-WebSocket-Key"));
  23461. });
  23462. }
  23463. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23464. // A header the client refuses to send must abort the handshake before any
  23465. // part of it reaches the wire; a lone request line would otherwise sit in
  23466. // the peer's buffer as a truncated request.
  23467. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23468. ASSERT_NE(INVALID_SOCKET, srv);
  23469. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23470. sockaddr_in addr{};
  23471. addr.sin_family = AF_INET;
  23472. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23473. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23474. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23475. ASSERT_EQ(0, ::listen(srv, 1));
  23476. sockaddr_in bound{};
  23477. socklen_t bound_len = sizeof(bound);
  23478. ASSERT_EQ(
  23479. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23480. auto port = ntohs(bound.sin_port);
  23481. ssize_t received = -1;
  23482. std::thread t([&] {
  23483. // Bound every blocking call so a regression fails the test with a bad
  23484. // value instead of hanging the suite.
  23485. fd_set rfds;
  23486. FD_ZERO(&rfds);
  23487. FD_SET(srv, &rfds);
  23488. timeval tv{5, 0};
  23489. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23490. 0) {
  23491. return;
  23492. }
  23493. sockaddr_in cli_addr{};
  23494. socklen_t cli_len = sizeof(cli_addr);
  23495. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23496. if (cli == INVALID_SOCKET) { return; }
  23497. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23498. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23499. char buf[4096];
  23500. received = ::recv(cli, buf, sizeof(buf), 0);
  23501. });
  23502. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23503. // connect() has already shut the socket down by the time it returns false,
  23504. // so the peer sees EOF without waiting for the client to be destroyed.
  23505. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23506. {{"X-Bad", "a\r\nInjected: 1"}});
  23507. EXPECT_FALSE(client.connect());
  23508. t.join();
  23509. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23510. EXPECT_EQ(0, received);
  23511. }
  23512. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23513. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23514. // contains "upgrade" as a substring is a different token and must not
  23515. // start a WebSocket handshake.
  23516. auto make_request = [](const std::vector<std::string> &connection_values) {
  23517. Request req;
  23518. req.method = "GET";
  23519. req.headers.emplace("Upgrade", "websocket");
  23520. for (const auto &value : connection_values) {
  23521. req.headers.emplace("Connection", value);
  23522. }
  23523. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23524. req.headers.emplace("Sec-WebSocket-Version", "13");
  23525. return req;
  23526. };
  23527. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23528. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23529. EXPECT_TRUE(
  23530. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23531. EXPECT_TRUE(
  23532. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23533. EXPECT_TRUE(
  23534. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23535. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23536. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23537. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23538. EXPECT_FALSE(
  23539. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23540. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23541. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23542. }
  23543. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23544. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23545. // asks recipients to match each protocol-name case-insensitively, and RFC
  23546. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23547. // client naming websocket alongside another protocol, or on a second field
  23548. // line, is offering websocket; a value that merely contains "websocket" as a
  23549. // substring is a different protocol name and is not.
  23550. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23551. Request req;
  23552. req.method = "GET";
  23553. for (const auto &value : upgrade_values) {
  23554. req.headers.emplace("Upgrade", value);
  23555. }
  23556. req.headers.emplace("Connection", "Upgrade");
  23557. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23558. req.headers.emplace("Sec-WebSocket-Version", "13");
  23559. return req;
  23560. };
  23561. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23562. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23563. EXPECT_TRUE(
  23564. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23565. EXPECT_TRUE(
  23566. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23567. EXPECT_TRUE(
  23568. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23569. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23570. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23571. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23572. EXPECT_FALSE(
  23573. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23574. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23575. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23576. }
  23577. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23578. Server svr;
  23579. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23580. auto port = svr.bind_to_any_port("localhost");
  23581. std::thread t([&]() { svr.listen_after_bind(); });
  23582. auto se = detail::scope_exit([&] {
  23583. svr.stop();
  23584. t.join();
  23585. });
  23586. svr.wait_until_ready();
  23587. Headers headers = {{"Upgrade", "websocket"},
  23588. {"Connection", "notupgrade"},
  23589. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23590. {"Sec-WebSocket-Version", "13"}};
  23591. Client cli("localhost", port);
  23592. auto res = cli.Get("/ws", headers);
  23593. // The route exists only as a WebSocket route, so a request that fails the
  23594. // handshake check falls through to ordinary routing.
  23595. ASSERT_TRUE(res);
  23596. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23597. }
  23598. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  23599. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  23600. // Connection value is the only thing left for the client to reject.
  23601. Server svr;
  23602. svr.Get("/ws", [](const Request &req, Response &res) {
  23603. res.status = StatusCode::SwitchingProtocol_101;
  23604. res.set_header("Upgrade", "websocket");
  23605. res.set_header("Connection", "notupgrade");
  23606. res.set_header("Sec-WebSocket-Accept",
  23607. detail::websocket_accept_key(
  23608. req.get_header_value("Sec-WebSocket-Key")));
  23609. });
  23610. auto port = svr.bind_to_any_port("localhost");
  23611. std::thread t([&]() { svr.listen_after_bind(); });
  23612. auto se = detail::scope_exit([&] {
  23613. svr.stop();
  23614. t.join();
  23615. });
  23616. svr.wait_until_ready();
  23617. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23618. auto res = client.connect();
  23619. EXPECT_FALSE(res);
  23620. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23621. EXPECT_FALSE(client.is_open());
  23622. }
  23623. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  23624. Server svr;
  23625. svr.Get("/ws", [](const Request &req, Response &res) {
  23626. res.status = StatusCode::SwitchingProtocol_101;
  23627. res.set_header("Upgrade", "websocket");
  23628. res.set_header("Connection", "Upgrade");
  23629. res.set_header("Sec-WebSocket-Accept",
  23630. detail::websocket_accept_key(
  23631. req.get_header_value("Sec-WebSocket-Key")));
  23632. res.set_header("Sec-WebSocket-Protocol", "admin");
  23633. });
  23634. auto port = svr.bind_to_any_port("localhost");
  23635. std::thread t([&]() { svr.listen_after_bind(); });
  23636. auto se = detail::scope_exit([&] {
  23637. svr.stop();
  23638. t.join();
  23639. });
  23640. svr.wait_until_ready();
  23641. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23642. // Server selects a subprotocol the client never offered
  23643. {
  23644. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23645. ws::WebSocketClient client(url, headers);
  23646. auto res = client.connect();
  23647. EXPECT_FALSE(res);
  23648. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23649. EXPECT_FALSE(client.is_open());
  23650. EXPECT_TRUE(client.subprotocol().empty());
  23651. }
  23652. // Client offered none but the server named one anyway
  23653. {
  23654. ws::WebSocketClient client(url);
  23655. auto res = client.connect();
  23656. EXPECT_FALSE(res);
  23657. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23658. EXPECT_FALSE(client.is_open());
  23659. EXPECT_TRUE(client.subprotocol().empty());
  23660. }
  23661. }
  23662. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23663. // The socket path doubles as the URL host, so it must not contain '/'.
  23664. const char *shard = getenv("GTEST_SHARD_INDEX");
  23665. const std::string sock_path =
  23666. shard ? std::string("httplib-ws-") + shard + ".sock"
  23667. : std::string("httplib-ws.sock");
  23668. std::remove(sock_path.c_str());
  23669. Server svr;
  23670. std::mutex mtx;
  23671. std::string received_host;
  23672. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23673. {
  23674. std::lock_guard<std::mutex> lock(mtx);
  23675. received_host = req.get_header_value("Host");
  23676. }
  23677. std::string msg;
  23678. while (ws.read(msg)) {
  23679. ws.send(msg);
  23680. }
  23681. });
  23682. svr.set_address_family(AF_UNIX);
  23683. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  23684. auto se = detail::scope_exit([&] {
  23685. svr.stop();
  23686. t.join();
  23687. std::remove(sock_path.c_str());
  23688. });
  23689. svr.wait_until_ready();
  23690. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  23691. client.set_address_family(AF_UNIX);
  23692. ASSERT_TRUE(client.connect());
  23693. ASSERT_TRUE(client.send("hello"));
  23694. std::string msg;
  23695. ASSERT_TRUE(client.read(msg));
  23696. client.close();
  23697. {
  23698. std::lock_guard<std::mutex> lock(mtx);
  23699. // There is no host:port for a Unix socket, so the same "localhost"
  23700. // placeholder the HTTP client uses is expected.
  23701. EXPECT_EQ("localhost", received_host);
  23702. }
  23703. }
  23704. // Two threads must never parse WebSocket frames from the same stream.
  23705. // close() used to read the peer's Close reply with its own frame read, so it
  23706. // raced a reader thread that was in the middle of a payload: the payload loop
  23707. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  23708. // so bytes taken by close() were replaced with bytes from further along the
  23709. // stream. The message kept its length and silently changed content.
  23710. //
  23711. // The raw peer below sends a frame header plus part of the payload, waits for
  23712. // the handler to call close(), and only then sends the rest. Whichever thread
  23713. // would win the race for those bytes, the message must arrive intact, because
  23714. // close() must not touch the stream while read() owns it.
  23715. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23716. #ifndef _WIN32
  23717. signal(SIGPIPE, SIG_IGN);
  23718. #endif
  23719. const size_t payload_len = 120; // fits the 7-bit length field
  23720. const size_t prefix_len = 8;
  23721. const int attempts = 8;
  23722. std::string expected(payload_len, '\0');
  23723. for (size_t i = 0; i < payload_len; i++) {
  23724. expected[i] = static_cast<char>('a' + i % 26);
  23725. }
  23726. std::atomic<bool> peer_stalled{false};
  23727. std::atomic<bool> handler_done{false};
  23728. std::mutex received_mutex;
  23729. std::vector<std::string> received;
  23730. // Bound every wait, so a regression fails the test instead of hanging the
  23731. // suite.
  23732. auto wait_for = [](const std::atomic<bool> &flag) {
  23733. for (int i = 0; i < 500 && !flag; i++) {
  23734. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23735. }
  23736. };
  23737. Server svr;
  23738. svr.set_websocket_ping_interval(0);
  23739. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23740. std::thread reader([&]() {
  23741. std::string msg;
  23742. while (ws.read(msg)) {
  23743. std::lock_guard<std::mutex> guard(received_mutex);
  23744. received.push_back(msg);
  23745. }
  23746. });
  23747. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23748. // inside read_websocket_frame() when close() runs.
  23749. wait_for(peer_stalled);
  23750. ws.close();
  23751. reader.join();
  23752. handler_done = true;
  23753. });
  23754. auto port = svr.bind_to_any_port("127.0.0.1");
  23755. std::thread t([&]() { svr.listen_after_bind(); });
  23756. auto se = detail::scope_exit([&] {
  23757. svr.stop();
  23758. t.join();
  23759. });
  23760. svr.wait_until_ready();
  23761. auto send_bytes = [](socket_t s, const std::string &data) {
  23762. #ifdef _WIN32
  23763. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23764. #else
  23765. auto n = ::send(s, data.data(), data.size(), 0);
  23766. #endif
  23767. return n == static_cast<decltype(n)>(data.size());
  23768. };
  23769. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23770. // Every length used here fits the 7-bit length field.
  23771. auto masked_header = [](uint8_t first_byte, size_t len) {
  23772. std::string h;
  23773. h += static_cast<char>(first_byte);
  23774. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23775. h.append(4, '\0'); // mask key
  23776. return h;
  23777. };
  23778. for (int attempt = 0; attempt < attempts; attempt++) {
  23779. peer_stalled = false;
  23780. handler_done = false;
  23781. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23782. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23783. auto se_sock = detail::scope_exit([&] {
  23784. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23785. });
  23786. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23787. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23788. sockaddr_in addr{};
  23789. addr.sin_family = AF_INET;
  23790. addr.sin_port = htons(static_cast<uint16_t>(port));
  23791. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23792. ASSERT_EQ(
  23793. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23794. << "attempt " << attempt;
  23795. ASSERT_TRUE(send_bytes(sock,
  23796. "GET /ws HTTP/1.1\r\n"
  23797. "Host: 127.0.0.1\r\n"
  23798. "Upgrade: websocket\r\n"
  23799. "Connection: Upgrade\r\n"
  23800. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23801. "Sec-WebSocket-Version: 13\r\n"
  23802. "\r\n"))
  23803. << "attempt " << attempt;
  23804. std::string response;
  23805. while (response.find("\r\n\r\n") == std::string::npos) {
  23806. char buf[512];
  23807. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23808. if (n <= 0) { break; }
  23809. response.append(buf, static_cast<size_t>(n));
  23810. }
  23811. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23812. << "attempt " << attempt;
  23813. // Send the header of a Binary message but only the first prefix_len bytes
  23814. // of its payload, leaving the reader thread stalled inside the payload.
  23815. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23816. expected.substr(0, prefix_len)))
  23817. << "attempt " << attempt;
  23818. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23819. peer_stalled = true;
  23820. // Let close() send its Close frame and park in its own read before the
  23821. // rest of the payload arrives, so both threads are waiting for it.
  23822. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23823. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23824. close_frame += static_cast<char>(0x03); // status 1000
  23825. close_frame += static_cast<char>(0xE8);
  23826. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23827. << "attempt " << attempt;
  23828. // Closing the peer releases the reader thread even on the buggy path,
  23829. // where it waits for bytes another thread already consumed.
  23830. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23831. detail::close_socket(sock);
  23832. sock = INVALID_SOCKET;
  23833. wait_for(handler_done);
  23834. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23835. }
  23836. std::lock_guard<std::mutex> guard(received_mutex);
  23837. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23838. << "a message in flight when close() ran was dropped";
  23839. for (size_t i = 0; i < received.size(); i++) {
  23840. EXPECT_EQ(expected, received[i]) << "message " << i;
  23841. }
  23842. }
  23843. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23844. // returning the socket, or INVALID_SOCKET.
  23845. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23846. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23847. if (sock == INVALID_SOCKET) { return sock; }
  23848. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23849. sockaddr_in addr{};
  23850. addr.sin_family = AF_INET;
  23851. addr.sin_port = htons(static_cast<uint16_t>(port));
  23852. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23853. std::string req = "GET " + path +
  23854. " HTTP/1.1\r\n"
  23855. "Host: 127.0.0.1\r\n"
  23856. "Upgrade: websocket\r\n"
  23857. "Connection: Upgrade\r\n"
  23858. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23859. "Sec-WebSocket-Version: 13\r\n"
  23860. "\r\n";
  23861. std::string res;
  23862. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23863. detail::send_socket(sock, req.data(), req.size(), 0) ==
  23864. static_cast<ssize_t>(req.size())) {
  23865. char c;
  23866. while (res.find("\r\n\r\n") == std::string::npos &&
  23867. ::recv(sock, &c, 1, 0) == 1) {
  23868. res += c;
  23869. }
  23870. }
  23871. if (res.find(" 101 ") == std::string::npos) {
  23872. detail::close_socket(sock);
  23873. return INVALID_SOCKET;
  23874. }
  23875. return sock;
  23876. }
  23877. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23878. // The payload must fit the 7-bit length field.
  23879. static std::string masked_frame(uint8_t first_byte,
  23880. const std::string &payload) {
  23881. std::string f;
  23882. f += static_cast<char>(first_byte);
  23883. f += static_cast<char>(0x80 | payload.size());
  23884. f.append(4, '\0');
  23885. return f + payload;
  23886. }
  23887. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23888. std::atomic<bool> done{false};
  23889. std::string received;
  23890. Server svr;
  23891. svr.set_websocket_ping_interval(0);
  23892. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23893. std::string msg;
  23894. if (ws.read(msg) == ws::Binary) { received = msg; }
  23895. done = true;
  23896. });
  23897. auto port = svr.bind_to_any_port("127.0.0.1");
  23898. std::thread t([&]() { svr.listen_after_bind(); });
  23899. auto se = detail::scope_exit([&] {
  23900. svr.stop();
  23901. t.join();
  23902. });
  23903. svr.wait_until_ready();
  23904. auto sock = connect_raw_websocket(port, "/ws");
  23905. ASSERT_NE(INVALID_SOCKET, sock);
  23906. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23907. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23908. masked_frame(0x89, "p") + // FIN + Ping
  23909. masked_frame(0x80, "lo"); // FIN + Continuation
  23910. detail::send_socket(sock, frames.data(), frames.size(), 0);
  23911. for (int i = 0; i < 500 && !done; i++) {
  23912. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23913. }
  23914. ASSERT_TRUE(done);
  23915. EXPECT_EQ("Hello", received);
  23916. // The Ping between the fragments is answered with a Pong.
  23917. char pong[3];
  23918. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23919. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23920. }
  23921. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23922. Server svr;
  23923. svr.set_websocket_ping_interval(-1);
  23924. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23925. std::string msg;
  23926. while (ws.read(msg)) {}
  23927. });
  23928. auto port = svr.bind_to_any_port("127.0.0.1");
  23929. std::thread t([&]() { svr.listen_after_bind(); });
  23930. auto se = detail::scope_exit([&] {
  23931. svr.stop();
  23932. t.join();
  23933. });
  23934. svr.wait_until_ready();
  23935. auto sock = connect_raw_websocket(port, "/ws");
  23936. ASSERT_NE(INVALID_SOCKET, sock);
  23937. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23938. // Nothing comes while the client stays quiet.
  23939. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23940. char c;
  23941. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23942. }
  23943. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  23944. // and that has to end a read() already waiting on the peer, on every platform.
  23945. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  23946. // The peer sends no pings, and its handler never calls read(), which is
  23947. // where pongs are written.
  23948. std::mutex mutex;
  23949. std::condition_variable cv;
  23950. auto release = false;
  23951. svr.set_websocket_ping_interval(0);
  23952. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  23953. std::unique_lock<std::mutex> lock(mutex);
  23954. cv.wait(lock, [&] { return release; });
  23955. });
  23956. auto port = svr.bind_to_any_port(HOST);
  23957. std::thread t([&]() { svr.listen_after_bind(); });
  23958. auto se = detail::scope_exit([&] {
  23959. {
  23960. std::lock_guard<std::mutex> lock(mutex);
  23961. release = true;
  23962. }
  23963. cv.notify_all();
  23964. svr.stop();
  23965. t.join();
  23966. });
  23967. svr.wait_until_ready();
  23968. ws::WebSocketClient client(std::string(scheme) +
  23969. "://localhost:" + std::to_string(port) + "/ws");
  23970. #ifdef CPPHTTPLIB_SSL_ENABLED
  23971. client.enable_server_certificate_verification(false);
  23972. #endif
  23973. // A ping a second, given up on after two go unanswered: about 3s
  23974. client.set_websocket_ping_interval(1);
  23975. client.set_websocket_max_missed_pongs(2);
  23976. // Well past that, so that a read the timeout ends instead stands out
  23977. client.set_read_timeout(10);
  23978. ASSERT_TRUE(client.connect());
  23979. auto start = std::chrono::steady_clock::now();
  23980. std::string msg;
  23981. EXPECT_EQ(ws::Fail, client.read(msg));
  23982. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  23983. std::chrono::steady_clock::now() - start)
  23984. .count(),
  23985. 6000);
  23986. EXPECT_FALSE(client.is_open());
  23987. }
  23988. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  23989. Server svr;
  23990. check_pong_timeout_ends_read(svr, "ws");
  23991. }
  23992. #ifdef CPPHTTPLIB_SSL_ENABLED
  23993. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  23994. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23995. ASSERT_TRUE(svr.is_valid());
  23996. check_pong_timeout_ends_read(svr, "wss");
  23997. }
  23998. #endif
  23999. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24000. Server svr;
  24001. svr.set_websocket_ping_interval(0);
  24002. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24003. std::string msg;
  24004. while (ws.read(msg)) {}
  24005. });
  24006. auto port = svr.bind_to_any_port("127.0.0.1");
  24007. std::thread t([&]() { svr.listen_after_bind(); });
  24008. auto se = detail::scope_exit([&] {
  24009. svr.stop();
  24010. t.join();
  24011. });
  24012. svr.wait_until_ready();
  24013. // Each Close payload and the reply it should get: an echo when valid, 1002
  24014. // otherwise.
  24015. std::vector<std::pair<std::string, std::string>> cases = {
  24016. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24017. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24018. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24019. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24020. };
  24021. // Also between the fragments of a message.
  24022. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24023. for (const auto &c : cases) {
  24024. auto sock = connect_raw_websocket(port, "/ws");
  24025. ASSERT_NE(INVALID_SOCKET, sock);
  24026. auto frames = prefix + masked_frame(0x88, c.first);
  24027. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24028. std::string reply;
  24029. char buf[256];
  24030. while (reply.size() < 2 + c.second.size()) {
  24031. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24032. if (n <= 0) { break; }
  24033. reply.append(buf, static_cast<size_t>(n));
  24034. }
  24035. detail::close_socket(sock);
  24036. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24037. c.second,
  24038. reply);
  24039. }
  24040. }
  24041. }
  24042. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24043. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24044. protected:
  24045. void SetUp() override {
  24046. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24047. SERVER_PRIVATE_KEY_FILE);
  24048. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24049. std::string msg;
  24050. ws::ReadResult ret;
  24051. while ((ret = ws.read(msg))) {
  24052. if (ret == ws::Binary) {
  24053. ws.send(msg.data(), msg.size());
  24054. } else {
  24055. ws.send(msg);
  24056. }
  24057. }
  24058. });
  24059. port_ = server_->bind_to_any_port(HOST);
  24060. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24061. server_->wait_until_ready();
  24062. }
  24063. void TearDown() override {
  24064. server_->stop();
  24065. if (server_thread_.joinable()) { server_thread_.join(); }
  24066. }
  24067. std::unique_ptr<SSLServer> server_;
  24068. std::thread server_thread_;
  24069. int port_ = 0;
  24070. };
  24071. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24072. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24073. {
  24074. ws::WebSocketClient client(url);
  24075. client.enable_server_certificate_verification(false);
  24076. auto calls = 0;
  24077. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24078. calls++;
  24079. return false;
  24080. });
  24081. EXPECT_FALSE(client.connect());
  24082. EXPECT_GT(calls, 0);
  24083. }
  24084. {
  24085. ws::WebSocketClient client(url);
  24086. client.enable_server_certificate_verification(false);
  24087. client.set_session_verifier([](tls::session_t) {
  24088. return SSLVerifierResponse::CertificateRejected;
  24089. });
  24090. EXPECT_FALSE(client.connect());
  24091. }
  24092. {
  24093. ws::WebSocketClient client(url);
  24094. client.enable_server_certificate_verification(false);
  24095. client.set_session_verifier([](tls::session_t) {
  24096. return SSLVerifierResponse::CertificateAccepted;
  24097. });
  24098. EXPECT_TRUE(client.connect());
  24099. }
  24100. }
  24101. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24102. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24103. "/ws-echo");
  24104. client.enable_server_certificate_verification(false);
  24105. ASSERT_TRUE(client.connect());
  24106. ASSERT_TRUE(client.is_open());
  24107. ASSERT_TRUE(client.send("Hello WSS"));
  24108. std::string msg;
  24109. EXPECT_EQ(ws::Text, client.read(msg));
  24110. EXPECT_EQ("Hello WSS", msg);
  24111. client.close();
  24112. }
  24113. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24114. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24115. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24116. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24117. // client (without calling close() first) is the only path that runs
  24118. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24119. // bug exactly.
  24120. //
  24121. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24122. // when linked against an instrumented libssl; run under Valgrind to catch it
  24123. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24124. // suite (the freed session otherwise stalls on the close handshake) — this test
  24125. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24126. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24127. {
  24128. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24129. "/ws-echo");
  24130. client.enable_server_certificate_verification(false);
  24131. client.set_read_timeout(2, 0);
  24132. client.set_write_timeout(2, 0);
  24133. ASSERT_TRUE(client.connect());
  24134. ASSERT_TRUE(client.is_open());
  24135. ASSERT_TRUE(client.send("still open"));
  24136. // Intentionally do NOT call client.close(): leaving scope runs
  24137. // shutdown_and_close() with the WebSocket still open, which must send the
  24138. // close frame while the TLS session is still alive.
  24139. }
  24140. }
  24141. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24142. // shutdown_and_close() at the start of connect(), reproducing the same
  24143. // use-after-free within the test body rather than at scope exit. The second
  24144. // connect must succeed and echo, proving the close handshake ran over a live
  24145. // session. See the note above about memory-tool requirements.
  24146. TEST_F(WebSocketSSLIntegrationTest,
  24147. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24148. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24149. "/ws-echo");
  24150. client.enable_server_certificate_verification(false);
  24151. client.set_read_timeout(2, 0);
  24152. client.set_write_timeout(2, 0);
  24153. ASSERT_TRUE(client.connect());
  24154. ASSERT_TRUE(client.is_open());
  24155. ASSERT_TRUE(client.send("still open"));
  24156. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24157. // the still-open connection, which must not touch a freed TLS session.
  24158. ASSERT_TRUE(client.connect());
  24159. ASSERT_TRUE(client.is_open());
  24160. ASSERT_TRUE(client.send("after reconnect"));
  24161. std::string msg;
  24162. EXPECT_EQ(ws::Text, client.read(msg));
  24163. EXPECT_EQ("after reconnect", msg);
  24164. client.close();
  24165. }
  24166. #endif
  24167. #ifdef CPPHTTPLIB_SSL_ENABLED
  24168. class WebSocketSSLCATest : public ::testing::Test {
  24169. protected:
  24170. void SetUp() override {
  24171. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24172. SERVER_PRIVATE_KEY_FILE);
  24173. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24174. std::string msg;
  24175. while (ws.read(msg)) {
  24176. ws.send(msg);
  24177. }
  24178. });
  24179. port_ = server_->bind_to_any_port("127.0.0.1");
  24180. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24181. server_->wait_until_ready();
  24182. }
  24183. void TearDown() override {
  24184. server_->stop();
  24185. if (server_thread_.joinable()) { server_thread_.join(); }
  24186. }
  24187. std::string url() const {
  24188. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24189. }
  24190. std::unique_ptr<SSLServer> server_;
  24191. std::thread server_thread_;
  24192. int port_ = 0;
  24193. };
  24194. // A custom CA loaded as PEM verifies the server with full certificate
  24195. // verification enabled
  24196. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24197. ws::WebSocketClient client(url());
  24198. std::string cert;
  24199. read_file(SERVER_CERT2_FILE, cert);
  24200. client.load_ca_cert_store(cert.c_str(), cert.size());
  24201. ASSERT_TRUE(client.connect());
  24202. ASSERT_TRUE(client.send("hello"));
  24203. std::string msg;
  24204. EXPECT_EQ(ws::Text, client.read(msg));
  24205. EXPECT_EQ("hello", msg);
  24206. client.close();
  24207. }
  24208. // A custom CA that does not cover the server must fail verification (the
  24209. // custom CA is exclusive; system certs are not loaded alongside it)
  24210. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24211. ws::WebSocketClient client(url());
  24212. std::string cert;
  24213. read_file(CLIENT_CA_CERT_FILE, cert);
  24214. client.load_ca_cert_store(cert.c_str(), cert.size());
  24215. auto res = client.connect();
  24216. ASSERT_FALSE(res);
  24217. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24218. EXPECT_EQ(-1, res.status());
  24219. EXPECT_NE(0u, res.ssl_backend_error());
  24220. }
  24221. // The same CA as a file path rather than PEM in memory
  24222. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24223. ws::WebSocketClient client(url());
  24224. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24225. ASSERT_TRUE(client.connect());
  24226. ASSERT_TRUE(client.send("hello"));
  24227. std::string msg;
  24228. EXPECT_EQ(ws::Text, client.read(msg));
  24229. EXPECT_EQ("hello", msg);
  24230. client.close();
  24231. }
  24232. // ...and a CA file that does not cover the server still fails, so it is the
  24233. // path above that decides the outcome
  24234. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24235. ws::WebSocketClient client(url());
  24236. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24237. ASSERT_FALSE(client.connect());
  24238. }
  24239. // Regression test: reconnecting with a native custom CA store used to reuse
  24240. // a store handle the previous TLS context had already freed (use-after-free
  24241. // under the OpenSSL backend). The context now lives as long as the client.
  24242. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24243. ws::WebSocketClient client(url());
  24244. std::string cert;
  24245. read_file(SERVER_CERT2_FILE, cert);
  24246. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24247. ASSERT_TRUE(client.connect());
  24248. client.close();
  24249. ASSERT_TRUE(client.connect());
  24250. ASSERT_TRUE(client.send("again"));
  24251. std::string msg;
  24252. EXPECT_EQ(ws::Text, client.read(msg));
  24253. EXPECT_EQ("again", msg);
  24254. client.close();
  24255. }
  24256. // Regression test: a certificate with a trusted chain but no identity match
  24257. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24258. // verification entirely for IP hosts, so this connection succeeded there.
  24259. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24260. // chain verification while the identity check must still fail.
  24261. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24262. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24263. ASSERT_TRUE(svr.is_valid());
  24264. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24265. std::string msg;
  24266. while (ws.read(msg)) {
  24267. ws.send(msg);
  24268. }
  24269. });
  24270. auto port = svr.bind_to_any_port("127.0.0.1");
  24271. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24272. auto se = detail::scope_exit([&] {
  24273. svr.stop();
  24274. t.join();
  24275. });
  24276. svr.wait_until_ready();
  24277. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24278. "/echo");
  24279. std::string cert;
  24280. read_file(SERVER_CERT_FILE, cert);
  24281. client.load_ca_cert_store(cert.c_str(), cert.size());
  24282. ASSERT_FALSE(client.connect());
  24283. }
  24284. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24285. // SNI, so nothing binds the host name to the TLS session. These bind the
  24286. // server to "localhost" instead, the only shape that exercises the SNI and
  24287. // hostname-verification path with certificate verification left enabled.
  24288. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24289. protected:
  24290. void Start(const char *cert_file) {
  24291. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24292. SERVER_PRIVATE_KEY_FILE);
  24293. ASSERT_TRUE(server_->is_valid());
  24294. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24295. std::string msg;
  24296. while (ws.read(msg)) {
  24297. ws.send(msg);
  24298. }
  24299. });
  24300. port_ = server_->bind_to_any_port("localhost");
  24301. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24302. server_->wait_until_ready();
  24303. }
  24304. void TearDown() override {
  24305. if (server_) { server_->stop(); }
  24306. if (server_thread_.joinable()) { server_thread_.join(); }
  24307. }
  24308. std::string url() const {
  24309. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24310. }
  24311. std::unique_ptr<SSLServer> server_;
  24312. std::thread server_thread_;
  24313. int port_ = 0;
  24314. };
  24315. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24316. // out and the connection is usable
  24317. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24318. Start(SERVER_CERT2_FILE);
  24319. ws::WebSocketClient client(url());
  24320. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24321. ASSERT_TRUE(client.connect());
  24322. ASSERT_TRUE(client.send("hello"));
  24323. std::string msg;
  24324. EXPECT_EQ(ws::Text, client.read(msg));
  24325. EXPECT_EQ("hello", msg);
  24326. client.close();
  24327. }
  24328. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24329. // while the identity check must still reject "localhost"
  24330. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24331. Start(SERVER_CERT_FILE);
  24332. ws::WebSocketClient client(url());
  24333. client.set_ca_cert_path(SERVER_CERT_FILE);
  24334. auto res = client.connect();
  24335. ASSERT_FALSE(res);
  24336. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24337. EXPECT_EQ(-1, res.status());
  24338. }
  24339. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24340. // disabled: the chain is still checked, only the identity check is skipped
  24341. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24342. Start(SERVER_CERT_FILE);
  24343. ws::WebSocketClient client(url());
  24344. client.set_ca_cert_path(SERVER_CERT_FILE);
  24345. client.enable_server_hostname_verification(false);
  24346. ASSERT_TRUE(client.connect());
  24347. ASSERT_TRUE(client.send("hello"));
  24348. std::string msg;
  24349. EXPECT_EQ(ws::Text, client.read(msg));
  24350. EXPECT_EQ("hello", msg);
  24351. client.close();
  24352. }
  24353. // A CA that did not sign the server certificate fails the chain, even though
  24354. // the name would match
  24355. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24356. Start(SERVER_CERT2_FILE);
  24357. ws::WebSocketClient client(url());
  24358. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24359. ASSERT_FALSE(client.connect());
  24360. }
  24361. // With verification disabled, neither the chain nor the name is checked
  24362. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24363. Start(SERVER_CERT_FILE);
  24364. ws::WebSocketClient client(url());
  24365. client.enable_server_certificate_verification(false);
  24366. ASSERT_TRUE(client.connect());
  24367. ASSERT_TRUE(client.send("hello"));
  24368. std::string msg;
  24369. EXPECT_EQ(ws::Text, client.read(msg));
  24370. EXPECT_EQ("hello", msg);
  24371. client.close();
  24372. }
  24373. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24374. protected:
  24375. void SetUp() override {
  24376. server_ = httplib::detail::make_unique<SSLServer>(
  24377. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24378. ASSERT_TRUE(server_->is_valid());
  24379. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24380. std::string msg;
  24381. while (ws.read(msg)) {
  24382. ws.send(msg);
  24383. }
  24384. });
  24385. port_ = server_->bind_to_any_port("localhost");
  24386. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24387. server_->wait_until_ready();
  24388. }
  24389. void TearDown() override {
  24390. server_->stop();
  24391. if (server_thread_.joinable()) { server_thread_.join(); }
  24392. }
  24393. std::string url() const {
  24394. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24395. }
  24396. void ConnectWithClientCert(const std::string &client_cert_file,
  24397. const std::string &client_private_key_file,
  24398. const char *private_key_password) {
  24399. std::string cert_pem, key_pem;
  24400. read_file(client_cert_file, cert_pem);
  24401. read_file(client_private_key_file, key_pem);
  24402. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24403. key_pem.c_str(), key_pem.size(),
  24404. private_key_password};
  24405. ConnectWithPem(pem);
  24406. }
  24407. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24408. ws::WebSocketClient client(url(), pem);
  24409. ASSERT_TRUE(client.is_valid());
  24410. client.enable_server_certificate_verification(false);
  24411. ASSERT_TRUE(client.connect());
  24412. ASSERT_TRUE(client.send("hello"));
  24413. std::string msg;
  24414. EXPECT_EQ(ws::Text, client.read(msg));
  24415. EXPECT_EQ("hello", msg);
  24416. client.close();
  24417. }
  24418. std::unique_ptr<SSLServer> server_;
  24419. std::thread server_thread_;
  24420. int port_ = 0;
  24421. };
  24422. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24423. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24424. }
  24425. // Control for the tests above: the fixture's server really does require a
  24426. // client certificate, so it is the PEM the constructor installed that decides
  24427. // the outcome.
  24428. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24429. ws::WebSocketClient client(url());
  24430. ASSERT_TRUE(client.is_valid());
  24431. client.enable_server_certificate_verification(false);
  24432. EXPECT_FALSE(client.connect());
  24433. }
  24434. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24435. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24436. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24437. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24438. }
  24439. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  24440. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  24441. std::string cert_pem, key_pem;
  24442. read_file(CLIENT_CERT_FILE, cert_pem);
  24443. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  24444. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  24445. std::vector<char> key(key_pem.begin(), key_pem.end());
  24446. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  24447. key.size(), nullptr};
  24448. ConnectWithPem(pem);
  24449. }
  24450. #endif
  24451. #if !defined(_WIN32)
  24452. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24453. auto secret_dir = std::string("./symlink_test_secret");
  24454. auto served_dir = std::string("./symlink_test_served");
  24455. auto secret_file = secret_dir + "/secret.txt";
  24456. auto symlink_path = served_dir + "/escape";
  24457. // Setup: create directories and files
  24458. mkdir(secret_dir.c_str(), 0755);
  24459. mkdir(served_dir.c_str(), 0755);
  24460. {
  24461. std::ofstream ofs(secret_file);
  24462. ofs << "SECRET_DATA";
  24463. }
  24464. // Create symlink using absolute path so it resolves correctly
  24465. #ifdef PATH_MAX
  24466. char abs_secret[PATH_MAX];
  24467. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24468. #else
  24469. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24470. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24471. ASSERT_NE(nullptr, abs_secret);
  24472. #endif
  24473. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24474. auto se = detail::scope_exit([&] {
  24475. unlink(symlink_path.c_str());
  24476. unlink(secret_file.c_str());
  24477. rmdir(served_dir.c_str());
  24478. rmdir(secret_dir.c_str());
  24479. });
  24480. Server svr;
  24481. svr.set_mount_point("/", served_dir);
  24482. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24483. auto se2 = detail::scope_exit([&] {
  24484. svr.stop();
  24485. listen_thread.join();
  24486. });
  24487. svr.wait_until_ready();
  24488. Client cli("localhost", PORT);
  24489. // Symlink pointing outside base dir should be blocked
  24490. auto res = cli.Get("/escape/secret.txt");
  24491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24492. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24493. }
  24494. #endif
  24495. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24496. // "GET /smuggled" request), reads the first response, and only then sends the
  24497. // embedded request as the body. Returns how many times /smuggled ran.
  24498. //
  24499. // The body is sent AFTER receiving the first response (as in the original
  24500. // PoC) so that the stream_line_reader cannot buffer it together with the
  24501. // headers of the first request.
  24502. static int count_smuggled_requests(const std::string &outer_head,
  24503. std::string &first_response) {
  24504. Server svr;
  24505. svr.set_mount_point("/", "./www");
  24506. std::atomic<int> smuggled_count(0);
  24507. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24508. smuggled_count++;
  24509. res.set_content("oops", "text/plain");
  24510. });
  24511. svr.Post("/post", [&](const Request &req, Response &res) {
  24512. res.set_content(req.body, "text/plain");
  24513. });
  24514. auto port = svr.bind_to_any_port("localhost");
  24515. thread t = thread([&] { svr.listen_after_bind(); });
  24516. auto se = detail::scope_exit([&] {
  24517. svr.stop();
  24518. t.join();
  24519. });
  24520. svr.wait_until_ready();
  24521. auto error = Error::Success;
  24522. auto sock = detail::create_client_socket(
  24523. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24524. /*connection_timeout_sec=*/2, 0,
  24525. /*read_timeout_sec=*/2, 0,
  24526. /*write_timeout_sec=*/2, 0, std::string(), error);
  24527. EXPECT_NE(INVALID_SOCKET, sock);
  24528. if (sock == INVALID_SOCKET) { return -1; }
  24529. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24530. // The "smuggled" request will be sent as the body of the outer request
  24531. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24532. "Host: localhost\r\n"
  24533. "Connection: close\r\n"
  24534. "\r\n";
  24535. auto head = outer_head;
  24536. auto len = std::to_string(smuggled.size());
  24537. for (auto pos = head.find("{len}"); pos != std::string::npos;
  24538. pos = head.find("{len}", pos + len.size())) {
  24539. head.replace(pos, 5, len);
  24540. }
  24541. // Step 1: Send only the outer request headers (no body yet)
  24542. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  24543. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  24544. // Step 2: Read the first response
  24545. char buf[4096];
  24546. for (;;) {
  24547. auto n = recv(sock, buf, sizeof(buf), 0);
  24548. if (n <= 0) break;
  24549. first_response.append(buf, static_cast<size_t>(n));
  24550. // Stop once we have a complete response (headers + body)
  24551. auto hdr_end = first_response.find("\r\n\r\n");
  24552. if (hdr_end != std::string::npos) {
  24553. // Check for Content-Length to know when the body is complete
  24554. auto cl_pos = first_response.find("Content-Length:");
  24555. if (cl_pos != std::string::npos) {
  24556. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  24557. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  24558. auto cl = std::stoul(
  24559. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  24560. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  24561. } else {
  24562. break; // No Content-Length, assume headers-only response
  24563. }
  24564. }
  24565. }
  24566. // Step 3: Now send the body, which looks like a new HTTP request. On a
  24567. // vulnerable server the keep-alive loop reads this as a second request. The
  24568. // server may already have closed the connection, so the result is ignored.
  24569. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  24570. // Half-close so that a server which drained the body sees EOF and closes,
  24571. // instead of the read below waiting for the read timeout.
  24572. #ifdef _WIN32
  24573. ::shutdown(sock, SD_SEND);
  24574. #else
  24575. ::shutdown(sock, SHUT_WR);
  24576. #endif
  24577. // Step 4: Read until the server closes the connection
  24578. for (;;) {
  24579. auto n = recv(sock, buf, sizeof(buf), 0);
  24580. if (n <= 0) break;
  24581. }
  24582. return smuggled_count.load();
  24583. }
  24584. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  24585. // A GET request with Content-Length to a static file handler must have its
  24586. // body drained before the keep-alive connection is reused. Otherwise the
  24587. // unread body bytes are interpreted as the next HTTP request.
  24588. std::string first_response;
  24589. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24590. "Host: localhost\r\n"
  24591. "Content-Length: {len}\r\n"
  24592. "\r\n",
  24593. first_response));
  24594. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  24595. }
  24596. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  24597. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  24598. // be answered with 400 and the connection closed. Treating it as "no body"
  24599. // leaves the body to be parsed as the next request.
  24600. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  24601. const char *targets[] = {
  24602. "GET /file", // handler that never reads the body
  24603. "GET /not-found", // no handler matches (404)
  24604. "POST /post", // handler that reads the body
  24605. };
  24606. for (auto target : targets) {
  24607. for (auto value : values) {
  24608. std::string first_response;
  24609. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  24610. " HTTP/1.1\r\n"
  24611. "Host: localhost\r\n"
  24612. "Content-Length: " +
  24613. value + "\r\n\r\n",
  24614. first_response))
  24615. << target << " with Content-Length: " << value;
  24616. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  24617. << target << " with Content-Length: " << value;
  24618. }
  24619. }
  24620. }
  24621. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  24622. // A 400 for an unparseable request line leaves the rest of the message
  24623. // unread, so the connection must be closed rather than reused.
  24624. std::string first_response;
  24625. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  24626. "Host: localhost\r\n"
  24627. "Content-Length: {len}\r\n"
  24628. "\r\n",
  24629. first_response));
  24630. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24631. }
  24632. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  24633. // Same as above for a header block that fails to parse.
  24634. std::string first_response;
  24635. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24636. "Host: localhost\r\n"
  24637. "Bad Header\r\n"
  24638. "Content-Length: {len}\r\n"
  24639. "\r\n",
  24640. first_response));
  24641. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24642. }
  24643. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  24644. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  24645. // server must not read another request on that connection, even when the
  24646. // request had no body to drain.
  24647. std::string first_response;
  24648. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  24649. "Host: localhost\r\n"
  24650. "\r\n",
  24651. first_response));
  24652. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  24653. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  24654. }
  24655. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  24656. // A content reader that stops early leaves the stream inside the body.
  24657. // Draining the whole Content-Length from there, or reading the body again,
  24658. // reads into the next request, and whatever follows is parsed as a request
  24659. // of its own.
  24660. Server svr;
  24661. std::atomic<int> smuggled_count(0);
  24662. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  24663. svr.Post("/upload", [](const Request &req, Response &res,
  24664. const ContentReader &content_reader) {
  24665. // Stop at the last chunk, so the whole body has been read however it
  24666. // arrives.
  24667. auto length = req.get_header_value_u64("Content-Length");
  24668. size_t total = 0;
  24669. auto consumed = content_reader([&](const char *, size_t n) {
  24670. total += n;
  24671. return total < length;
  24672. });
  24673. EXPECT_FALSE(consumed);
  24674. if (req.has_param("retry")) {
  24675. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  24676. }
  24677. // Replace the 400 the aborted read set, which would close the connection.
  24678. res.set_redirect("/done");
  24679. });
  24680. auto port = svr.bind_to_any_port(HOST);
  24681. thread t = thread([&] { svr.listen_after_bind(); });
  24682. auto se = detail::scope_exit([&] {
  24683. svr.stop();
  24684. t.join();
  24685. });
  24686. svr.wait_until_ready();
  24687. // A front end sees the second request as a POST whose body is the GET. The
  24688. // first body is as long as the POST's headers, so draining it again reads
  24689. // exactly those and leaves the GET to be parsed next.
  24690. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  24691. "Host: localhost\r\n"
  24692. "\r\n";
  24693. std::string second_head = "POST /post HTTP/1.1\r\n"
  24694. "Host: localhost\r\n"
  24695. "Content-Length: " +
  24696. std::to_string(inner.size()) +
  24697. "\r\n"
  24698. "\r\n";
  24699. for (auto target : {"/upload", "/upload?retry"}) {
  24700. smuggled_count = 0;
  24701. std::string request = "POST " + std::string(target) +
  24702. " HTTP/1.1\r\n"
  24703. "Host: localhost\r\n"
  24704. "Content-Length: " +
  24705. std::to_string(second_head.size()) +
  24706. "\r\n"
  24707. "\r\n" +
  24708. std::string(second_head.size(), 'A') + second_head +
  24709. inner;
  24710. std::string response;
  24711. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  24712. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  24713. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  24714. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  24715. EXPECT_EQ(0, smuggled_count.load()) << target;
  24716. }
  24717. }
  24718. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  24719. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  24720. // must be rejected with 400 Bad Request.
  24721. Server svr;
  24722. svr.Post("/test", [&](const Request &, Response &res) {
  24723. res.set_content("ok", "text/plain");
  24724. });
  24725. thread t = thread([&] { svr.listen(HOST, PORT); });
  24726. auto se = detail::scope_exit([&] {
  24727. svr.stop();
  24728. t.join();
  24729. ASSERT_FALSE(svr.is_running());
  24730. });
  24731. svr.wait_until_ready();
  24732. // Exact "chunked"
  24733. {
  24734. auto req = "POST /test HTTP/1.1\r\n"
  24735. "Host: localhost\r\n"
  24736. "Content-Length: 5\r\n"
  24737. "Transfer-Encoding: chunked\r\n"
  24738. "Connection: close\r\n"
  24739. "\r\n"
  24740. "hello";
  24741. std::string response;
  24742. ASSERT_TRUE(send_request(1, req, &response));
  24743. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24744. response.substr(0, response.find("\r\n")));
  24745. }
  24746. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  24747. {
  24748. auto req = "POST /test HTTP/1.1\r\n"
  24749. "Host: localhost\r\n"
  24750. "Content-Length: 5\r\n"
  24751. "Transfer-Encoding: gzip, chunked\r\n"
  24752. "Connection: close\r\n"
  24753. "\r\n"
  24754. "hello";
  24755. std::string response;
  24756. ASSERT_TRUE(send_request(1, req, &response));
  24757. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24758. response.substr(0, response.find("\r\n")));
  24759. }
  24760. }
  24761. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  24762. Server svr;
  24763. svr.Post("/test", [&](const Request &, Response &res) {
  24764. res.set_content("ok", "text/plain");
  24765. });
  24766. thread t = thread([&] { svr.listen(HOST, PORT); });
  24767. auto se = detail::scope_exit([&] {
  24768. svr.stop();
  24769. t.join();
  24770. ASSERT_FALSE(svr.is_running());
  24771. });
  24772. svr.wait_until_ready();
  24773. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  24774. // length cannot be determined, so the server must answer 400 and close
  24775. // rather than treat the request as bodyless and leave the body in the
  24776. // socket for the next request to pick up.
  24777. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  24778. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  24779. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  24780. std::string response;
  24781. ASSERT_TRUE(send_request(1, req, &response));
  24782. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24783. response.substr(0, response.find("\r\n")))
  24784. << transfer_encoding;
  24785. }
  24786. // RFC 9110 5.3: the codings may also be split across several
  24787. // Transfer-Encoding lines, which combine in the order they were received.
  24788. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24789. // just like the single-line "chunked, gzip" above.
  24790. {
  24791. auto req = "POST /test HTTP/1.1\r\n"
  24792. "Host: localhost\r\n"
  24793. "Transfer-Encoding: chunked\r\n"
  24794. "Transfer-Encoding: gzip\r\n"
  24795. "\r\n"
  24796. "0\r\n\r\n";
  24797. std::string response;
  24798. ASSERT_TRUE(send_request(1, req, &response));
  24799. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24800. response.substr(0, response.find("\r\n")));
  24801. }
  24802. // A sequence ending in chunked stays valid.
  24803. auto req = "POST /test HTTP/1.1\r\n"
  24804. "Host: localhost\r\n"
  24805. "Transfer-Encoding: gzip, chunked\r\n"
  24806. "Connection: close\r\n"
  24807. "\r\n"
  24808. "0\r\n\r\n";
  24809. std::string response;
  24810. ASSERT_TRUE(send_request(1, req, &response));
  24811. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24812. // ...including when it is spread over several lines.
  24813. auto split_req = "POST /test HTTP/1.1\r\n"
  24814. "Host: localhost\r\n"
  24815. "Transfer-Encoding: gzip\r\n"
  24816. "Transfer-Encoding: chunked\r\n"
  24817. "Connection: close\r\n"
  24818. "\r\n"
  24819. "0\r\n\r\n";
  24820. std::string split_response;
  24821. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24822. EXPECT_EQ("HTTP/1.1 200 OK",
  24823. split_response.substr(0, split_response.find("\r\n")));
  24824. }
  24825. // Regression for issue #2450: a DELETE without Content-Length on a
  24826. // keep-alive connection must not let the post-response drain consume the
  24827. // next request's bytes.
  24828. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24829. Server svr;
  24830. std::atomic<int> delete_count(0);
  24831. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24832. delete_count++;
  24833. res.status = StatusCode::NoContent_204;
  24834. });
  24835. auto port = svr.bind_to_any_port(HOST);
  24836. thread t = thread([&] { svr.listen_after_bind(); });
  24837. auto se = detail::scope_exit([&] {
  24838. svr.stop();
  24839. t.join();
  24840. });
  24841. svr.wait_until_ready();
  24842. auto error = Error::Success;
  24843. auto sock = detail::create_client_socket(
  24844. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24845. /*connection_timeout_sec=*/2, 0,
  24846. /*read_timeout_sec=*/2, 0,
  24847. /*write_timeout_sec=*/2, 0, std::string(), error);
  24848. ASSERT_NE(INVALID_SOCKET, sock);
  24849. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24850. auto send_request_and_read_response = [&](const std::string &req,
  24851. std::string &out) -> bool {
  24852. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  24853. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24854. char buf[4096];
  24855. for (;;) {
  24856. auto n = recv(sock, buf, sizeof(buf), 0);
  24857. if (n <= 0) { return !out.empty(); }
  24858. out.append(buf, static_cast<size_t>(n));
  24859. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24860. }
  24861. };
  24862. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24863. "Host: localhost\r\n"
  24864. "\r\n";
  24865. std::string resp1;
  24866. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24867. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24868. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24869. "Host: localhost\r\n"
  24870. "Connection: close\r\n"
  24871. "\r\n";
  24872. std::string resp2;
  24873. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24874. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24875. EXPECT_EQ(2, delete_count.load());
  24876. }
  24877. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24878. Server svr;
  24879. svr.Post("/ingest", [&](const Request &, Response &res,
  24880. const ContentReader &content_reader) {
  24881. auto consumed = content_reader([](const char *, size_t) { return false; });
  24882. EXPECT_FALSE(consumed);
  24883. res.status = StatusCode::Conflict_409;
  24884. res.set_header("Connection", "close");
  24885. });
  24886. auto port = svr.bind_to_any_port(HOST);
  24887. thread t = thread([&] { svr.listen_after_bind(); });
  24888. auto se = detail::scope_exit([&] {
  24889. svr.stop();
  24890. t.join();
  24891. });
  24892. svr.wait_until_ready();
  24893. auto error = Error::Success;
  24894. auto sock = detail::create_client_socket(
  24895. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24896. /*connection_timeout_sec=*/2, 0,
  24897. /*read_timeout_sec=*/1, 0,
  24898. /*write_timeout_sec=*/2, 0, std::string(), error);
  24899. ASSERT_NE(INVALID_SOCKET, sock);
  24900. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24901. std::string request = "POST /ingest HTTP/1.1\r\n"
  24902. "Host: localhost\r\n"
  24903. "Transfer-Encoding: chunked\r\n"
  24904. "\r\n"
  24905. "4\r\n"
  24906. "data\r\n";
  24907. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  24908. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24909. std::string response;
  24910. ssize_t received = 0;
  24911. do {
  24912. char buf[4096];
  24913. received = recv(sock, buf, sizeof(buf), 0);
  24914. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24915. } while (received > 0);
  24916. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24917. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24918. EXPECT_EQ(0, received);
  24919. }
  24920. namespace no_proxy_test {
  24921. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24922. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24923. // calling listen().
  24924. class ScopedServer {
  24925. public:
  24926. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24927. ~ScopedServer() {
  24928. svr_.stop();
  24929. if (th_.joinable()) { th_.join(); }
  24930. }
  24931. Server &svr() { return svr_; }
  24932. int port() const { return port_; }
  24933. void listen() {
  24934. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24935. svr_.wait_until_ready();
  24936. }
  24937. private:
  24938. Server svr_;
  24939. std::thread th_;
  24940. int port_ = 0;
  24941. };
  24942. class ProxyAndTargetServers {
  24943. public:
  24944. ProxyAndTargetServers() {
  24945. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24946. proxy_hits_++;
  24947. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24948. res.set_content("via-proxy", "text/plain");
  24949. });
  24950. target_.Get(".*", [this](const Request &req, Response &res) {
  24951. target_hits_++;
  24952. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24953. res.set_content("direct", "text/plain");
  24954. });
  24955. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24956. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24957. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24958. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24959. proxy_mock_.wait_until_ready();
  24960. target_.wait_until_ready();
  24961. }
  24962. ~ProxyAndTargetServers() {
  24963. proxy_mock_.stop();
  24964. target_.stop();
  24965. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24966. if (target_thread_.joinable()) { target_thread_.join(); }
  24967. }
  24968. Server &proxy_mock() { return proxy_mock_; }
  24969. Server &target() { return target_; }
  24970. int proxy_port() const { return proxy_port_; }
  24971. int target_port() const { return target_port_; }
  24972. int proxy_hits() const { return proxy_hits_.load(); }
  24973. int target_hits() const { return target_hits_.load(); }
  24974. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24975. void reset_counters() {
  24976. proxy_hits_ = 0;
  24977. target_hits_ = 0;
  24978. last_had_proxy_authz_ = false;
  24979. }
  24980. private:
  24981. Server proxy_mock_;
  24982. Server target_;
  24983. std::thread proxy_thread_;
  24984. std::thread target_thread_;
  24985. int proxy_port_ = 0;
  24986. int target_port_ = 0;
  24987. std::atomic<int> proxy_hits_{0};
  24988. std::atomic<int> target_hits_{0};
  24989. std::atomic<bool> last_had_proxy_authz_{false};
  24990. };
  24991. inline std::unique_ptr<Client> make_client(const std::string &host,
  24992. ProxyAndTargetServers &s) {
  24993. auto cli = detail::make_unique<Client>(host, s.target_port());
  24994. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24995. cli->set_proxy("127.0.0.1", s.proxy_port());
  24996. return cli;
  24997. }
  24998. } // namespace no_proxy_test
  24999. using no_proxy_test::make_client;
  25000. using no_proxy_test::ProxyAndTargetServers;
  25001. TEST(NoProxyTest, ExactHostnameBypasses) {
  25002. ProxyAndTargetServers s;
  25003. auto cli = make_client("example.com", s);
  25004. cli->set_no_proxy({"example.com"});
  25005. auto res = cli->Get("/");
  25006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25007. EXPECT_EQ(0, s.proxy_hits());
  25008. EXPECT_EQ(1, s.target_hits());
  25009. }
  25010. TEST(NoProxyTest, SubdomainBypasses) {
  25011. ProxyAndTargetServers s;
  25012. auto cli = make_client("foo.example.com", s);
  25013. cli->set_no_proxy({"example.com"});
  25014. auto res = cli->Get("/");
  25015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25016. EXPECT_EQ(0, s.proxy_hits());
  25017. EXPECT_EQ(1, s.target_hits());
  25018. }
  25019. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25020. // Regression guard: "evilexample.com" must not be considered a subdomain
  25021. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25022. // check would let traffic bypass the proxy and leak credentials direct
  25023. // to the attacker host.
  25024. ProxyAndTargetServers s;
  25025. auto cli = make_client("evilexample.com", s);
  25026. cli->set_no_proxy({"example.com"});
  25027. auto res = cli->Get("/");
  25028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25029. EXPECT_GE(s.proxy_hits(), 1);
  25030. EXPECT_EQ(0, s.target_hits());
  25031. }
  25032. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25033. ProxyAndTargetServers s;
  25034. auto cli = make_client("example.com.evil.com", s);
  25035. cli->set_no_proxy({"example.com"});
  25036. auto res = cli->Get("/");
  25037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25038. EXPECT_GE(s.proxy_hits(), 1);
  25039. EXPECT_EQ(0, s.target_hits());
  25040. }
  25041. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25042. ProxyAndTargetServers s;
  25043. auto cli = make_client("example.com", s);
  25044. cli->set_no_proxy({".example.com"});
  25045. auto res = cli->Get("/");
  25046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25047. EXPECT_EQ(0, s.proxy_hits());
  25048. EXPECT_EQ(1, s.target_hits());
  25049. }
  25050. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25051. ProxyAndTargetServers s;
  25052. auto cli = make_client("Example.COM", s);
  25053. cli->set_no_proxy({"EXAMPLE.com"});
  25054. auto res = cli->Get("/");
  25055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25056. EXPECT_EQ(0, s.proxy_hits());
  25057. EXPECT_EQ(1, s.target_hits());
  25058. }
  25059. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25060. ProxyAndTargetServers s;
  25061. auto cli = make_client("example.com.", s);
  25062. cli->set_no_proxy({"example.com"});
  25063. auto res = cli->Get("/");
  25064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25065. EXPECT_EQ(0, s.proxy_hits());
  25066. EXPECT_EQ(1, s.target_hits());
  25067. }
  25068. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25069. // Trailing dots must be normalized on BOTH sides — host and entry.
  25070. // An implementation that only strips the host-side trailing dot would
  25071. // fail to match host "example.com" against entry "example.com." because
  25072. // a literal substring search would compare 11 chars against 12.
  25073. ProxyAndTargetServers s;
  25074. auto cli = make_client("example.com", s);
  25075. cli->set_no_proxy({"example.com."});
  25076. auto res = cli->Get("/");
  25077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25078. EXPECT_EQ(0, s.proxy_hits());
  25079. EXPECT_EQ(1, s.target_hits());
  25080. }
  25081. TEST(NoProxyTest, WildcardBypassesEverything) {
  25082. ProxyAndTargetServers s;
  25083. auto cli = make_client("anything.invalid.test", s);
  25084. cli->set_no_proxy({"*"});
  25085. auto res = cli->Get("/");
  25086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25087. EXPECT_EQ(0, s.proxy_hits());
  25088. EXPECT_EQ(1, s.target_hits());
  25089. }
  25090. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25091. ProxyAndTargetServers s;
  25092. Client cli("127.0.0.1", s.target_port());
  25093. cli.set_proxy("127.0.0.1", s.proxy_port());
  25094. cli.set_no_proxy({"127.0.0.1"});
  25095. auto res = cli.Get("/");
  25096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25097. EXPECT_EQ(0, s.proxy_hits());
  25098. EXPECT_EQ(1, s.target_hits());
  25099. }
  25100. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25101. ProxyAndTargetServers s;
  25102. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25103. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25104. cli.set_proxy("127.0.0.1", s.proxy_port());
  25105. cli.set_no_proxy({"::1"});
  25106. auto res = cli.Get("/");
  25107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25108. EXPECT_EQ(0, s.proxy_hits());
  25109. EXPECT_EQ(1, s.target_hits());
  25110. }
  25111. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25112. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25113. // must still be recognized as IPv6 for CIDR matching. Implementations
  25114. // that detect IPv6 only when the host begins with '[' would parse the
  25115. // host as a hostname and miss the match.
  25116. ProxyAndTargetServers s;
  25117. Client cli("fe80::1", s.target_port());
  25118. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25119. cli.set_proxy("127.0.0.1", s.proxy_port());
  25120. cli.set_no_proxy({"fe80::/10"});
  25121. auto res = cli.Get("/");
  25122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25123. EXPECT_EQ(0, s.proxy_hits());
  25124. EXPECT_EQ(1, s.target_hits());
  25125. }
  25126. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25127. ProxyAndTargetServers s;
  25128. Client cli("::1", s.target_port());
  25129. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25130. cli.set_proxy("127.0.0.1", s.proxy_port());
  25131. cli.set_no_proxy({"[::1]"});
  25132. auto res = cli.Get("/");
  25133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25134. EXPECT_EQ(0, s.proxy_hits());
  25135. EXPECT_EQ(1, s.target_hits());
  25136. }
  25137. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25138. ProxyAndTargetServers s;
  25139. Client cli("fe80::1", s.target_port());
  25140. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25141. cli.set_proxy("127.0.0.1", s.proxy_port());
  25142. cli.set_no_proxy({"[fe80::]/10"});
  25143. auto res = cli.Get("/");
  25144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25145. EXPECT_EQ(0, s.proxy_hits());
  25146. EXPECT_EQ(1, s.target_hits());
  25147. }
  25148. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25149. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25150. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25151. // tricks via address-family conversion.
  25152. ProxyAndTargetServers s;
  25153. Client cli("::ffff:127.0.0.1", s.target_port());
  25154. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25155. cli.set_proxy("127.0.0.1", s.proxy_port());
  25156. cli.set_no_proxy({"127.0.0.1"});
  25157. auto res = cli.Get("/");
  25158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25159. EXPECT_GE(s.proxy_hits(), 1);
  25160. EXPECT_EQ(0, s.target_hits());
  25161. }
  25162. TEST(NoProxyTest, IPv4CidrMatch) {
  25163. ProxyAndTargetServers s;
  25164. Client cli("127.0.0.1", s.target_port());
  25165. cli.set_proxy("127.0.0.1", s.proxy_port());
  25166. cli.set_no_proxy({"127.0.0.0/8"});
  25167. auto res = cli.Get("/");
  25168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25169. EXPECT_EQ(0, s.proxy_hits());
  25170. EXPECT_EQ(1, s.target_hits());
  25171. }
  25172. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25173. ProxyAndTargetServers s;
  25174. Client cli("127.0.0.1", s.target_port());
  25175. cli.set_proxy("127.0.0.1", s.proxy_port());
  25176. cli.set_no_proxy({"10.0.0.0/8"});
  25177. auto res = cli.Get("/");
  25178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25179. EXPECT_GE(s.proxy_hits(), 1);
  25180. EXPECT_EQ(0, s.target_hits());
  25181. }
  25182. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25183. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25184. // IPv4 target matches.
  25185. ProxyAndTargetServers s;
  25186. Client cli("127.0.0.1", s.target_port());
  25187. cli.set_proxy("127.0.0.1", s.proxy_port());
  25188. cli.set_no_proxy({"0.0.0.0/0"});
  25189. auto res = cli.Get("/");
  25190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25191. EXPECT_EQ(0, s.proxy_hits());
  25192. EXPECT_EQ(1, s.target_hits());
  25193. }
  25194. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25195. ProxyAndTargetServers s;
  25196. Client cli("127.0.0.1", s.target_port());
  25197. cli.set_proxy("127.0.0.1", s.proxy_port());
  25198. cli.set_no_proxy({"127.0.0.1"});
  25199. auto res = cli.Get("/");
  25200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25201. EXPECT_EQ(0, s.proxy_hits());
  25202. EXPECT_EQ(1, s.target_hits());
  25203. }
  25204. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25205. ProxyAndTargetServers s;
  25206. Client cli("127.0.0.1", s.target_port());
  25207. cli.set_proxy("127.0.0.1", s.proxy_port());
  25208. cli.set_no_proxy({"127.0.0.0/33"});
  25209. auto res = cli.Get("/");
  25210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25211. EXPECT_GE(s.proxy_hits(), 1);
  25212. EXPECT_EQ(0, s.target_hits());
  25213. }
  25214. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25215. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25216. ProxyAndTargetServers s;
  25217. Client cli("127.0.0.1", s.target_port());
  25218. cli.set_proxy("127.0.0.1", s.proxy_port());
  25219. cli.set_no_proxy({"127.0.0.1/"});
  25220. auto res = cli.Get("/");
  25221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25222. EXPECT_GE(s.proxy_hits(), 1);
  25223. EXPECT_EQ(0, s.target_hits());
  25224. }
  25225. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25226. ProxyAndTargetServers s;
  25227. auto cli = make_client("internal.corp", s);
  25228. cli->set_proxy_basic_auth("u", "p");
  25229. cli->set_no_proxy({"internal.corp"});
  25230. auto res = cli->Get("/");
  25231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25232. EXPECT_EQ(1, s.target_hits());
  25233. EXPECT_EQ(0, s.proxy_hits());
  25234. EXPECT_FALSE(s.last_had_proxy_authz())
  25235. << "Proxy-Authorization must not be sent direct to the target";
  25236. }
  25237. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25238. ProxyAndTargetServers s;
  25239. auto cli = make_client("public.example", s);
  25240. cli->set_proxy_basic_auth("u", "p");
  25241. cli->set_no_proxy({"internal.corp"}); // does not match
  25242. auto res = cli->Get("/");
  25243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25244. EXPECT_GE(s.proxy_hits(), 1);
  25245. EXPECT_TRUE(s.last_had_proxy_authz());
  25246. }
  25247. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25248. std::atomic<int> hits{0};
  25249. std::atomic<int> hits_with_authz{0};
  25250. no_proxy_test::ScopedServer proxy_mock;
  25251. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25252. hits++;
  25253. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25254. if (req.target.find("/redir") != std::string::npos) {
  25255. res.set_redirect("http://other.example/landed");
  25256. } else {
  25257. res.set_content("via-proxy", "text/plain");
  25258. }
  25259. });
  25260. proxy_mock.listen();
  25261. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25262. hits = 0;
  25263. hits_with_authz = 0;
  25264. Client cli("public.example", 80);
  25265. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25266. cli.set_proxy_basic_auth(c.first, c.second);
  25267. cli.set_follow_location(true);
  25268. // The redirect to another host goes through the proxy as well
  25269. auto res = cli.Get("/redir");
  25270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25271. EXPECT_EQ(2, hits.load());
  25272. EXPECT_EQ(2, hits_with_authz.load());
  25273. }
  25274. }
  25275. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25276. ProxyAndTargetServers s;
  25277. auto cli = make_client("anything.test", s);
  25278. auto res = cli->Get("/");
  25279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25280. EXPECT_GE(s.proxy_hits(), 1);
  25281. EXPECT_EQ(0, s.target_hits());
  25282. }
  25283. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25284. ProxyAndTargetServers s;
  25285. auto cli = make_client("example.com", s);
  25286. cli->set_no_proxy({"example.com:8080"});
  25287. auto res = cli->Get("/");
  25288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25289. EXPECT_GE(s.proxy_hits(), 1);
  25290. EXPECT_EQ(0, s.target_hits());
  25291. }
  25292. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25293. ProxyAndTargetServers s;
  25294. auto cli = make_client("anything.test", s);
  25295. cli->set_no_proxy({"", " ", "\t"});
  25296. auto res = cli->Get("/");
  25297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25298. EXPECT_GE(s.proxy_hits(), 1);
  25299. EXPECT_EQ(0, s.target_hits());
  25300. }
  25301. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25302. // An entry with leading/trailing whitespace must still match — env-style
  25303. // values are commonly pasted with stray spaces and an implementation
  25304. // that feeds the raw token directly to inet_pton would fail to match
  25305. // valid CIDRs because of the spaces.
  25306. ProxyAndTargetServers s;
  25307. Client cli("127.0.0.1", s.target_port());
  25308. cli.set_proxy("127.0.0.1", s.proxy_port());
  25309. cli.set_no_proxy({" 127.0.0.0/8 "});
  25310. auto res = cli.Get("/");
  25311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25312. EXPECT_EQ(0, s.proxy_hits());
  25313. EXPECT_EQ(1, s.target_hits());
  25314. }
  25315. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25316. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25317. // go direct and must NOT carry Proxy-Authorization.
  25318. std::atomic<int> proxy_hits{0};
  25319. std::atomic<int> target_hits{0};
  25320. std::atomic<bool> target_saw_authz{false};
  25321. no_proxy_test::ScopedServer proxy_mock, target;
  25322. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25323. proxy_hits++;
  25324. res.status = 302;
  25325. res.set_header("Location", "http://127.0.0.1:" +
  25326. std::to_string(target.port()) + "/landed");
  25327. });
  25328. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25329. target_hits++;
  25330. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25331. res.set_content("direct", "text/plain");
  25332. });
  25333. proxy_mock.listen();
  25334. target.listen();
  25335. Client cli("public.example", target.port());
  25336. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25337. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25338. cli.set_proxy_basic_auth("u", "p");
  25339. cli.set_no_proxy({"127.0.0.1"});
  25340. cli.set_follow_location(true);
  25341. auto res = cli.Get("/redir");
  25342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25343. EXPECT_GE(proxy_hits.load(), 1);
  25344. EXPECT_GE(target_hits.load(), 1);
  25345. EXPECT_FALSE(target_saw_authz.load());
  25346. }
  25347. #ifdef CPPHTTPLIB_SSL_ENABLED
  25348. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25349. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25350. // proxy creds would be sent to the (possibly hostile) origin.
  25351. std::atomic<int> target_hits{0};
  25352. std::atomic<bool> target_saw_proxy_authz{false};
  25353. no_proxy_test::ScopedServer target;
  25354. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25355. target_hits++;
  25356. if (req.has_header("Proxy-Authorization")) {
  25357. target_saw_proxy_authz = true;
  25358. }
  25359. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25360. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25361. "nonce=\"abc\", algorithm=MD5");
  25362. });
  25363. target.listen();
  25364. // The proxy address is set to the target's port: the bypass MUST kick in;
  25365. // if it doesn't, the test still routes "via proxy" to the same server and
  25366. // the Proxy-Authorization assertion below catches the leak.
  25367. Client cli("evil.example", target.port());
  25368. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25369. cli.set_proxy("127.0.0.1", target.port());
  25370. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25371. cli.set_no_proxy({"evil.example"});
  25372. auto res = cli.Get("/x");
  25373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25374. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25375. EXPECT_EQ(1, target_hits.load());
  25376. EXPECT_FALSE(target_saw_proxy_authz.load());
  25377. }
  25378. #endif
  25379. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25380. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25381. std::atomic<int> proxy_hits{0};
  25382. std::atomic<int> bypass_hits{0};
  25383. std::atomic<bool> proxy_saw_c_url{false};
  25384. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25385. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25386. proxy_hits++;
  25387. if (req.path.find("/start") != std::string::npos) {
  25388. res.status = 302;
  25389. res.set_header("Location", "http://127.0.0.1:" +
  25390. std::to_string(bypass_server.port()) +
  25391. "/middle");
  25392. return;
  25393. }
  25394. if (req.path.find("/end") != std::string::npos) {
  25395. proxy_saw_c_url = true;
  25396. res.set_content("c-via-proxy", "text/plain");
  25397. return;
  25398. }
  25399. res.set_content("unexpected", "text/plain");
  25400. });
  25401. // public.example's "advertised" port is arbitrary (the request never lands
  25402. // there — it goes through the proxy), but use a dynamic value to stay
  25403. // friendly with sharded parallel runs.
  25404. int public_port = bypass_server.port();
  25405. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25406. bypass_hits++;
  25407. res.status = 302;
  25408. res.set_header("Location", "http://public.example:" +
  25409. std::to_string(public_port) + "/end");
  25410. });
  25411. proxy_mock.listen();
  25412. bypass_server.listen();
  25413. Client cli("public.example", public_port);
  25414. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25415. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25416. cli.set_no_proxy({"127.0.0.1"});
  25417. cli.set_follow_location(true);
  25418. auto res = cli.Get("/start");
  25419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25420. EXPECT_EQ(StatusCode::OK_200, res->status);
  25421. EXPECT_EQ("c-via-proxy", res->body);
  25422. EXPECT_GE(proxy_hits.load(), 2);
  25423. EXPECT_GE(bypass_hits.load(), 1);
  25424. EXPECT_TRUE(proxy_saw_c_url.load());
  25425. }
  25426. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  25427. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  25428. // request reconnects to the correct endpoint.
  25429. std::atomic<int> proxy_hits{0};
  25430. std::atomic<int> target_hits{0};
  25431. no_proxy_test::ScopedServer proxy_mock, target;
  25432. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25433. proxy_hits++;
  25434. res.set_content("via-proxy", "text/plain");
  25435. });
  25436. target.svr().Get(".*", [&](const Request &, Response &res) {
  25437. target_hits++;
  25438. res.set_content("direct", "text/plain");
  25439. });
  25440. proxy_mock.listen();
  25441. target.listen();
  25442. Client cli("public.example", target.port());
  25443. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25444. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25445. cli.set_keep_alive(true);
  25446. auto res1 = cli.Get("/a");
  25447. ASSERT_TRUE(res1);
  25448. EXPECT_EQ("via-proxy", res1->body);
  25449. EXPECT_EQ(1, proxy_hits.load());
  25450. EXPECT_EQ(0, target_hits.load());
  25451. cli.set_no_proxy({"public.example"});
  25452. auto res2 = cli.Get("/b");
  25453. ASSERT_TRUE(res2);
  25454. EXPECT_EQ("direct", res2->body);
  25455. EXPECT_EQ(1, proxy_hits.load());
  25456. EXPECT_EQ(1, target_hits.load());
  25457. }
  25458. // Forward declarations (see the base64_encode note).
  25459. namespace httplib {
  25460. namespace detail {
  25461. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  25462. int shutdown_socket(socket_t sock) noexcept;
  25463. } // namespace detail
  25464. } // namespace httplib
  25465. namespace proxy_tunnel_test {
  25466. const char *const kTunnelEstablished =
  25467. "HTTP/1.1 200 Connection established\r\n\r\n";
  25468. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  25469. using ConnectReply = std::function<std::string(const std::string &head)>;
  25470. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  25471. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  25472. class ScopedConnectProxy {
  25473. public:
  25474. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  25475. : forward_port_(forward_port), reply_(std::move(reply)) {
  25476. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25477. if (listen_sock_ == INVALID_SOCKET) { return; }
  25478. auto a = loopback(0);
  25479. auto addr = reinterpret_cast<sockaddr *>(&a);
  25480. socklen_t alen = sizeof(a);
  25481. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  25482. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  25483. ::listen(listen_sock_, 4) != 0) {
  25484. return;
  25485. }
  25486. port_ = ntohs(a.sin_port);
  25487. th_ = std::thread([this] { run(); });
  25488. }
  25489. ~ScopedConnectProxy() {
  25490. if (th_.joinable()) {
  25491. stop_ = true;
  25492. auto wake = connect_to(port_);
  25493. th_.join();
  25494. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  25495. }
  25496. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  25497. }
  25498. int port() const { return port_; }
  25499. int connect_hits() const { return connect_hits_.load(); }
  25500. // Head of the last CONNECT request, as the proxy saw it on the wire.
  25501. std::string connect_request() const {
  25502. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25503. return connect_request_;
  25504. }
  25505. private:
  25506. static sockaddr_in loopback(int port) {
  25507. sockaddr_in a{};
  25508. a.sin_family = AF_INET;
  25509. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25510. a.sin_port = htons(static_cast<unsigned short>(port));
  25511. return a;
  25512. }
  25513. static socket_t connect_to(int port) {
  25514. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25515. if (sock == INVALID_SOCKET) { return sock; }
  25516. auto a = loopback(port);
  25517. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  25518. detail::close_socket(sock);
  25519. return INVALID_SOCKET;
  25520. }
  25521. return sock;
  25522. }
  25523. static bool send_all(socket_t sock, const char *data, size_t size) {
  25524. while (size > 0) {
  25525. auto n = detail::send_socket(sock, data, size, 0);
  25526. if (n <= 0) { return false; }
  25527. data += n;
  25528. size -= static_cast<size_t>(n);
  25529. }
  25530. return true;
  25531. }
  25532. void run() {
  25533. for (;;) {
  25534. auto client = ::accept(listen_sock_, nullptr, nullptr);
  25535. if (stop_) {
  25536. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  25537. return;
  25538. }
  25539. if (client == INVALID_SOCKET) { continue; }
  25540. serve(client);
  25541. detail::close_socket(client);
  25542. }
  25543. }
  25544. void serve(socket_t client) {
  25545. std::string head;
  25546. char buf[2048];
  25547. while (head.find("\r\n\r\n") == std::string::npos) {
  25548. if (detail::select_read(client, 5, 0) <= 0) { return; }
  25549. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  25550. if (n <= 0) { return; }
  25551. head.append(buf, static_cast<size_t>(n));
  25552. }
  25553. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  25554. connect_hits_++;
  25555. {
  25556. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25557. connect_request_ = head;
  25558. }
  25559. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  25560. if (!send_all(client, res.data(), res.size()) ||
  25561. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  25562. return;
  25563. }
  25564. auto origin = connect_to(forward_port_);
  25565. if (origin == INVALID_SOCKET) { return; }
  25566. // When either side stops, shut both down so the other pump returns too.
  25567. auto pump = [&](socket_t from, socket_t to) {
  25568. char b[8192];
  25569. for (;;) {
  25570. auto n = detail::read_socket(from, b, sizeof(b), 0);
  25571. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  25572. }
  25573. detail::shutdown_socket(client);
  25574. detail::shutdown_socket(origin);
  25575. };
  25576. std::thread up([&] { pump(client, origin); });
  25577. pump(origin, client);
  25578. up.join();
  25579. detail::close_socket(origin);
  25580. }
  25581. int forward_port_;
  25582. ConnectReply reply_;
  25583. socket_t listen_sock_ = INVALID_SOCKET;
  25584. int port_ = 0;
  25585. std::thread th_;
  25586. std::atomic<bool> stop_{false};
  25587. std::atomic<int> connect_hits_{0};
  25588. mutable std::mutex connect_request_mutex_;
  25589. std::string connect_request_;
  25590. };
  25591. } // namespace proxy_tunnel_test
  25592. #ifdef CPPHTTPLIB_SSL_ENABLED
  25593. namespace proxy_tunnel_test {
  25594. // SSLServer counterpart to no_proxy_test::ScopedServer.
  25595. class ScopedSSLServer {
  25596. public:
  25597. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  25598. port_ = svr_.bind_to_any_port("127.0.0.1");
  25599. }
  25600. ~ScopedSSLServer() {
  25601. svr_.stop();
  25602. if (th_.joinable()) { th_.join(); }
  25603. }
  25604. SSLServer &svr() { return svr_; }
  25605. int port() const { return port_; }
  25606. void listen() {
  25607. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25608. svr_.wait_until_ready();
  25609. }
  25610. private:
  25611. SSLServer svr_;
  25612. std::thread th_;
  25613. int port_ = 0;
  25614. };
  25615. // Sends one request through the CONNECT proxy to the TLS origin with a
  25616. // credential configured for each hop, and checks that each credential reaches
  25617. // only the hop it was configured for: the proxy's on the CONNECT request, the
  25618. // origin's (every header in origin_headers) on the tunnelled request.
  25619. void CredentialsStayWithTheirHop(
  25620. const std::function<void(SSLClient &)> &set_credentials,
  25621. const std::string &scheme,
  25622. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  25623. std::atomic<int> origin_hits{0};
  25624. std::atomic<bool> origin_saw_proxy_authz{false};
  25625. std::atomic<bool> origin_saw_headers{false};
  25626. ScopedSSLServer origin;
  25627. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25628. origin_hits++;
  25629. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  25630. origin_saw_headers =
  25631. std::all_of(origin_headers.begin(), origin_headers.end(),
  25632. [&](const std::string &h) { return req.has_header(h); });
  25633. res.set_content("ok", "text/plain");
  25634. });
  25635. origin.listen();
  25636. ScopedConnectProxy proxy(origin.port());
  25637. ASSERT_NE(0, proxy.port());
  25638. // Pinned to 127.0.0.1 for the same reason as the test below.
  25639. SSLClient cli("127.0.0.1", origin.port());
  25640. cli.enable_server_certificate_verification(false);
  25641. cli.set_proxy("127.0.0.1", proxy.port());
  25642. set_credentials(cli);
  25643. auto res = cli.Get("/x");
  25644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25645. EXPECT_EQ(StatusCode::OK_200, res->status);
  25646. EXPECT_EQ(1, origin_hits.load());
  25647. EXPECT_EQ(1, proxy.connect_hits());
  25648. EXPECT_TRUE(origin_saw_headers.load());
  25649. EXPECT_FALSE(origin_saw_proxy_authz.load())
  25650. << "Proxy-Authorization must not be sent inside the tunnel";
  25651. auto connect_req = proxy.connect_request();
  25652. EXPECT_NE(std::string::npos,
  25653. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  25654. for (const auto &h : origin_headers) {
  25655. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  25656. << h << " must not be sent to the proxy on CONNECT";
  25657. }
  25658. }
  25659. } // namespace proxy_tunnel_test
  25660. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  25661. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25662. [](SSLClient &cli) {
  25663. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25664. cli.set_basic_auth("origin-user", "origin-pass");
  25665. },
  25666. "Basic");
  25667. }
  25668. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  25669. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25670. [](SSLClient &cli) {
  25671. cli.set_proxy_bearer_token_auth("proxy-token");
  25672. cli.set_bearer_token_auth("origin-token");
  25673. },
  25674. "Bearer");
  25675. }
  25676. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  25677. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25678. [](SSLClient &cli) {
  25679. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25680. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  25681. {"Cookie", "sid=origin-session"},
  25682. {"X-Api-Key", "origin-key"}});
  25683. },
  25684. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  25685. }
  25686. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  25687. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  25688. // retry; otherwise proxy creds would be sent to the origin.
  25689. std::atomic<int> origin_hits{0};
  25690. std::atomic<bool> origin_saw_proxy_authz{false};
  25691. proxy_tunnel_test::ScopedSSLServer origin;
  25692. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25693. origin_hits++;
  25694. if (req.has_header("Proxy-Authorization")) {
  25695. origin_saw_proxy_authz = true;
  25696. }
  25697. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25698. res.set_header("Proxy-Authenticate",
  25699. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  25700. "algorithm=MD5");
  25701. });
  25702. origin.listen();
  25703. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25704. ASSERT_NE(0, proxy.port());
  25705. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  25706. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  25707. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  25708. // and answer with its own status, making this test flaky.
  25709. SSLClient cli("127.0.0.1", origin.port());
  25710. cli.enable_server_certificate_verification(false);
  25711. cli.set_proxy("127.0.0.1", proxy.port());
  25712. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25713. auto res = cli.Get("/x");
  25714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25715. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25716. EXPECT_EQ(1, origin_hits.load());
  25717. EXPECT_FALSE(origin_saw_proxy_authz.load());
  25718. EXPECT_EQ(1, proxy.connect_hits());
  25719. }
  25720. #endif
  25721. namespace proxy_tunnel_test {
  25722. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  25723. // anything else gets a 407 with `challenge`.
  25724. ConnectReply require_proxy_auth(const std::string &expected,
  25725. const std::string &challenge) {
  25726. return [=](const std::string &head) -> std::string {
  25727. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  25728. std::string::npos) {
  25729. return kTunnelEstablished;
  25730. }
  25731. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  25732. "Proxy-Authenticate: " +
  25733. challenge + "\r\nContent-Length: 0\r\n\r\n";
  25734. };
  25735. }
  25736. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  25737. // request, then echoes.
  25738. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  25739. ws.send(
  25740. "authorization:" + req.get_header_value("Authorization") +
  25741. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  25742. std::string msg;
  25743. while (ws.read(msg)) {
  25744. ws.send(msg);
  25745. }
  25746. }
  25747. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  25748. class ScopedWebSocketOrigin {
  25749. public:
  25750. ScopedWebSocketOrigin() {
  25751. server_.svr().WebSocket("/ws", report_auth_then_echo);
  25752. server_.listen();
  25753. }
  25754. int port() const { return server_.port(); }
  25755. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  25756. std::string url() const {
  25757. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  25758. }
  25759. private:
  25760. no_proxy_test::ScopedServer server_;
  25761. };
  25762. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  25763. // passed as a constructor header, and checks that each reaches only its hop.
  25764. void WebSocketCredentialsStayWithTheirHop(
  25765. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  25766. const std::string &proxy_authz, const std::string &origin_authz) {
  25767. ScopedWebSocketOrigin origin;
  25768. ScopedConnectProxy proxy(
  25769. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  25770. ASSERT_NE(0, proxy.port());
  25771. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  25772. client.set_proxy("127.0.0.1", proxy.port());
  25773. set_proxy_credentials(client);
  25774. auto res = client.connect();
  25775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25776. std::string msg;
  25777. ASSERT_TRUE(client.read(msg));
  25778. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  25779. client.close();
  25780. EXPECT_EQ(1, proxy.connect_hits());
  25781. EXPECT_EQ(std::string::npos,
  25782. proxy.connect_request().find("\r\nAuthorization: "))
  25783. << "origin credentials must not be sent to the proxy";
  25784. }
  25785. } // namespace proxy_tunnel_test
  25786. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  25787. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25788. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25789. ASSERT_NE(0, proxy.port());
  25790. ws::WebSocketClient client(origin.url());
  25791. client.set_proxy("127.0.0.1", proxy.port());
  25792. auto res = client.connect();
  25793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25794. std::string msg;
  25795. ASSERT_TRUE(client.read(msg));
  25796. ASSERT_TRUE(client.send("hello"));
  25797. ASSERT_TRUE(client.read(msg));
  25798. EXPECT_EQ("hello", msg);
  25799. client.close();
  25800. EXPECT_EQ(1, proxy.connect_hits());
  25801. auto target = "127.0.0.1:" + std::to_string(origin.port());
  25802. auto connect_req = proxy.connect_request();
  25803. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  25804. EXPECT_NE(std::string::npos,
  25805. connect_req.find("\r\nHost: " + target + "\r\n"));
  25806. }
  25807. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  25808. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  25809. [](ws::WebSocketClient &cli) {
  25810. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25811. },
  25812. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  25813. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  25814. }
  25815. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  25816. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  25817. [](ws::WebSocketClient &cli) {
  25818. cli.set_proxy_bearer_token_auth("proxy-token");
  25819. },
  25820. "Bearer proxy-token", "Bearer origin-token");
  25821. }
  25822. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  25823. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25824. proxy_tunnel_test::ScopedConnectProxy proxy(
  25825. origin.port(), proxy_tunnel_test::require_proxy_auth(
  25826. "Basic " + detail::base64_encode("proxy-user:"),
  25827. "Basic realm=\"proxy\""));
  25828. ASSERT_NE(0, proxy.port());
  25829. ws::WebSocketClient client(origin.url());
  25830. client.set_proxy("127.0.0.1", proxy.port());
  25831. client.set_proxy_basic_auth("proxy-user", "");
  25832. auto res = client.connect();
  25833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25834. client.close();
  25835. EXPECT_EQ(1, proxy.connect_hits());
  25836. }
  25837. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  25838. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25839. proxy_tunnel_test::ScopedConnectProxy proxy(
  25840. origin.port(), proxy_tunnel_test::require_proxy_auth(
  25841. "Bearer proxy-token", "Basic realm=\"proxy\""));
  25842. ASSERT_NE(0, proxy.port());
  25843. ws::WebSocketClient client(origin.url());
  25844. client.set_proxy("127.0.0.1", proxy.port());
  25845. auto res = client.connect();
  25846. EXPECT_FALSE(res);
  25847. EXPECT_EQ(Error::ProxyConnection, res.error());
  25848. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  25849. EXPECT_EQ("Basic realm=\"proxy\"",
  25850. res.get_header_value("Proxy-Authenticate"));
  25851. EXPECT_FALSE(client.is_open());
  25852. }
  25853. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  25854. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25855. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25856. ASSERT_NE(0, proxy.port());
  25857. ws::WebSocketClient client(origin.url());
  25858. client.set_proxy("127.0.0.1", proxy.port());
  25859. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25860. client.set_no_proxy({"127.0.0.1"});
  25861. auto res = client.connect();
  25862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25863. std::string msg;
  25864. ASSERT_TRUE(client.read(msg));
  25865. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  25866. << "proxy credentials must not reach a bypassed origin";
  25867. client.close();
  25868. EXPECT_EQ(0, proxy.connect_hits());
  25869. }
  25870. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  25871. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25872. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25873. ASSERT_NE(0, proxy.port());
  25874. ws::WebSocketClient client(origin.url());
  25875. client.set_proxy("127.0.0.1", proxy.port());
  25876. ASSERT_TRUE(client.connect());
  25877. ASSERT_TRUE(client.connect());
  25878. client.close();
  25879. EXPECT_EQ(2, proxy.connect_hits());
  25880. }
  25881. #ifdef CPPHTTPLIB_SSL_ENABLED
  25882. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  25883. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25884. proxy_tunnel_test::ScopedConnectProxy proxy(
  25885. origin.port(), [](const std::string &head) -> std::string {
  25886. if (head.find(
  25887. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  25888. std::string::npos) {
  25889. return proxy_tunnel_test::kTunnelEstablished;
  25890. }
  25891. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  25892. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  25893. "nonce=\"abc\", algorithm=MD5\r\n"
  25894. "Content-Length: 0\r\n\r\n";
  25895. });
  25896. ASSERT_NE(0, proxy.port());
  25897. ws::WebSocketClient client(origin.url());
  25898. client.set_proxy("127.0.0.1", proxy.port());
  25899. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25900. auto res = client.connect();
  25901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25902. std::string msg;
  25903. ASSERT_TRUE(client.read(msg));
  25904. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  25905. client.close();
  25906. EXPECT_EQ(2, proxy.connect_hits());
  25907. }
  25908. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  25909. proxy_tunnel_test::ScopedSSLServer origin;
  25910. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  25911. origin.listen();
  25912. proxy_tunnel_test::ScopedConnectProxy proxy(
  25913. origin.port(), proxy_tunnel_test::require_proxy_auth(
  25914. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  25915. ASSERT_NE(0, proxy.port());
  25916. ws::WebSocketClient client(
  25917. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  25918. client.enable_server_certificate_verification(false);
  25919. client.set_proxy("127.0.0.1", proxy.port());
  25920. client.set_proxy_bearer_token_auth("proxy-token");
  25921. auto res = client.connect();
  25922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25923. std::string msg;
  25924. ASSERT_TRUE(client.read(msg));
  25925. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  25926. << "Proxy-Authorization must not be sent inside the tunnel";
  25927. client.close();
  25928. EXPECT_EQ(1, proxy.connect_hits());
  25929. }
  25930. #endif