1
0

test.cc 973 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. } // namespace tls
  69. } // namespace httplib
  70. #endif
  71. using namespace std;
  72. using namespace httplib;
  73. const char *HOST = "localhost";
  74. static int get_base_port() {
  75. const char *shard = getenv("GTEST_SHARD_INDEX");
  76. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  77. }
  78. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  79. // New standalone tests MUST use svr.bind_to_any_port() instead.
  80. const int PORT = get_base_port();
  81. const string LONG_QUERY_VALUE = string(25000, '@');
  82. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  83. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  84. const string TOO_LONG_QUERY_URL =
  85. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  86. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  87. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  88. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  89. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  90. return file.name == key;
  91. });
  92. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  93. return *it;
  94. #else
  95. if (it != items.end()) { return *it; }
  96. throw std::runtime_error("invalid multipart form data name error");
  97. #endif
  98. }
  99. static void read_file(const std::string &path, std::string &out) {
  100. std::ifstream fs(path, std::ios_base::binary);
  101. if (!fs) {
  102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  103. return;
  104. #else
  105. throw std::runtime_error("File not found: " + path);
  106. #endif
  107. }
  108. fs.seekg(0, std::ios_base::end);
  109. auto size = fs.tellg();
  110. fs.seekg(0);
  111. out.resize(static_cast<size_t>(size));
  112. fs.read(&out[0], static_cast<std::streamsize>(size));
  113. }
  114. class UnixSocketTest : public ::testing::Test {
  115. protected:
  116. void TearDown() override { std::remove(pathname_.c_str()); }
  117. void client_GET(const std::string &addr) {
  118. httplib::Client cli{addr};
  119. cli.set_address_family(AF_UNIX);
  120. ASSERT_TRUE(cli.is_valid());
  121. const auto &result = cli.Get(pattern_);
  122. ASSERT_TRUE(result) << "error: " << result.error();
  123. const auto &resp = result.value();
  124. EXPECT_EQ(resp.status, StatusCode::OK_200);
  125. EXPECT_EQ(resp.body, content_);
  126. }
  127. static std::string make_sock_path() {
  128. const char *shard = getenv("GTEST_SHARD_INDEX");
  129. return shard ? std::string("./httplib-server-") + shard + ".sock"
  130. : "./httplib-server.sock";
  131. }
  132. const std::string pathname_{make_sock_path()};
  133. const std::string pattern_{"/hi"};
  134. const std::string content_{"Hello World!"};
  135. };
  136. TEST_F(UnixSocketTest, pathname) {
  137. httplib::Server svr;
  138. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  139. res.set_content(content_, "text/plain");
  140. });
  141. std::thread t{[&] {
  142. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  143. }};
  144. auto se = detail::scope_exit([&] {
  145. svr.stop();
  146. t.join();
  147. ASSERT_FALSE(svr.is_running());
  148. });
  149. svr.wait_until_ready();
  150. ASSERT_TRUE(svr.is_running());
  151. client_GET(pathname_);
  152. // ".//x.sock", which is not taken for a URL
  153. client_GET("./" + pathname_.substr(1));
  154. }
  155. #if defined(__linux__) || \
  156. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  157. TEST_F(UnixSocketTest, PeerPid) {
  158. httplib::Server svr;
  159. std::string remote_port_val;
  160. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  161. res.set_content(content_, "text/plain");
  162. remote_port_val = std::to_string(req.remote_port);
  163. });
  164. std::thread t{[&] {
  165. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  166. }};
  167. auto se = detail::scope_exit([&] {
  168. svr.stop();
  169. t.join();
  170. ASSERT_FALSE(svr.is_running());
  171. });
  172. svr.wait_until_ready();
  173. ASSERT_TRUE(svr.is_running());
  174. client_GET(pathname_);
  175. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  176. }
  177. #endif
  178. #ifdef __linux__
  179. TEST_F(UnixSocketTest, abstract) {
  180. constexpr char svr_path[]{"\x00httplib-server.sock"};
  181. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  182. httplib::Server svr;
  183. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. client_GET(abstract_addr);
  197. }
  198. #endif
  199. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  200. httplib::Server svr;
  201. std::string received_host_header;
  202. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  203. // Capture the Host header sent by the client
  204. auto host_iter = req.headers.find("Host");
  205. if (host_iter != req.headers.end()) {
  206. received_host_header = host_iter->second;
  207. }
  208. res.set_content(content_, "text/plain");
  209. });
  210. std::thread t{[&] {
  211. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  212. }};
  213. auto se = detail::scope_exit([&] {
  214. svr.stop();
  215. t.join();
  216. ASSERT_FALSE(svr.is_running());
  217. });
  218. svr.wait_until_ready();
  219. ASSERT_TRUE(svr.is_running());
  220. // Test that Host header is automatically set to "localhost" for Unix socket
  221. // connections
  222. httplib::Client cli{pathname_};
  223. cli.set_address_family(AF_UNIX);
  224. ASSERT_TRUE(cli.is_valid());
  225. const auto &result = cli.Get(pattern_);
  226. ASSERT_TRUE(result) << "error: " << result.error();
  227. const auto &resp = result.value();
  228. EXPECT_EQ(resp.status, StatusCode::OK_200);
  229. EXPECT_EQ(resp.body, content_);
  230. // Verify that Host header was automatically set to "localhost"
  231. EXPECT_EQ(received_host_header, "localhost");
  232. }
  233. #ifndef _WIN32
  234. TEST(SocketStream, wait_writable_UNIX) {
  235. int fds[2];
  236. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  237. const auto asSocketStream = [&](socket_t fd,
  238. std::function<bool(Stream &)> func) {
  239. return detail::process_client_socket(
  240. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  241. };
  242. asSocketStream(fds[0], [&](Stream &s0) {
  243. EXPECT_EQ(s0.socket(), fds[0]);
  244. EXPECT_TRUE(s0.wait_writable());
  245. EXPECT_TRUE(s0.is_peer_alive());
  246. EXPECT_EQ(0, close(fds[1]));
  247. EXPECT_FALSE(s0.is_peer_alive());
  248. return true;
  249. });
  250. EXPECT_EQ(0, close(fds[0]));
  251. }
  252. TEST(SocketStream, wait_writable_INET) {
  253. sockaddr_in addr;
  254. memset(&addr, 0, sizeof(addr));
  255. addr.sin_family = AF_INET;
  256. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  257. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  258. int disconnected_svr_sock = -1;
  259. std::thread svr{[&] {
  260. const int s = socket(AF_INET, SOCK_STREAM, 0);
  261. ASSERT_LE(0, s);
  262. // PORT + 1 is shared with the SSL redirect tests and with
  263. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  264. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  265. // because that happens on a worker thread the ASSERT does not stop the
  266. // test: it runs on and fails at the disconnected_svr_sock check instead.
  267. default_socket_options(s);
  268. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  269. ASSERT_EQ(0, listen(s, 1));
  270. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  271. ASSERT_EQ(0, close(s));
  272. }};
  273. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  274. std::thread cli{[&] {
  275. const int s = socket(AF_INET, SOCK_STREAM, 0);
  276. ASSERT_LE(0, s);
  277. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  278. ASSERT_EQ(0, close(s));
  279. }};
  280. cli.join();
  281. svr.join();
  282. ASSERT_NE(disconnected_svr_sock, -1);
  283. const auto asSocketStream = [&](socket_t fd,
  284. std::function<bool(Stream &)> func) {
  285. return detail::process_client_socket(
  286. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  287. };
  288. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  289. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  290. // wait_writable() returns true because select_write() only checks if the
  291. // send buffer has space. Peer disconnection is detected later by send().
  292. EXPECT_TRUE(ss.wait_writable());
  293. return true;
  294. });
  295. ASSERT_EQ(0, close(disconnected_svr_sock));
  296. }
  297. #endif // #ifndef _WIN32
  298. TEST(SetSocketOptTest, TcpNoDelay) {
  299. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  300. ASSERT_NE(sock, INVALID_SOCKET);
  301. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  302. int val = 0;
  303. socklen_t len = sizeof(val);
  304. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  305. reinterpret_cast<char *>(&val), &len));
  306. EXPECT_NE(val, 0);
  307. detail::close_socket(sock);
  308. }
  309. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  310. // accept() reports failures through WSAGetLastError() on Windows and through
  311. // errno everywhere else. Asking the wrong one is what made the accept loop
  312. // treat every recoverable failure as fatal on Windows.
  313. struct Classification {
  314. bool resource;
  315. bool transient;
  316. };
  317. auto classify = [](int err) {
  318. #ifdef _WIN32
  319. WSASetLastError(err);
  320. #else
  321. errno = err;
  322. #endif
  323. // Read both before asserting: an assertion may clobber the error slot.
  324. Classification c;
  325. c.resource = detail::is_accept_resource_error();
  326. c.transient = detail::is_accept_transient_error();
  327. return c;
  328. };
  329. #ifdef _WIN32
  330. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  331. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  332. WSAECONNRESET, WSAECONNABORTED};
  333. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  334. #else
  335. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  336. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  337. ECONNABORTED};
  338. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  339. #endif
  340. for (auto err : resource_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.resource) << "error " << err;
  343. EXPECT_FALSE(c.transient) << "error " << err;
  344. }
  345. for (auto err : transient_errors) {
  346. const auto c = classify(err);
  347. EXPECT_TRUE(c.transient) << "error " << err;
  348. EXPECT_FALSE(c.resource) << "error " << err;
  349. }
  350. for (auto err : fatal_errors) {
  351. const auto c = classify(err);
  352. EXPECT_FALSE(c.resource) << "error " << err;
  353. EXPECT_FALSE(c.transient) << "error " << err;
  354. }
  355. #ifdef _WIN32
  356. WSASetLastError(0);
  357. #else
  358. errno = 0;
  359. #endif
  360. }
  361. TEST(ClientTest, MoveConstructible) {
  362. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  363. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  364. }
  365. TEST(ClientTest, MoveAssignable) {
  366. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  367. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  368. }
  369. #ifdef _WIN32
  370. TEST(StartupTest, WSAStartup) {
  371. WSADATA wsaData;
  372. int ret = WSAStartup(0x0002, &wsaData);
  373. ASSERT_EQ(0, ret);
  374. }
  375. #endif
  376. TEST(DecodePathTest, PercentCharacter) {
  377. EXPECT_EQ(
  378. decode_path_component(
  379. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  380. U8("descrip=Gastos áéíóúñÑ 6"));
  381. }
  382. TEST(DecodePathTest, PercentCharacterNUL) {
  383. string expected;
  384. expected.push_back('x');
  385. expected.push_back('\0');
  386. expected.push_back('x');
  387. EXPECT_EQ(decode_path_component("x%00x"), expected);
  388. }
  389. TEST(DecodePathTest, UnicodeEncoding) {
  390. // %u0041 = 'A' (1-byte UTF-8)
  391. EXPECT_EQ("A", decode_path_component("%u0041"));
  392. // %u00E9 = 'é' (2-byte UTF-8)
  393. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  394. // %u3042 = 'あ' (3-byte UTF-8)
  395. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  396. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  397. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  398. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  399. // neighbours)
  400. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  401. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  402. }
  403. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  404. // A sign or whitespace inside the two-character escape window must not be
  405. // accepted as a valid percent-encoding; the sequence is passed through
  406. // literally, matching decode_uri_component / decode_path_component.
  407. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  408. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  409. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  410. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  411. // Well-formed escapes still decode.
  412. EXPECT_EQ("-", decode_query_component("%2D", false));
  413. EXPECT_EQ("A", decode_query_component("%41", false));
  414. }
  415. TEST(SanitizeFilenameTest, VariousPatterns) {
  416. // Path traversal
  417. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  419. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  420. // Normal and edge cases
  421. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  422. EXPECT_EQ("filename.txt",
  423. httplib::sanitize_filename("/path/to/filename.txt"));
  424. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  425. EXPECT_EQ("", httplib::sanitize_filename(".."));
  426. EXPECT_EQ("", httplib::sanitize_filename(""));
  427. // Null bytes stripped
  428. EXPECT_EQ("safe.txt",
  429. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  430. // Whitespace-only rejected
  431. EXPECT_EQ("", httplib::sanitize_filename(" "));
  432. }
  433. // Forward declaration (see the base64_encode note below): split builds move the
  434. // definition into httplib.cc, so re-declaring it here lets the test link.
  435. namespace httplib {
  436. namespace detail {
  437. bool is_chunked_transfer_encoding(const Headers &headers);
  438. } // namespace detail
  439. } // namespace httplib
  440. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  441. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  442. auto make = [](std::initializer_list<const char *> lines) {
  443. Headers h;
  444. for (auto te : lines) {
  445. if (te) { h.emplace("Transfer-Encoding", te); }
  446. }
  447. return h;
  448. };
  449. // Sole coding, matched case-insensitively.
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  453. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  457. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  462. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  463. // were received, into one list. Headers preserves that order, so the answer
  464. // is decided by the last coding of the last line and the order the lines
  465. // arrived in is significant.
  466. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  467. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  469. // The split can fall anywhere in the list.
  470. EXPECT_TRUE(
  471. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  472. EXPECT_FALSE(
  473. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  474. // A trailing line naming no coding leaves the list ending in nothing, so it
  475. // must not inherit the chunked from the line before it.
  476. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  477. }
  478. // Forward declarations (see the base64_encode note below).
  479. namespace httplib {
  480. namespace detail {
  481. bool parse_status_line(const char *line, std::string &version, int &status,
  482. std::string &reason);
  483. std::string file_extension(const std::string &path);
  484. std::string
  485. find_content_type(const std::string &path,
  486. const std::map<std::string, std::string> &user_data,
  487. const std::string &default_content_type);
  488. bool can_compress_content_type(const std::string &content_type);
  489. bool is_prohibited_header_name(const std::string &name);
  490. #ifdef CPPHTTPLIB_SSL_ENABLED
  491. bool match_hostname(const std::string &pattern, const std::string &hostname);
  492. #endif
  493. } // namespace detail
  494. } // namespace httplib
  495. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  496. struct {
  497. const char *line;
  498. const char *version;
  499. int status;
  500. const char *reason;
  501. } cases[] = {
  502. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  503. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  504. // The reason phrase may be empty, or left out along with its space.
  505. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  506. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  507. };
  508. for (const auto &c : cases) {
  509. std::string version;
  510. int status = 0;
  511. std::string reason = "unset";
  512. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  513. << c.line;
  514. EXPECT_EQ(c.version, version);
  515. EXPECT_EQ(c.status, status);
  516. EXPECT_EQ(c.reason, reason);
  517. }
  518. }
  519. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  520. const char *lines[] = {
  521. "HTTP/2 200 OK\r\n",
  522. "HTTP/1.2 200 OK\r\n",
  523. "HTTP/1.1 20 OK\r\n",
  524. "HTTP/1.1 2000 OK\r\n",
  525. "HTTP/1.1 2x0 OK\r\n",
  526. "HTTP/1.1 200 OK\r\n",
  527. "HTTP/1.1 200OK\r\n",
  528. "HTTP/1.1 200 O\rK\r\n",
  529. "HTTP/1.1 200 OK",
  530. "HTTP/1.1 200 OK\r\nX",
  531. "",
  532. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  533. "HTTP/1.1 200 OK\n",
  534. #endif
  535. };
  536. for (auto line : lines) {
  537. std::string version;
  538. int status = 0;
  539. std::string reason;
  540. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  541. << line;
  542. }
  543. }
  544. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  545. // Long enough to overflow the stack when matched with std::regex.
  546. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  547. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  548. std::string version;
  549. int status = 0;
  550. std::string reason;
  551. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  552. EXPECT_EQ(200, status);
  553. EXPECT_EQ(long_reason, reason);
  554. }
  555. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  556. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  557. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  558. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  559. EXPECT_EQ("", detail::file_extension("noext"));
  560. EXPECT_EQ("", detail::file_extension("a."));
  561. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  562. EXPECT_EQ("", detail::file_extension("a.b-c"));
  563. // Long enough to overflow the stack when matched with std::regex.
  564. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  565. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  566. }
  567. #ifdef CPPHTTPLIB_SSL_ENABLED
  568. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  569. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  570. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  572. // A wildcard needs two labels after it, in the leftmost label only
  573. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  574. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  575. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  576. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  577. EXPECT_FALSE(
  578. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  579. // No name may have an empty label
  580. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  581. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  582. }
  583. #endif
  584. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  585. detail::case_ignore::hash hash;
  586. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  587. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  588. // Long enough to overflow the stack if hashed one call per character.
  589. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  590. }
  591. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  592. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  593. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  594. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  595. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  596. // Same 26-bit hash as html, svg and js.
  597. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  598. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  600. }
  601. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  602. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  603. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  604. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  605. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  606. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  607. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  608. // Same 26-bit hash as application/json.
  609. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  610. }
  611. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  612. Request req;
  613. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  614. EXPECT_TRUE(req.is_multipart_form_data());
  615. std::string boundary;
  616. EXPECT_TRUE(detail::parse_multipart_boundary(
  617. req.get_header_value("Content-Type"), boundary));
  618. EXPECT_EQ("x", boundary);
  619. }
  620. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  621. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  622. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  623. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  624. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  625. // Same 26-bit hash as REMOTE_ADDR.
  626. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  627. }
  628. // Forward declaration: in split builds split.py strips `inline` and moves the
  629. // definition into httplib.cc, so detail::base64_encode is not visible from the
  630. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  631. // in both header-only and split builds.
  632. namespace httplib {
  633. namespace detail {
  634. std::string base64_encode(const std::string &in);
  635. } // namespace detail
  636. } // namespace httplib
  637. TEST(Base64EncodeTest, KnownAnswers) {
  638. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  639. // where the accumulator's top bit is already set before the next shift.
  640. EXPECT_EQ("", detail::base64_encode(""));
  641. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  642. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  643. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  644. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  645. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  646. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  647. // High bytes keep the top bit set across several rounds.
  648. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  649. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  650. }
  651. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  652. string unescapedCharacters = "-_.!~*'()";
  653. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  654. }
  655. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  656. string reservedCharacters = ";,/?:@&=+$";
  657. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  658. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  659. }
  660. TEST(ClientQueryOrder, PreserveOrder) {
  661. // This test reproduces Issue #2259: client may reorder query parameters
  662. // when sending a GET request. The expected behavior is that the client
  663. // preserves the original query string order when the caller supplied it
  664. // as part of the path.
  665. Server svr;
  666. svr.Get("/", [&](const Request &req, Response &res) {
  667. // Echo back the raw target so the test can assert ordering
  668. res.set_content(req.target, "text/plain");
  669. });
  670. std::thread t{[&] { svr.listen(HOST, PORT); }};
  671. auto se = detail::scope_exit([&] {
  672. svr.stop();
  673. t.join();
  674. ASSERT_FALSE(svr.is_running());
  675. });
  676. svr.wait_until_ready();
  677. Client cli(HOST, PORT);
  678. ASSERT_TRUE(cli.is_valid());
  679. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  680. auto res = cli.Get(original);
  681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  682. // Expect the echoed target to exactly match the original path (order
  683. // preserved)
  684. EXPECT_EQ(res->body, original);
  685. }
  686. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  687. string chineseCharacters = U8("中国語");
  688. string russianCharacters = U8("дом");
  689. string brazilianCharacters = U8("óculos");
  690. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  691. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  692. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  693. "%D0%B4%D0%BE%D0%BC");
  694. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  695. }
  696. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  697. string unescapedCharacters = "-_.!~*'()";
  698. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  699. }
  700. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  701. string reservedCharacters = ";,/?:@&=+$";
  702. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  703. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  704. }
  705. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  706. string chineseCharacters = U8("中国語");
  707. string russianCharacters = U8("дом");
  708. string brazilianCharacters = U8("óculos");
  709. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  710. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  711. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  712. "%D0%B4%D0%BE%D0%BC");
  713. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  714. }
  715. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  716. // Issue #2082 use case: encoding path component with ampersand
  717. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  718. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  719. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  720. }
  721. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  722. string unescapedCharacters = "-_.!~*'()";
  723. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  724. }
  725. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  726. string reservedCharacters = ";,/?:@&=+$#";
  727. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  728. }
  729. TEST(EncodeUriTest, TestUTF8Characters) {
  730. string chineseCharacters = U8("中国語");
  731. string russianCharacters = U8("дом");
  732. string brazilianCharacters = U8("óculos");
  733. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  734. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  735. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  736. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  737. }
  738. TEST(EncodeUriTest, TestCompleteUri) {
  739. string uri =
  740. "https://example.com/path/to/resource?query=value&param=test#fragment";
  741. EXPECT_EQ(
  742. httplib::encode_uri(uri),
  743. "https://example.com/path/to/resource?query=value&param=test#fragment");
  744. }
  745. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  746. string uri =
  747. "https://example.com/path with spaces/file name.html?q=hello world";
  748. EXPECT_EQ(httplib::encode_uri(uri),
  749. "https://example.com/path%20with%20spaces/"
  750. "file%20name.html?q=hello%20world");
  751. }
  752. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  753. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  754. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  755. }
  756. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  757. string unescapedCharacters = "-_.!~*'()";
  758. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  759. }
  760. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  761. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  762. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  763. string encodedBrazilian = "%C3%B3culos";
  764. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  765. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  767. }
  768. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  769. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  770. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  771. "Piri Tommy Villiers - on & on");
  772. }
  773. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  774. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  775. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  776. }
  777. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  778. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  779. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  780. }
  781. TEST(DecodeUriTest, TestUTF8Characters) {
  782. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  783. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  784. string encodedBrazilian = "%C3%B3culos";
  785. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  786. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  787. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  788. }
  789. TEST(DecodeUriTest, TestCompleteUri) {
  790. string encodedUri = "https://example.com/path%20with%20spaces/"
  791. "file%20name.html?q=hello%20world";
  792. EXPECT_EQ(
  793. httplib::decode_uri(encodedUri),
  794. "https://example.com/path with spaces/file name.html?q=hello world");
  795. }
  796. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  797. string original =
  798. "https://example.com/path with spaces/file name.html?q=hello world";
  799. string encoded = httplib::encode_uri(original);
  800. string decoded = httplib::decode_uri(encoded);
  801. EXPECT_EQ(decoded, original);
  802. }
  803. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  804. // decode_uri is the inverse of encode_uri: an escaped reserved character
  805. // stays encoded so it is not promoted into a real delimiter, while
  806. // non-reserved escapes still decode (like JS decodeURI).
  807. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  808. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  809. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  810. "%3F%3A%40%26%3D%2B%24%2C%3B");
  811. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  812. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  813. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  814. "http://example.com/a%2Fb");
  815. // decode_uri_component still decodes the reserved character.
  816. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  817. }
  818. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  819. string original = "Piri Tommy Villiers - on & on";
  820. string encoded = httplib::encode_uri_component(original);
  821. string decoded = httplib::decode_uri_component(encoded);
  822. EXPECT_EQ(decoded, original);
  823. }
  824. TEST(TrimTests, TrimStringTests) {
  825. EXPECT_EQ("abc", detail::trim_copy("abc"));
  826. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  827. EXPECT_TRUE(detail::trim_copy("").empty());
  828. }
  829. TEST(AsciiTest, LocaleIndependentClassification) {
  830. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  831. // which consult the global C locale: std::isalnum(0xC5) can return true
  832. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  833. // helpers must classify every byte by the ASCII grammar alone.
  834. for (int i = 0; i < 256; i++) {
  835. auto c = static_cast<char>(i);
  836. auto is_digit = i >= '0' && i <= '9';
  837. auto is_upper = i >= 'A' && i <= 'Z';
  838. auto is_lower = i >= 'a' && i <= 'z';
  839. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  840. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  841. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  842. << "byte " << i;
  843. }
  844. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  845. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  846. // Non-ASCII bytes must be percent-encoded, never passed through as
  847. // alphanumeric.
  848. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  849. }
  850. TEST(FromCharsTest, Double) {
  851. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  852. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  853. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  854. auto parse = [](const std::string &s, double &v) {
  855. return detail::from_chars(s.data(), s.data() + s.size(), v);
  856. };
  857. double v = -1.0;
  858. // Representative quality values.
  859. EXPECT_EQ(parse("0", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 0.0);
  861. EXPECT_EQ(parse("1", v).ec, std::errc{});
  862. EXPECT_DOUBLE_EQ(v, 1.0);
  863. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.8);
  865. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 0.001);
  867. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 1.0);
  869. // A missing integer or fractional part is tolerated.
  870. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 0.5);
  872. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 5.0);
  874. // Values outside [0, 1] still parse; the caller range-checks them.
  875. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 123.456);
  877. // Stops at the first byte that is not part of the number and reports where.
  878. std::string trailing = "0.9, text/html";
  879. auto r = parse(trailing, v);
  880. EXPECT_EQ(r.ec, std::errc{});
  881. EXPECT_DOUBLE_EQ(v, 0.9);
  882. EXPECT_EQ(*r.ptr, ',');
  883. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  884. // outright, and an 'e'/'E' simply ends the number.
  885. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  886. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  887. std::string exp_input = "1.5e3";
  888. r = parse(exp_input, v);
  889. EXPECT_EQ(r.ec, std::errc{});
  890. EXPECT_DOUBLE_EQ(v, 1.5);
  891. EXPECT_EQ(*r.ptr, 'e');
  892. // Invalid inputs.
  893. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  898. // Pathological but well-formed inputs must stay bounded (no overflow, no
  899. // out-of-bounds table access) and stay within [0, 1] for the caller.
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  901. std::errc{});
  902. EXPECT_DOUBLE_EQ(v, 0.0);
  903. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  904. std::errc{});
  905. EXPECT_GE(v, 0.0);
  906. EXPECT_LE(v, 1.0);
  907. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  908. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  909. }
  910. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  911. // Simple case without quality values
  912. std::vector<std::string> result1;
  913. EXPECT_TRUE(detail::parse_accept_header(
  914. "text/html,application/json,text/plain", result1));
  915. EXPECT_EQ(result1.size(), 3U);
  916. EXPECT_EQ(result1[0], "text/html");
  917. EXPECT_EQ(result1[1], "application/json");
  918. EXPECT_EQ(result1[2], "text/plain");
  919. // With quality values
  920. std::vector<std::string> result2;
  921. EXPECT_TRUE(detail::parse_accept_header(
  922. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  923. EXPECT_EQ(result2.size(), 3U);
  924. EXPECT_EQ(result2[0], "application/json"); // highest q value
  925. EXPECT_EQ(result2[1], "text/html");
  926. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  927. }
  928. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  929. // Mixed with and without quality values
  930. std::vector<std::string> result;
  931. EXPECT_TRUE(detail::parse_accept_header(
  932. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  933. EXPECT_EQ(result.size(), 3U);
  934. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  935. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  936. EXPECT_EQ(result[2], "application/json"); // q=0.5
  937. }
  938. TEST(ParseAcceptHeaderTest, EdgeCases) {
  939. // Empty header
  940. std::vector<std::string> empty_result;
  941. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  942. EXPECT_TRUE(empty_result.empty());
  943. // Single type
  944. std::vector<std::string> single_result;
  945. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  946. EXPECT_EQ(single_result.size(), 1U);
  947. EXPECT_EQ(single_result[0], "application/json");
  948. // Wildcard types
  949. std::vector<std::string> wildcard_result;
  950. EXPECT_TRUE(detail::parse_accept_header(
  951. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  952. EXPECT_EQ(wildcard_result.size(), 3U);
  953. EXPECT_EQ(wildcard_result[0], "application/json");
  954. EXPECT_EQ(wildcard_result[1], "text/*");
  955. EXPECT_EQ(wildcard_result[2], "*/*");
  956. }
  957. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  958. // Common browser Accept header
  959. std::vector<std::string> browser_result;
  960. EXPECT_TRUE(
  961. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  962. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  963. browser_result));
  964. EXPECT_EQ(browser_result.size(), 6U);
  965. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  970. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  971. // API client header
  972. std::vector<std::string> api_result;
  973. EXPECT_TRUE(detail::parse_accept_header(
  974. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  975. api_result));
  976. EXPECT_EQ(api_result.size(), 3U);
  977. EXPECT_EQ(api_result[0], "application/json");
  978. EXPECT_EQ(api_result[1], "application/xml");
  979. EXPECT_EQ(api_result[2], "text/plain");
  980. }
  981. TEST(ParseAcceptHeaderTest, SpecialCases) {
  982. // Quality value with 3 decimal places
  983. std::vector<std::string> decimal_result;
  984. EXPECT_TRUE(detail::parse_accept_header(
  985. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  986. EXPECT_EQ(decimal_result.size(), 2U);
  987. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  988. EXPECT_EQ(decimal_result[1], "text/html");
  989. // Zero quality (should still be included but with lowest priority)
  990. std::vector<std::string> zero_q_result;
  991. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  992. zero_q_result));
  993. EXPECT_EQ(zero_q_result.size(), 2U);
  994. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  995. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  996. // No spaces around commas
  997. std::vector<std::string> no_space_result;
  998. EXPECT_TRUE(detail::parse_accept_header(
  999. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1000. no_space_result));
  1001. EXPECT_EQ(no_space_result.size(), 3U);
  1002. EXPECT_EQ(no_space_result[0], "text/html");
  1003. EXPECT_EQ(no_space_result[1], "application/json");
  1004. EXPECT_EQ(no_space_result[2], "text/plain");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1007. // Quality values always use '.' as the decimal separator, so parsing must
  1008. // not depend on the process locale. An embedding application may have
  1009. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1010. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1011. std::string saved = cur ? cur : "C";
  1012. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1013. "fr_FR.UTF-8"};
  1014. bool switched = false;
  1015. for (const auto loc : comma_locales) {
  1016. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1017. std::localeconv()->decimal_point[0] == ',') {
  1018. switched = true;
  1019. break;
  1020. }
  1021. }
  1022. if (!switched) {
  1023. std::setlocale(LC_NUMERIC, saved.c_str());
  1024. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1025. }
  1026. // The higher-weighted type appears later in the list, so a correct parse
  1027. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1028. // sensitive parse reads both weights as 0 and leaves the original order.
  1029. std::vector<std::string> result;
  1030. EXPECT_TRUE(detail::parse_accept_header(
  1031. "application/json;q=0.1,text/html;q=0.9", result));
  1032. ASSERT_EQ(result.size(), 2U);
  1033. EXPECT_EQ(result[0], "text/html");
  1034. EXPECT_EQ(result[1], "application/json");
  1035. std::setlocale(LC_NUMERIC, saved.c_str());
  1036. }
  1037. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1038. std::vector<std::string> result;
  1039. // Invalid quality value (> 1.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1042. // Invalid quality value (< 0.0)
  1043. EXPECT_FALSE(
  1044. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1045. // Invalid quality value (not a number)
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=invalid,application/json", result));
  1048. // A valid numeric prefix does not make the entire quality value valid.
  1049. EXPECT_FALSE(detail::parse_accept_header(
  1050. "text/html;q=0.5junk,application/json", result));
  1051. // Empty quality value
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("text/html;q=,application/json", result));
  1054. // Invalid media type format (no slash and not wildcard)
  1055. EXPECT_FALSE(
  1056. detail::parse_accept_header("invalidtype,application/json", result));
  1057. // Valid cases should still work
  1058. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*/*");
  1061. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "*");
  1064. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1065. EXPECT_EQ(result.size(), 1U);
  1066. EXPECT_EQ(result[0], "text/*");
  1067. }
  1068. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1069. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1070. // and must not be answered with 400 Bad Request.
  1071. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1072. struct {
  1073. const char *value;
  1074. std::vector<std::string> expected;
  1075. } cases[] = {
  1076. {",application/json", {"application/json"}},
  1077. {"text/html,", {"text/html"}},
  1078. {"text/html,,*/*", {"text/html", "*/*"}},
  1079. // An empty element may be spelled with whitespace in it
  1080. {"text/html, , application/json", {"text/html", "application/json"}},
  1081. // Nothing but empty elements is an empty list, which means the same
  1082. // thing as no Accept header at all
  1083. {",,,", {}},
  1084. // Quality values still apply across ignored empty elements
  1085. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1086. };
  1087. for (const auto &c : cases) {
  1088. std::vector<std::string> result;
  1089. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1090. << "value: " << c.value;
  1091. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1092. }
  1093. // An invalid entry is still rejected when empty elements surround it
  1094. std::vector<std::string> result;
  1095. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1096. }
  1097. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1098. // or ';' inside one does not end the list element or the parameter. Section
  1099. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1100. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1101. struct {
  1102. const char *value;
  1103. std::vector<std::string> expected;
  1104. } cases[] = {
  1105. {"text/html;profile=\"a,b\",application/json",
  1106. {"text/html", "application/json"}},
  1107. // A "q=" inside a quoted value is not the weight
  1108. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1109. {"text/html", "application/json"}},
  1110. // The weight after a quoted value still applies
  1111. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1112. {"application/json", "text/html"}},
  1113. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1114. {"application/json", "text/html"}},
  1115. {"text/html;profile=\"a\\\"b\",application/json",
  1116. {"text/html", "application/json"}},
  1117. // An escaped backslash does not escape the '"' after it
  1118. {"text/html;profile=\"a\\\\\",application/json",
  1119. {"text/html", "application/json"}},
  1120. };
  1121. for (const auto &c : cases) {
  1122. std::vector<std::string> result;
  1123. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1124. << "value: " << c.value;
  1125. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1126. }
  1127. }
  1128. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1129. Server svr;
  1130. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1131. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1132. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1133. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1134. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1135. res.set_content("ok", "text/plain");
  1136. });
  1137. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1138. EXPECT_TRUE(false);
  1139. res.set_content("bad request", "text/plain");
  1140. });
  1141. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1142. auto se = detail::scope_exit([&] {
  1143. svr.stop();
  1144. listen_thread.join();
  1145. ASSERT_FALSE(svr.is_running());
  1146. });
  1147. svr.wait_until_ready();
  1148. Client cli("localhost", PORT);
  1149. {
  1150. auto res = cli.Get(
  1151. "/accept_ok",
  1152. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1154. EXPECT_EQ(StatusCode::OK_200, res->status);
  1155. }
  1156. {
  1157. auto res = cli.Get("/accept_bad_request",
  1158. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1161. }
  1162. }
  1163. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1164. Server svr;
  1165. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1166. res.set_content("ok", "text/plain");
  1167. });
  1168. std::atomic<int> start_count{0};
  1169. std::atomic<bool> running_when_called{false};
  1170. svr.set_start_handler([&]() {
  1171. running_when_called = svr.is_running();
  1172. start_count++;
  1173. });
  1174. auto port = svr.bind_to_any_port(HOST);
  1175. std::thread t([&]() { svr.listen_after_bind(); });
  1176. auto se = detail::scope_exit([&] {
  1177. svr.stop();
  1178. t.join();
  1179. ASSERT_FALSE(svr.is_running());
  1180. });
  1181. svr.wait_until_ready();
  1182. // A successful request proves the accept loop is running, which the start
  1183. // handler precedes; so by now the handler must have run exactly once.
  1184. Client cli(HOST, port);
  1185. cli.set_connection_timeout(std::chrono::seconds(5));
  1186. auto res = cli.Get("/");
  1187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1188. EXPECT_EQ(StatusCode::OK_200, res->status);
  1189. EXPECT_EQ(1, start_count.load());
  1190. EXPECT_TRUE(running_when_called.load());
  1191. }
  1192. TEST(DivideTest, DivideStringTests) {
  1193. auto divide = [](const std::string &str, char d) {
  1194. std::string lhs;
  1195. std::string rhs;
  1196. detail::divide(str, d,
  1197. [&](const char *lhs_data, std::size_t lhs_size,
  1198. const char *rhs_data, std::size_t rhs_size) {
  1199. lhs.assign(lhs_data, lhs_size);
  1200. rhs.assign(rhs_data, rhs_size);
  1201. });
  1202. return std::make_pair(std::move(lhs), std::move(rhs));
  1203. };
  1204. {
  1205. const auto res = divide("", '=');
  1206. EXPECT_EQ(res.first, "");
  1207. EXPECT_EQ(res.second, "");
  1208. }
  1209. {
  1210. const auto res = divide("=", '=');
  1211. EXPECT_EQ(res.first, "");
  1212. EXPECT_EQ(res.second, "");
  1213. }
  1214. {
  1215. const auto res = divide(" ", '=');
  1216. EXPECT_EQ(res.first, " ");
  1217. EXPECT_EQ(res.second, "");
  1218. }
  1219. {
  1220. const auto res = divide("a", '=');
  1221. EXPECT_EQ(res.first, "a");
  1222. EXPECT_EQ(res.second, "");
  1223. }
  1224. {
  1225. const auto res = divide("a=", '=');
  1226. EXPECT_EQ(res.first, "a");
  1227. EXPECT_EQ(res.second, "");
  1228. }
  1229. {
  1230. const auto res = divide("=b", '=');
  1231. EXPECT_EQ(res.first, "");
  1232. EXPECT_EQ(res.second, "b");
  1233. }
  1234. {
  1235. const auto res = divide("a=b", '=');
  1236. EXPECT_EQ(res.first, "a");
  1237. EXPECT_EQ(res.second, "b");
  1238. }
  1239. {
  1240. const auto res = divide("a=b=", '=');
  1241. EXPECT_EQ(res.first, "a");
  1242. EXPECT_EQ(res.second, "b=");
  1243. }
  1244. {
  1245. const auto res = divide("a=b=c", '=');
  1246. EXPECT_EQ(res.first, "a");
  1247. EXPECT_EQ(res.second, "b=c");
  1248. }
  1249. }
  1250. TEST(SplitTest, ParseQueryString) {
  1251. string s = "key1=val1&key2=val2&key3=val3";
  1252. Params dic;
  1253. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1254. [&](const char *b, const char *e) {
  1255. string key, val;
  1256. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1257. if (key.empty()) {
  1258. key.assign(b2, e2);
  1259. } else {
  1260. val.assign(b2, e2);
  1261. }
  1262. });
  1263. dic.emplace(key, val);
  1264. });
  1265. EXPECT_EQ("val1", dic.find("key1")->second);
  1266. EXPECT_EQ("val2", dic.find("key2")->second);
  1267. EXPECT_EQ("val3", dic.find("key3")->second);
  1268. }
  1269. TEST(SplitTest, ParseInvalidQueryTests) {
  1270. {
  1271. string s = " ";
  1272. Params dict;
  1273. detail::parse_query_text(s, dict);
  1274. EXPECT_TRUE(dict.empty());
  1275. }
  1276. {
  1277. string s = " = =";
  1278. Params dict;
  1279. detail::parse_query_text(s, dict);
  1280. EXPECT_TRUE(dict.empty());
  1281. }
  1282. }
  1283. TEST(ParseQueryTest, ParseQueryString) {
  1284. {
  1285. std::string s = "key1=val1&key2=val2&key3=val3";
  1286. Params dic;
  1287. detail::parse_query_text(s, dic);
  1288. EXPECT_EQ("val1", dic.find("key1")->second);
  1289. EXPECT_EQ("val2", dic.find("key2")->second);
  1290. EXPECT_EQ("val3", dic.find("key3")->second);
  1291. }
  1292. {
  1293. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1294. Params dic;
  1295. detail::parse_query_text(s, dic);
  1296. EXPECT_EQ("", dic.find("key1")->second);
  1297. EXPECT_EQ("val1", dic.find("key2")->second);
  1298. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1299. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1300. }
  1301. }
  1302. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1303. Params dic;
  1304. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1305. dic.emplace("key1", "val1");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1307. dic.emplace("key2", "val2");
  1308. dic.emplace("key3", "val3");
  1309. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1310. }
  1311. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1312. Params params;
  1313. params.emplace("a", "1");
  1314. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1315. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1316. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1317. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1318. // Long enough to overflow the stack when matched with std::regex.
  1319. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1320. EXPECT_EQ("/p?" + long_query + "&a=1",
  1321. append_query_params("/p?" + long_query, params));
  1322. }
  1323. // Joins every entry of a Headers or Params into "key=value " so a whole
  1324. // traversal can be compared in one assertion. Both are instantiations of the
  1325. // same insertion-ordered container, so one helper serves both.
  1326. template <typename Map> static std::string entries_to_string(const Map &m) {
  1327. std::string s;
  1328. for (const auto &entry : m) {
  1329. s += entry.first + "=" + entry.second + " ";
  1330. }
  1331. return s;
  1332. }
  1333. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1334. // Params used to be a std::multimap, which sorted by name and handed the
  1335. // caller's query back alphabetised. A client signing its query string could
  1336. // not reproduce the order it asked for.
  1337. Params dic;
  1338. dic.emplace("zulu", "1");
  1339. dic.emplace("alpha", "2");
  1340. dic.emplace("mike", "3");
  1341. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1342. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1343. }
  1344. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1345. Params dic;
  1346. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1347. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1348. }
  1349. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1350. Request req;
  1351. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1352. req.params);
  1353. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1354. EXPECT_EQ("first", req.get_param_value("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1356. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1357. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1358. EXPECT_EQ("", req.get_param_value("tag", 3));
  1359. }
  1360. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1361. // Params shares its container with Headers, which matches field names
  1362. // case-insensitively. Parameter names must not pick that up.
  1363. Params dic;
  1364. dic.emplace("Key", "upper");
  1365. dic.emplace("key", "lower");
  1366. EXPECT_EQ(2U, dic.size());
  1367. EXPECT_EQ(1U, dic.count("Key"));
  1368. EXPECT_EQ(1U, dic.count("key"));
  1369. EXPECT_EQ("upper", dic.find("Key")->second);
  1370. EXPECT_EQ("lower", dic.find("key")->second);
  1371. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1372. }
  1373. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1374. Server svr;
  1375. std::string order;
  1376. svr.Get("/order", [&](const Request &req, Response &res) {
  1377. order = entries_to_string(req.params);
  1378. res.set_content("ok", "text/plain");
  1379. });
  1380. auto port = svr.bind_to_any_port(HOST);
  1381. thread t = thread([&] { svr.listen_after_bind(); });
  1382. auto se = detail::scope_exit([&] {
  1383. svr.stop();
  1384. t.join();
  1385. ASSERT_FALSE(svr.is_running());
  1386. });
  1387. svr.wait_until_ready();
  1388. Client cli(HOST, port);
  1389. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1390. ASSERT_TRUE(res);
  1391. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1392. }
  1393. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1394. Server svr;
  1395. std::string field_order, file_order;
  1396. svr.Post("/order", [&](const Request &req, Response &res) {
  1397. for (const auto &field : req.form.fields) {
  1398. field_order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. for (const auto &file : req.form.files) {
  1401. file_order += file.first + "=" + file.second.filename + " ";
  1402. }
  1403. res.set_content("ok", "text/plain");
  1404. });
  1405. auto port = svr.bind_to_any_port(HOST);
  1406. thread t = thread([&] { svr.listen_after_bind(); });
  1407. auto se = detail::scope_exit([&] {
  1408. svr.stop();
  1409. t.join();
  1410. ASSERT_FALSE(svr.is_running());
  1411. });
  1412. svr.wait_until_ready();
  1413. UploadFormDataItems items = {
  1414. {"zulu", "1", "", ""},
  1415. {"alpha", "2", "", ""},
  1416. {"mike", "3", "", ""},
  1417. {"zebra", "z", "z.txt", "text/plain"},
  1418. {"apple", "a", "a.txt", "text/plain"},
  1419. };
  1420. Client cli(HOST, port);
  1421. auto res = cli.Post("/order", items);
  1422. ASSERT_TRUE(res);
  1423. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1424. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1425. }
  1426. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1427. Server svr;
  1428. std::vector<std::string> values;
  1429. std::string first, second, out_of_range, order;
  1430. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1431. values = req.form.get_fields("tag");
  1432. first = req.form.get_field("tag", 0);
  1433. second = req.form.get_field("tag", 1);
  1434. out_of_range = req.form.get_field("tag", 2);
  1435. for (const auto &field : req.form.fields) {
  1436. order += field.first + "=" + field.second.content + " ";
  1437. }
  1438. res.set_content("ok", "text/plain");
  1439. });
  1440. auto port = svr.bind_to_any_port(HOST);
  1441. thread t = thread([&] { svr.listen_after_bind(); });
  1442. auto se = detail::scope_exit([&] {
  1443. svr.stop();
  1444. t.join();
  1445. ASSERT_FALSE(svr.is_running());
  1446. });
  1447. svr.wait_until_ready();
  1448. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1449. // not adjacent in the container.
  1450. UploadFormDataItems items = {
  1451. {"tag", "first", "", ""},
  1452. {"other", "x", "", ""},
  1453. {"tag", "second", "", ""},
  1454. };
  1455. Client cli(HOST, port);
  1456. auto res = cli.Post("/repeated", items);
  1457. ASSERT_TRUE(res);
  1458. ASSERT_EQ(2U, values.size());
  1459. EXPECT_EQ("first", values[0]);
  1460. EXPECT_EQ("second", values[1]);
  1461. EXPECT_EQ("first", first);
  1462. EXPECT_EQ("second", second);
  1463. // std::multimap already kept entries sharing a name in insertion order, so
  1464. // everything above passes without this change too. The whole traversal is
  1465. // what tells the two apart: sorting by name would hoist "other" to the front
  1466. // and the two "tag" parts would end up adjacent.
  1467. EXPECT_EQ("tag=first other=x tag=second ", order);
  1468. // Advancing past the last entry of a name used to run off the container;
  1469. // the container's saturating increment makes it return the default instead.
  1470. EXPECT_EQ("", out_of_range);
  1471. }
  1472. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1473. Server svr;
  1474. std::string file_names;
  1475. svr.Post("/upload", [&](const Request &req, Response &res) {
  1476. for (const auto &file : req.form.files) {
  1477. file_names += file.first + "|" + file.second.filename + " ";
  1478. }
  1479. res.set_content("ok", "text/plain");
  1480. });
  1481. auto port = svr.bind_to_any_port(HOST);
  1482. thread t = thread([&] { svr.listen_after_bind(); });
  1483. auto se = detail::scope_exit([&] {
  1484. svr.stop();
  1485. t.join();
  1486. ASSERT_FALSE(svr.is_running());
  1487. });
  1488. svr.wait_until_ready();
  1489. // A trailing backslash would otherwise escape the closing quote.
  1490. UploadFormDataItems items = {
  1491. {"dir\\", "x", "a.txt", "text/plain"},
  1492. {"b", "y", "a\\\\b.txt", "text/plain"},
  1493. };
  1494. Client cli(HOST, port);
  1495. auto res = cli.Post("/upload", items);
  1496. ASSERT_TRUE(res);
  1497. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1498. }
  1499. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1500. // Server::read_content() keeps a FormFields::iterator alive across the
  1501. // content callbacks that fill the part it points at. The container is
  1502. // vector-backed, so a later emplace can reallocate and invalidate an older
  1503. // iterator; 64 parts grow the vector through seven reallocations, which
  1504. // checks that every part's content still lands in its own entry.
  1505. const size_t part_count = 64;
  1506. // One formula for both the parts sent and the values expected back, so the
  1507. // two cannot drift apart.
  1508. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1509. auto content_of = [](size_t i) {
  1510. return std::string(64, static_cast<char>('a' + (i % 26)));
  1511. };
  1512. Server svr;
  1513. std::vector<std::pair<std::string, std::string>> received;
  1514. svr.Post("/many", [&](const Request &req, Response &res) {
  1515. for (const auto &field : req.form.fields) {
  1516. received.emplace_back(field.first, field.second.content);
  1517. }
  1518. res.set_content("ok", "text/plain");
  1519. });
  1520. auto port = svr.bind_to_any_port(HOST);
  1521. thread t = thread([&] { svr.listen_after_bind(); });
  1522. auto se = detail::scope_exit([&] {
  1523. svr.stop();
  1524. t.join();
  1525. ASSERT_FALSE(svr.is_running());
  1526. });
  1527. svr.wait_until_ready();
  1528. UploadFormDataItems items;
  1529. for (size_t i = 0; i < part_count; i++) {
  1530. items.push_back({name_of(i), content_of(i), "", ""});
  1531. }
  1532. Client cli(HOST, port);
  1533. auto res = cli.Post("/many", items);
  1534. ASSERT_TRUE(res);
  1535. ASSERT_EQ(part_count, received.size());
  1536. for (size_t i = 0; i < part_count; i++) {
  1537. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1538. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1539. }
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1542. string content_type = "multipart/form-data; boundary=something";
  1543. string boundary;
  1544. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1545. EXPECT_TRUE(ret);
  1546. EXPECT_EQ(boundary, "something");
  1547. }
  1548. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1549. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1550. string boundary;
  1551. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1552. EXPECT_TRUE(ret);
  1553. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1556. string content_type =
  1557. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1558. string boundary;
  1559. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1562. }
  1563. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1564. string content_type =
  1565. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1566. string boundary;
  1567. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1568. EXPECT_TRUE(ret);
  1569. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1570. }
  1571. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1572. const string boundary(70, 'a');
  1573. string content_type = "multipart/form-data; boundary=" + boundary;
  1574. string parsed;
  1575. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1576. EXPECT_TRUE(ret);
  1577. EXPECT_EQ(parsed, boundary);
  1578. }
  1579. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1580. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1581. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1582. string parsed;
  1583. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1584. EXPECT_FALSE(ret);
  1585. }
  1586. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1587. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1588. // is 72 characters on the wire and still valid.
  1589. const string boundary(70, 'a');
  1590. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1591. string parsed;
  1592. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1593. EXPECT_EQ(parsed, boundary);
  1594. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1595. parsed.clear();
  1596. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1597. }
  1598. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1599. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1600. // The parameter parser must not treat that '=' as the key/value separator.
  1601. string content_type =
  1602. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1603. "charset=UTF-8";
  1604. string parsed;
  1605. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1606. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1607. }
  1608. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1609. // A ';' inside the quoted-string is part of the value, not a parameter
  1610. // separator, so it must not truncate the boundary.
  1611. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1612. string parsed;
  1613. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1614. EXPECT_EQ(parsed, "a;b");
  1615. }
  1616. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1617. string parsed;
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1620. EXPECT_EQ("a\\b", parsed);
  1621. EXPECT_TRUE(detail::parse_multipart_boundary(
  1622. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1623. EXPECT_EQ("a\"b", parsed);
  1624. }
  1625. TEST(ParseDispositionParamsTest, QuotedValues) {
  1626. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1627. // ';' and '=' are ordinary characters inside one.
  1628. struct {
  1629. const char *value;
  1630. std::vector<std::pair<const char *, const char *>> expected;
  1631. } cases[] = {
  1632. {"name=\"file1\"; filename=\"a.txt\"",
  1633. {{"name", "file1"}, {"filename", "a.txt"}}},
  1634. // Whitespace around '=' and ';' is still trimmed
  1635. {"name=\"file2\" ;filename = \"a.html\"",
  1636. {{"name", "file2"}, {"filename", "a.html"}}},
  1637. // '=' inside the value used to leave only the text after the last one
  1638. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1639. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1640. {"name=\"x=y\"", {{"name", "x=y"}}},
  1641. // ';' inside the value used to truncate the pair and leave a bogus one
  1642. {"name=\"file3\"; filename=\"a;b.txt\"",
  1643. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1644. // An unquoted value keeps working, and so does filename*
  1645. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1646. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1647. // A parameter with no key is dropped rather than turned into one whose
  1648. // key is the value
  1649. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1650. // An escaped quote does not end the value
  1651. {"name=\"a\\\"; filename=evil.php\"",
  1652. {{"name", "a\"; filename=evil.php"}}},
  1653. // Other backslashes, as in a Windows path, are kept
  1654. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1655. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1656. };
  1657. for (const auto &c : cases) {
  1658. Params params;
  1659. detail::parse_disposition_params(c.value, params);
  1660. for (const auto &kv : c.expected) {
  1661. auto it = params.find(kv.first);
  1662. ASSERT_NE(it, params.end())
  1663. << "value: " << c.value << ", key: " << kv.first;
  1664. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1665. }
  1666. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1667. }
  1668. }
  1669. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1670. Server svr;
  1671. std::string filename;
  1672. std::string content;
  1673. svr.Post("/upload", [&](const Request &req, Response &) {
  1674. const auto &file = req.form.get_file("file");
  1675. filename = file.filename;
  1676. content = file.content;
  1677. });
  1678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1679. auto se = detail::scope_exit([&] {
  1680. svr.stop();
  1681. thread.join();
  1682. ASSERT_FALSE(svr.is_running());
  1683. });
  1684. svr.wait_until_ready();
  1685. std::string body = "--B\r\n"
  1686. "Content-Disposition: form-data; name=\"file\"; "
  1687. "filename=\"a.txt\"\r\n"
  1688. "Content-Type: text/plain\r\n"
  1689. "\r\n"
  1690. "hello\r\n"
  1691. "--B--\r\n";
  1692. Client cli(HOST, PORT);
  1693. auto res = cli.Post(
  1694. "/upload",
  1695. [&](size_t offset, DataSink &sink) {
  1696. if (offset < body.size()) {
  1697. sink.write(&body[offset], 1);
  1698. } else {
  1699. sink.done();
  1700. }
  1701. return true;
  1702. },
  1703. "multipart/form-data; boundary=B");
  1704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1705. EXPECT_EQ(StatusCode::OK_200, res->status);
  1706. EXPECT_EQ("a.txt", filename);
  1707. EXPECT_EQ("hello", content);
  1708. }
  1709. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1710. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1711. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1712. Server svr;
  1713. std::string field_value, file_name, file_filename;
  1714. bool has_field = false, has_file = false;
  1715. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1716. has_field = req.form.has_field("x=y");
  1717. field_value = req.form.get_field("x=y");
  1718. has_file = req.form.has_file("file1");
  1719. const auto &file = req.form.get_file("file1");
  1720. file_name = file.name;
  1721. file_filename = file.filename;
  1722. res.set_content("ok", "text/plain");
  1723. });
  1724. auto port = svr.bind_to_any_port(HOST);
  1725. thread t = thread([&] { svr.listen_after_bind(); });
  1726. auto se = detail::scope_exit([&] {
  1727. svr.stop();
  1728. t.join();
  1729. ASSERT_FALSE(svr.is_running());
  1730. });
  1731. svr.wait_until_ready();
  1732. UploadFormDataItems items = {
  1733. {"x=y", "field-value", "", ""},
  1734. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1735. };
  1736. Client cli(HOST, port);
  1737. auto res = cli.Post("/quoted", items);
  1738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1739. ASSERT_EQ(StatusCode::OK_200, res->status);
  1740. EXPECT_TRUE(has_field);
  1741. EXPECT_EQ("field-value", field_value);
  1742. EXPECT_TRUE(has_file);
  1743. EXPECT_EQ("file1", file_name);
  1744. EXPECT_EQ("a;b=report.pdf", file_filename);
  1745. }
  1746. TEST(GetHeaderValueTest, DefaultValue) {
  1747. Headers headers = {{"Dummy", "Dummy"}};
  1748. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1749. EXPECT_STREQ("text/plain", val);
  1750. }
  1751. TEST(GetHeaderValueTest, DefaultValueInt) {
  1752. Headers headers = {{"Dummy", "Dummy"}};
  1753. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1754. EXPECT_EQ(100ull, val);
  1755. }
  1756. TEST(GetHeaderValueTest, RegularValue) {
  1757. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1758. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1759. EXPECT_STREQ("text/html", val);
  1760. }
  1761. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1762. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1763. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1764. EXPECT_STREQ("text/html", val);
  1765. }
  1766. TEST(GetHeaderValueTest, SetContent) {
  1767. Response res;
  1768. res.set_content("html", "text/html");
  1769. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1770. res.set_content("text", "text/plain");
  1771. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1772. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1773. }
  1774. TEST(GetHeaderValueTest, RegularValueInt) {
  1775. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1776. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1777. EXPECT_EQ(100ull, val);
  1778. }
  1779. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1780. Headers headers = {{"Content-Length", "x"}};
  1781. auto is_invalid_value = false;
  1782. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1783. is_invalid_value);
  1784. EXPECT_EQ(0ull, val);
  1785. EXPECT_TRUE(is_invalid_value);
  1786. }
  1787. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1788. // An all-digit value that overflows size_t must be reported as invalid, not
  1789. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1790. // a large length to a small one on 32-bit builds, leaving the framing length
  1791. // wrong while is_invalid_value stayed false.
  1792. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1793. auto is_invalid_value = false;
  1794. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1795. is_invalid_value);
  1796. EXPECT_TRUE(is_invalid_value);
  1797. // A well-formed length is unaffected.
  1798. Headers ok = {{"Content-Length", "1234"}};
  1799. is_invalid_value = false;
  1800. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1801. is_invalid_value);
  1802. EXPECT_EQ(1234ull, val);
  1803. EXPECT_FALSE(is_invalid_value);
  1804. }
  1805. TEST(GetHeaderValueTest, Range) {
  1806. {
  1807. Headers headers = {make_range_header({{1, -1}})};
  1808. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1809. EXPECT_STREQ("bytes=1-", val);
  1810. }
  1811. {
  1812. Headers headers = {make_range_header({{-1, 1}})};
  1813. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1814. EXPECT_STREQ("bytes=-1", val);
  1815. }
  1816. {
  1817. Headers headers = {make_range_header({{1, 10}})};
  1818. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1819. EXPECT_STREQ("bytes=1-10", val);
  1820. }
  1821. {
  1822. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1823. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1824. EXPECT_STREQ("bytes=1-10, 100-", val);
  1825. }
  1826. {
  1827. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1828. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1829. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1830. }
  1831. {
  1832. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1833. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1834. EXPECT_STREQ("bytes=0-0, -1", val);
  1835. }
  1836. }
  1837. TEST(BearerTokenAuthTest, SchemeValidation) {
  1838. // A value shorter than "Bearer " must not throw from the fixed-length
  1839. // substr, and a non-Bearer scheme must not be reported as a token.
  1840. struct {
  1841. const char *value;
  1842. const char *expected;
  1843. } cases[] = {
  1844. {"x", ""},
  1845. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1846. {"Bearer abc123", "abc123"},
  1847. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1848. };
  1849. for (const auto &c : cases) {
  1850. Request req;
  1851. req.set_header("Authorization", c.value);
  1852. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1853. }
  1854. }
  1855. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1856. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1857. // to depend on the standard library (libstdc++ handed back duplicates in
  1858. // reverse insertion order, libc++ in insertion order).
  1859. Request req;
  1860. req.set_header("Accept-Encoding", "gzip");
  1861. req.set_header("Accept-Encoding", "deflate");
  1862. req.set_header("Accept-Encoding", "br");
  1863. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1864. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1866. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1867. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1868. }
  1869. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1870. Request req;
  1871. req.set_header("X-Test", "only");
  1872. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1873. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1875. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1876. }
  1877. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1878. Request req;
  1879. req.set_header("X-First", "1");
  1880. req.set_header("X-Test", "2");
  1881. req.params.emplace("first", "1");
  1882. req.params.emplace("test", "2");
  1883. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1884. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1885. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1886. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1887. // The second one is negative when read as a signed value
  1888. const auto max_id = (std::numeric_limits<size_t>::max)();
  1889. for (auto id : {max_id / 2, max_id}) {
  1890. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1891. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1892. EXPECT_EQ("", req.get_param_value("test", id));
  1893. EXPECT_EQ("", req.form.get_field("test", id));
  1894. EXPECT_EQ("", req.form.get_file("test", id).content);
  1895. }
  1896. }
  1897. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1898. Headers headers;
  1899. headers.emplace("Host", "example.com");
  1900. headers.emplace("Accept-Encoding", "gzip");
  1901. headers.emplace("User-Agent", "test");
  1902. headers.emplace("Accept-Encoding", "deflate");
  1903. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1904. "Accept-Encoding=deflate ",
  1905. entries_to_string(headers));
  1906. }
  1907. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1908. Headers headers = {{"Content-Type", "text/html"},
  1909. {"CONTENT-TYPE", "text/xml"}};
  1910. EXPECT_EQ(2U, headers.count("content-type"));
  1911. auto it = headers.find("content-type");
  1912. ASSERT_TRUE(it != headers.end());
  1913. EXPECT_EQ("text/html", it->second);
  1914. }
  1915. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1916. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1917. // drop only those fields and leave everything positioned between them.
  1918. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1919. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1920. auto rng = headers.equal_range("a");
  1921. headers.erase(rng.first, rng.second);
  1922. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1923. }
  1924. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1925. Headers headers = {
  1926. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1927. EXPECT_EQ(3U, headers.erase("A"));
  1928. EXPECT_EQ(0U, headers.count("A"));
  1929. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1930. }
  1931. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1932. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1933. headers.emplace_front("Host", "example.com");
  1934. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1935. entries_to_string(headers));
  1936. }
  1937. TEST(ParseHeaderValueTest, Range) {
  1938. {
  1939. Ranges ranges;
  1940. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1941. EXPECT_TRUE(ret);
  1942. EXPECT_EQ(1u, ranges.size());
  1943. EXPECT_EQ(1u, ranges[0].first);
  1944. EXPECT_EQ(-1, ranges[0].second);
  1945. }
  1946. {
  1947. Ranges ranges;
  1948. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1949. EXPECT_TRUE(ret);
  1950. EXPECT_EQ(1u, ranges.size());
  1951. EXPECT_EQ(-1, ranges[0].first);
  1952. EXPECT_EQ(1u, ranges[0].second);
  1953. }
  1954. {
  1955. Ranges ranges;
  1956. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1957. EXPECT_TRUE(ret);
  1958. EXPECT_EQ(1u, ranges.size());
  1959. EXPECT_EQ(1u, ranges[0].first);
  1960. EXPECT_EQ(10u, ranges[0].second);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1965. EXPECT_FALSE(ret);
  1966. }
  1967. {
  1968. Ranges ranges;
  1969. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1970. EXPECT_TRUE(ret);
  1971. EXPECT_EQ(2u, ranges.size());
  1972. EXPECT_EQ(1u, ranges[0].first);
  1973. EXPECT_EQ(10u, ranges[0].second);
  1974. EXPECT_EQ(100u, ranges[1].first);
  1975. EXPECT_EQ(-1, ranges[1].second);
  1976. }
  1977. {
  1978. Ranges ranges;
  1979. auto ret =
  1980. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1981. EXPECT_TRUE(ret);
  1982. EXPECT_EQ(3u, ranges.size());
  1983. EXPECT_EQ(1u, ranges[0].first);
  1984. EXPECT_EQ(10u, ranges[0].second);
  1985. EXPECT_EQ(100u, ranges[1].first);
  1986. EXPECT_EQ(200u, ranges[1].second);
  1987. EXPECT_EQ(300u, ranges[2].first);
  1988. EXPECT_EQ(400u, ranges[2].second);
  1989. }
  1990. {
  1991. Ranges ranges;
  1992. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1997. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2002. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2003. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2004. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2005. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2006. EXPECT_FALSE(
  2007. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2008. EXPECT_TRUE(ranges.empty());
  2009. }
  2010. {
  2011. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2012. // remainder of the representation, so it stays accepted.
  2013. Ranges ranges;
  2014. auto ret =
  2015. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2016. EXPECT_TRUE(ret);
  2017. ASSERT_EQ(1u, ranges.size());
  2018. EXPECT_EQ(0, ranges[0].first);
  2019. EXPECT_EQ(-1, ranges[0].second);
  2020. }
  2021. // RFC 9110 14.1: range unit names are case-insensitive.
  2022. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2023. Ranges ranges;
  2024. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2025. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2026. }
  2027. }
  2028. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2029. Request req;
  2030. req.set_header("Accept-Encoding", "gzip");
  2031. Response res;
  2032. res.set_header("Content-Type", "text/plain");
  2033. auto ret = detail::encoding_type(req, res);
  2034. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2035. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2036. #else
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. #endif
  2039. }
  2040. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2041. Request req;
  2042. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2043. Response res;
  2044. res.set_header("Content-Type", "text/plain");
  2045. auto ret = detail::encoding_type(req, res);
  2046. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2047. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2048. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2050. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2052. #else
  2053. EXPECT_TRUE(ret == detail::EncodingType::None);
  2054. #endif
  2055. }
  2056. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2057. Request req;
  2058. req.set_header("Accept-Encoding",
  2059. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2060. Response res;
  2061. res.set_header("Content-Type", "text/plain");
  2062. auto ret = detail::encoding_type(req, res);
  2063. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2065. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2066. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2067. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2068. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2069. #else
  2070. EXPECT_TRUE(ret == detail::EncodingType::None);
  2071. #endif
  2072. }
  2073. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2074. // All supported encodings rejected with q=0 should return None
  2075. Request req;
  2076. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2077. Response res;
  2078. res.set_header("Content-Type", "text/plain");
  2079. auto ret = detail::encoding_type(req, res);
  2080. EXPECT_TRUE(ret == detail::EncodingType::None);
  2081. }
  2082. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2083. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2084. Request req;
  2085. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2086. Response res;
  2087. res.set_header("Content-Type", "text/plain");
  2088. auto ret = detail::encoding_type(req, res);
  2089. EXPECT_TRUE(ret == detail::EncodingType::None);
  2090. }
  2091. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2092. Request req;
  2093. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2094. Response res;
  2095. res.set_header("Content-Type", "text/plain");
  2096. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2097. }
  2098. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2099. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2100. Request req;
  2101. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2102. Response res;
  2103. res.set_header("Content-Type", "text/plain");
  2104. auto ret = detail::encoding_type(req, res);
  2105. EXPECT_TRUE(ret == detail::EncodingType::None);
  2106. }
  2107. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2108. // RFC 7231: Accept-Encoding values are case-insensitive
  2109. Request req;
  2110. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2111. Response res;
  2112. res.set_header("Content-Type", "text/plain");
  2113. auto ret = detail::encoding_type(req, res);
  2114. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2115. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2116. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2117. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2118. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2120. #else
  2121. EXPECT_TRUE(ret == detail::EncodingType::None);
  2122. #endif
  2123. }
  2124. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2125. // q value should determine priority, not hardcoded order
  2126. Request req;
  2127. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2128. Response res;
  2129. res.set_header("Content-Type", "text/plain");
  2130. auto ret = detail::encoding_type(req, res);
  2131. // gzip has highest q=1.0, so it should be selected even though
  2132. // br and zstd are also supported
  2133. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2135. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2136. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2137. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2138. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2139. #else
  2140. EXPECT_TRUE(ret == detail::EncodingType::None);
  2141. #endif
  2142. }
  2143. TEST(BufferStreamTest, read) {
  2144. detail::BufferStream strm1;
  2145. Stream &strm = strm1;
  2146. EXPECT_EQ(5, strm.write("hello"));
  2147. char buf[512];
  2148. EXPECT_EQ(2, strm.read(buf, 2));
  2149. EXPECT_EQ('h', buf[0]);
  2150. EXPECT_EQ('e', buf[1]);
  2151. EXPECT_EQ(2, strm.read(buf, 2));
  2152. EXPECT_EQ('l', buf[0]);
  2153. EXPECT_EQ('l', buf[1]);
  2154. EXPECT_EQ(1, strm.read(buf, 1));
  2155. EXPECT_EQ('o', buf[0]);
  2156. EXPECT_EQ(0, strm.read(buf, 1));
  2157. }
  2158. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2159. auto host = "www.httpwatch.com";
  2160. auto ip = hosted_at(host);
  2161. EXPECT_EQ("23.96.13.243", ip);
  2162. std::vector<std::string> addrs;
  2163. hosted_at(host, addrs);
  2164. EXPECT_EQ(1u, addrs.size());
  2165. }
  2166. #if 0 // It depends on each test environment...
  2167. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2168. auto host = "www.youtube.com";
  2169. std::vector<std::string> addrs;
  2170. hosted_at(host, addrs);
  2171. EXPECT_EQ(20u, addrs.size());
  2172. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2173. EXPECT_TRUE(it != addrs.end());
  2174. }
  2175. #endif
  2176. class ChunkedEncodingTest : public ::testing::Test {
  2177. protected:
  2178. ChunkedEncodingTest()
  2179. : cli_(HOST, PORT)
  2180. #ifdef CPPHTTPLIB_SSL_ENABLED
  2181. ,
  2182. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2183. #endif
  2184. {
  2185. cli_.set_connection_timeout(2);
  2186. #ifdef CPPHTTPLIB_SSL_ENABLED
  2187. cli_.enable_server_certificate_verification(false);
  2188. #endif
  2189. }
  2190. virtual void SetUp() {
  2191. read_file("./image.jpg", image_data_);
  2192. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2193. res.set_content("Hello World!", "text/plain");
  2194. });
  2195. svr_.Get(
  2196. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2197. res.set_chunked_content_provider(
  2198. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2199. size_t remaining = image_data_.size() - offset;
  2200. if (remaining == 0) {
  2201. sink.done();
  2202. } else {
  2203. constexpr size_t CHUNK_SIZE = 1024;
  2204. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2205. sink.write(&image_data_[offset], send_size);
  2206. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2207. }
  2208. return true;
  2209. });
  2210. });
  2211. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2212. svr_.wait_until_ready();
  2213. }
  2214. virtual void TearDown() {
  2215. svr_.stop();
  2216. if (!request_threads_.empty()) {
  2217. std::this_thread::sleep_for(std::chrono::seconds(1));
  2218. for (auto &t : request_threads_) {
  2219. t.join();
  2220. }
  2221. }
  2222. t_.join();
  2223. }
  2224. #ifdef CPPHTTPLIB_SSL_ENABLED
  2225. SSLClient cli_;
  2226. SSLServer svr_;
  2227. #else
  2228. Client cli_;
  2229. Server svr_;
  2230. #endif
  2231. thread t_;
  2232. std::vector<thread> request_threads_;
  2233. std::string image_data_;
  2234. };
  2235. TEST_F(ChunkedEncodingTest, NormalGet) {
  2236. auto res = cli_.Get("/chunked");
  2237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2238. std::string out;
  2239. read_file("./image.jpg", out);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. EXPECT_EQ(out, res->body);
  2242. }
  2243. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2244. std::string body;
  2245. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2246. body.append(data, data_length);
  2247. return true;
  2248. });
  2249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2250. std::string out;
  2251. read_file("./image.jpg", out);
  2252. EXPECT_EQ(StatusCode::OK_200, res->status);
  2253. EXPECT_EQ(out, body);
  2254. }
  2255. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2256. std::string body;
  2257. auto res = cli_.Get(
  2258. "/chunked",
  2259. [&](const Response &response) {
  2260. EXPECT_EQ(StatusCode::OK_200, response.status);
  2261. return true;
  2262. },
  2263. [&](const char *data, size_t data_length) {
  2264. body.append(data, data_length);
  2265. return true;
  2266. });
  2267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2268. std::string out;
  2269. read_file("./image.jpg", out);
  2270. EXPECT_EQ(StatusCode::OK_200, res->status);
  2271. EXPECT_EQ(out, body);
  2272. }
  2273. TEST(RangeTest, FromHTTPBin_Online) {
  2274. auto host = "httpbingo.org";
  2275. auto path = std::string{"/range/32"};
  2276. #ifdef CPPHTTPLIB_SSL_ENABLED
  2277. auto port = 443;
  2278. SSLClient cli(host, port);
  2279. #else
  2280. auto port = 80;
  2281. Client cli(host, port);
  2282. #endif
  2283. cli.set_connection_timeout(5);
  2284. {
  2285. auto res = cli.Get(path);
  2286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2287. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2288. EXPECT_EQ(StatusCode::OK_200, res->status);
  2289. }
  2290. {
  2291. Headers headers = {make_range_header({{1, -1}})};
  2292. auto res = cli.Get(path, headers);
  2293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2294. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2295. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2296. }
  2297. {
  2298. Headers headers = {make_range_header({{1, 10}})};
  2299. auto res = cli.Get(path, headers);
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. EXPECT_EQ("bcdefghijk", res->body);
  2302. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2303. }
  2304. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2305. // entire resource, while the original httpbin returned 200. Both are
  2306. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2307. {
  2308. Headers headers = {make_range_header({{0, 31}})};
  2309. auto res = cli.Get(path, headers);
  2310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2311. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2312. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2313. res->status == StatusCode::PartialContent_206);
  2314. }
  2315. {
  2316. Headers headers = {make_range_header({{0, -1}})};
  2317. auto res = cli.Get(path, headers);
  2318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2319. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2320. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2321. res->status == StatusCode::PartialContent_206);
  2322. }
  2323. // go-httpbin returns 206 with clamped range for over-range requests,
  2324. // while the original httpbin returned 416. Both behaviors are observed
  2325. // in real servers, so we only verify the request succeeds.
  2326. {
  2327. Headers headers = {make_range_header({{0, 32}})};
  2328. auto res = cli.Get(path, headers);
  2329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2330. }
  2331. }
  2332. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2333. auto host = "unresolvableaddress.local";
  2334. auto path = std::string{"/"};
  2335. #ifdef CPPHTTPLIB_SSL_ENABLED
  2336. auto port = 443;
  2337. SSLClient cli(host, port);
  2338. #else
  2339. auto port = 80;
  2340. Client cli(host, port);
  2341. #endif
  2342. cli.set_connection_timeout(1);
  2343. {
  2344. auto res = cli.Get(path);
  2345. ASSERT_FALSE(res);
  2346. }
  2347. std::this_thread::sleep_for(std::chrono::seconds(8));
  2348. }
  2349. #if defined(__linux__) && defined(__GLIBC__) && \
  2350. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2351. // Forward declaration: in split builds split.py strips `inline` and moves the
  2352. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2353. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2354. // against the symbol in both header-only and split builds.
  2355. namespace httplib {
  2356. namespace detail {
  2357. int getaddrinfo_with_timeout(const char *node, const char *service,
  2358. const struct addrinfo *hints,
  2359. struct addrinfo **res, time_t timeout_sec);
  2360. } // namespace detail
  2361. } // namespace httplib
  2362. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2363. //
  2364. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2365. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2366. // gai_suspend() call hits the connection timeout the function calls
  2367. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2368. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2369. // still alive and still references the now-destroyed stack frame.
  2370. //
  2371. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2372. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2373. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2374. // and runs them in a container.
  2375. namespace {
  2376. bool should_run_issue_2431_tests() {
  2377. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2378. return v && *v && std::string(v) != "0";
  2379. }
  2380. std::string unique_unresolvable_host(int n) {
  2381. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2382. // glibc still asks the configured nameserver — which is exactly the path
  2383. // we want to exercise. A unique label per call avoids the resolver cache.
  2384. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2385. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2386. std::to_string(n) + ".invalid";
  2387. }
  2388. } // namespace
  2389. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2390. if (!should_run_issue_2431_tests()) {
  2391. GTEST_SKIP()
  2392. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2393. }
  2394. for (int i = 0; i < 8; ++i) {
  2395. struct addrinfo hints;
  2396. memset(&hints, 0, sizeof(hints));
  2397. hints.ai_family = AF_UNSPEC;
  2398. hints.ai_socktype = SOCK_STREAM;
  2399. auto host = unique_unresolvable_host(i);
  2400. struct addrinfo *result = nullptr;
  2401. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2402. &result, /*timeout_sec=*/1);
  2403. if (rc == 0 && result) { freeaddrinfo(result); }
  2404. }
  2405. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2406. // stack region they still believe holds their gaicb.
  2407. std::this_thread::sleep_for(std::chrono::seconds(3));
  2408. }
  2409. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2410. if (!should_run_issue_2431_tests()) {
  2411. GTEST_SKIP()
  2412. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2413. }
  2414. std::atomic<bool> stop{false};
  2415. std::vector<std::thread> threads;
  2416. for (int t = 0; t < 8; ++t) {
  2417. threads.emplace_back([t, &stop] {
  2418. int i = 0;
  2419. while (!stop.load(std::memory_order_relaxed)) {
  2420. struct addrinfo hints;
  2421. memset(&hints, 0, sizeof(hints));
  2422. hints.ai_family = AF_UNSPEC;
  2423. hints.ai_socktype = SOCK_STREAM;
  2424. auto host = unique_unresolvable_host(t * 100000 + i++);
  2425. struct addrinfo *result = nullptr;
  2426. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2427. &result, /*timeout_sec=*/1);
  2428. if (rc == 0 && result) { freeaddrinfo(result); }
  2429. }
  2430. });
  2431. }
  2432. std::this_thread::sleep_for(std::chrono::seconds(8));
  2433. stop.store(true, std::memory_order_relaxed);
  2434. for (auto &th : threads) {
  2435. th.join();
  2436. }
  2437. std::this_thread::sleep_for(std::chrono::seconds(3));
  2438. }
  2439. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2440. if (!should_run_issue_2431_tests()) {
  2441. GTEST_SKIP()
  2442. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2443. }
  2444. std::atomic<bool> stop{false};
  2445. std::vector<std::thread> threads;
  2446. for (int t = 0; t < 8; ++t) {
  2447. threads.emplace_back([t, &stop] {
  2448. int i = 0;
  2449. while (!stop.load(std::memory_order_relaxed)) {
  2450. auto host = unique_unresolvable_host(t * 100000 + i++);
  2451. Client cli(host, 80);
  2452. cli.set_connection_timeout(1, 0);
  2453. cli.set_read_timeout(1, 0);
  2454. cli.set_write_timeout(1, 0);
  2455. (void)cli.Get("/");
  2456. }
  2457. });
  2458. }
  2459. std::this_thread::sleep_for(std::chrono::seconds(8));
  2460. stop.store(true, std::memory_order_relaxed);
  2461. for (auto &th : threads) {
  2462. th.join();
  2463. }
  2464. std::this_thread::sleep_for(std::chrono::seconds(3));
  2465. }
  2466. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2467. TEST(ConnectionErrorTest, InvalidHost) {
  2468. auto host = "-abcde.com";
  2469. #ifdef CPPHTTPLIB_SSL_ENABLED
  2470. auto port = 443;
  2471. SSLClient cli(host, port);
  2472. #else
  2473. auto port = 80;
  2474. Client cli(host, port);
  2475. #endif
  2476. cli.set_connection_timeout(std::chrono::seconds(2));
  2477. auto res = cli.Get("/");
  2478. ASSERT_TRUE(!res);
  2479. EXPECT_EQ(Error::Connection, res.error());
  2480. }
  2481. TEST(ConnectionErrorTest, InvalidHost2) {
  2482. auto host = "httpcan.org/";
  2483. #ifdef CPPHTTPLIB_SSL_ENABLED
  2484. SSLClient cli(host);
  2485. #else
  2486. Client cli(host);
  2487. #endif
  2488. cli.set_connection_timeout(std::chrono::seconds(2));
  2489. auto res = cli.Get("/");
  2490. ASSERT_TRUE(!res);
  2491. EXPECT_EQ(Error::Connection, res.error());
  2492. }
  2493. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2494. auto host = "httpcan.org/";
  2495. #ifdef CPPHTTPLIB_SSL_ENABLED
  2496. SSLClient cli(host);
  2497. #else
  2498. Client cli(host);
  2499. #endif
  2500. cli.set_connection_timeout(std::chrono::seconds(2));
  2501. auto res = cli.Get("/");
  2502. ASSERT_TRUE(!res);
  2503. stringstream s;
  2504. s << "error code: " << res.error();
  2505. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2506. }
  2507. TEST(ConnectionErrorTest, InvalidPort) {
  2508. auto host = "localhost";
  2509. auto port = 44380;
  2510. #ifdef CPPHTTPLIB_SSL_ENABLED
  2511. SSLClient cli(host, port);
  2512. #else
  2513. Client cli(host, port);
  2514. #endif
  2515. cli.set_connection_timeout(std::chrono::seconds(2));
  2516. auto res = cli.Get("/");
  2517. ASSERT_TRUE(!res);
  2518. EXPECT_TRUE(Error::Connection == res.error() ||
  2519. Error::ConnectionTimeout == res.error());
  2520. }
  2521. TEST(ConnectionErrorTest, Timeout_Online) {
  2522. auto host = "google.com";
  2523. #ifdef CPPHTTPLIB_SSL_ENABLED
  2524. auto port = 44380;
  2525. SSLClient cli(host, port);
  2526. #else
  2527. auto port = 8080;
  2528. Client cli(host, port);
  2529. #endif
  2530. cli.set_connection_timeout(std::chrono::seconds(2));
  2531. // only probe one address type so that the error reason
  2532. // correlates to the timed-out IPv4, not the unsupported
  2533. // IPv6 connection attempt
  2534. cli.set_address_family(AF_INET);
  2535. auto res = cli.Get("/");
  2536. ASSERT_TRUE(!res);
  2537. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2538. }
  2539. TEST(CancelTest, NoCancel_Online) {
  2540. auto host = "httpbingo.org";
  2541. auto path = std::string{"/range/32"};
  2542. #ifdef CPPHTTPLIB_SSL_ENABLED
  2543. auto port = 443;
  2544. SSLClient cli(host, port);
  2545. #else
  2546. auto port = 80;
  2547. Client cli(host, port);
  2548. #endif
  2549. cli.set_connection_timeout(std::chrono::seconds(5));
  2550. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2552. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. }
  2555. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2556. // Use /bytes with a large payload so that the DownloadProgress callback
  2557. // (which only fires for Content-Length responses) is invoked before the
  2558. // entire body is received, giving cancellation a chance to fire.
  2559. auto host = "httpbingo.org";
  2560. auto path = std::string{"/bytes/524288"};
  2561. #ifdef CPPHTTPLIB_SSL_ENABLED
  2562. auto port = 443;
  2563. SSLClient cli(host, port);
  2564. #else
  2565. auto port = 80;
  2566. Client cli(host, port);
  2567. #endif
  2568. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2569. cli.set_connection_timeout(std::chrono::seconds(5));
  2570. ASSERT_TRUE(!res);
  2571. EXPECT_EQ(Error::Canceled, res.error());
  2572. }
  2573. TEST(CancelTest, WithCancelLargePayload_Online) {
  2574. auto host = "httpbingo.org";
  2575. auto path = std::string{"/bytes/524288"};
  2576. #ifdef CPPHTTPLIB_SSL_ENABLED
  2577. auto port = 443;
  2578. SSLClient cli(host, port);
  2579. #else
  2580. auto port = 80;
  2581. Client cli(host, port);
  2582. #endif
  2583. cli.set_connection_timeout(std::chrono::seconds(5));
  2584. uint32_t count = 0;
  2585. auto res =
  2586. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2587. ASSERT_TRUE(!res);
  2588. EXPECT_EQ(Error::Canceled, res.error());
  2589. }
  2590. TEST(CancelTest, NoCancelPost) {
  2591. Server svr;
  2592. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2593. res.set_content("Hello World!", "text/plain");
  2594. });
  2595. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2596. auto se = detail::scope_exit([&] {
  2597. svr.stop();
  2598. thread.join();
  2599. ASSERT_FALSE(svr.is_running());
  2600. });
  2601. svr.wait_until_ready();
  2602. Client cli(HOST, PORT);
  2603. cli.set_connection_timeout(std::chrono::seconds(5));
  2604. auto res =
  2605. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2606. "application/json", [](uint64_t, uint64_t) { return true; });
  2607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2608. EXPECT_EQ("Hello World!", res->body);
  2609. EXPECT_EQ(StatusCode::OK_200, res->status);
  2610. }
  2611. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2612. Server svr;
  2613. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2614. res.set_content("Hello World!", "text/plain");
  2615. });
  2616. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2617. auto se = detail::scope_exit([&] {
  2618. svr.stop();
  2619. thread.join();
  2620. ASSERT_FALSE(svr.is_running());
  2621. });
  2622. svr.wait_until_ready();
  2623. Client cli(HOST, PORT);
  2624. cli.set_connection_timeout(std::chrono::seconds(5));
  2625. auto res =
  2626. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2627. "application/json", [](uint64_t, uint64_t) { return false; });
  2628. ASSERT_TRUE(!res);
  2629. EXPECT_EQ(Error::Canceled, res.error());
  2630. }
  2631. TEST(CancelTest, WithCancelLargePayloadPost) {
  2632. Server svr;
  2633. svr.set_payload_max_length(200 * 1024 * 1024);
  2634. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2635. res.set_content(LARGE_DATA, "text/plain");
  2636. });
  2637. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2638. auto se = detail::scope_exit([&] {
  2639. svr.stop();
  2640. thread.join();
  2641. ASSERT_FALSE(svr.is_running());
  2642. });
  2643. svr.wait_until_ready();
  2644. Client cli(HOST, PORT);
  2645. cli.set_payload_max_length(200 * 1024 * 1024);
  2646. cli.set_connection_timeout(std::chrono::seconds(5));
  2647. auto res =
  2648. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2649. "application/json", [](uint64_t, uint64_t) { return false; });
  2650. ASSERT_TRUE(!res);
  2651. EXPECT_EQ(Error::Canceled, res.error());
  2652. }
  2653. TEST(CancelTest, NoCancelPut) {
  2654. Server svr;
  2655. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2656. res.set_content("Hello World!", "text/plain");
  2657. });
  2658. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2659. auto se = detail::scope_exit([&] {
  2660. svr.stop();
  2661. thread.join();
  2662. ASSERT_FALSE(svr.is_running());
  2663. });
  2664. svr.wait_until_ready();
  2665. Client cli(HOST, PORT);
  2666. cli.set_connection_timeout(std::chrono::seconds(5));
  2667. auto res =
  2668. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2669. "application/json", [](uint64_t, uint64_t) { return true; });
  2670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2671. EXPECT_EQ("Hello World!", res->body);
  2672. EXPECT_EQ(StatusCode::OK_200, res->status);
  2673. }
  2674. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2675. Server svr;
  2676. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2677. res.set_content("Hello World!", "text/plain");
  2678. });
  2679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2680. auto se = detail::scope_exit([&] {
  2681. svr.stop();
  2682. thread.join();
  2683. ASSERT_FALSE(svr.is_running());
  2684. });
  2685. svr.wait_until_ready();
  2686. Client cli(HOST, PORT);
  2687. cli.set_connection_timeout(std::chrono::seconds(5));
  2688. auto res =
  2689. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2690. "application/json", [](uint64_t, uint64_t) { return false; });
  2691. ASSERT_TRUE(!res);
  2692. EXPECT_EQ(Error::Canceled, res.error());
  2693. }
  2694. TEST(CancelTest, WithCancelLargePayloadPut) {
  2695. Server svr;
  2696. svr.set_payload_max_length(200 * 1024 * 1024);
  2697. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2698. res.set_content(LARGE_DATA, "text/plain");
  2699. });
  2700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2701. auto se = detail::scope_exit([&] {
  2702. svr.stop();
  2703. thread.join();
  2704. ASSERT_FALSE(svr.is_running());
  2705. });
  2706. svr.wait_until_ready();
  2707. Client cli(HOST, PORT);
  2708. cli.set_payload_max_length(200 * 1024 * 1024);
  2709. cli.set_connection_timeout(std::chrono::seconds(5));
  2710. auto res =
  2711. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2712. "application/json", [](uint64_t, uint64_t) { return false; });
  2713. ASSERT_TRUE(!res);
  2714. EXPECT_EQ(Error::Canceled, res.error());
  2715. }
  2716. TEST(CancelTest, NoCancelPatch) {
  2717. Server svr;
  2718. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2719. res.set_content("Hello World!", "text/plain");
  2720. });
  2721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2722. auto se = detail::scope_exit([&] {
  2723. svr.stop();
  2724. thread.join();
  2725. ASSERT_FALSE(svr.is_running());
  2726. });
  2727. svr.wait_until_ready();
  2728. Client cli(HOST, PORT);
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. auto res =
  2731. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2732. "application/json", [](uint64_t, uint64_t) { return true; });
  2733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2734. EXPECT_EQ("Hello World!", res->body);
  2735. EXPECT_EQ(StatusCode::OK_200, res->status);
  2736. }
  2737. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2738. Server svr;
  2739. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2740. res.set_content("Hello World!", "text/plain");
  2741. });
  2742. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2743. auto se = detail::scope_exit([&] {
  2744. svr.stop();
  2745. thread.join();
  2746. ASSERT_FALSE(svr.is_running());
  2747. });
  2748. svr.wait_until_ready();
  2749. Client cli(HOST, PORT);
  2750. cli.set_connection_timeout(std::chrono::seconds(5));
  2751. auto res =
  2752. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2753. "application/json", [](uint64_t, uint64_t) { return false; });
  2754. ASSERT_TRUE(!res);
  2755. EXPECT_EQ(Error::Canceled, res.error());
  2756. }
  2757. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2758. Server svr;
  2759. svr.set_payload_max_length(200 * 1024 * 1024);
  2760. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2761. res.set_content(LARGE_DATA, "text/plain");
  2762. });
  2763. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2764. auto se = detail::scope_exit([&] {
  2765. svr.stop();
  2766. thread.join();
  2767. ASSERT_FALSE(svr.is_running());
  2768. });
  2769. svr.wait_until_ready();
  2770. Client cli(HOST, PORT);
  2771. cli.set_payload_max_length(200 * 1024 * 1024);
  2772. cli.set_connection_timeout(std::chrono::seconds(5));
  2773. auto res =
  2774. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2775. "application/json", [](uint64_t, uint64_t) { return false; });
  2776. ASSERT_TRUE(!res);
  2777. EXPECT_EQ(Error::Canceled, res.error());
  2778. }
  2779. TEST(CancelTest, NoCancelDelete) {
  2780. Server svr;
  2781. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2782. res.set_content("Hello World!", "text/plain");
  2783. });
  2784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2785. auto se = detail::scope_exit([&] {
  2786. svr.stop();
  2787. thread.join();
  2788. ASSERT_FALSE(svr.is_running());
  2789. });
  2790. svr.wait_until_ready();
  2791. Client cli(HOST, PORT);
  2792. cli.set_connection_timeout(std::chrono::seconds(5));
  2793. auto res =
  2794. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2795. "application/json", [](uint64_t, uint64_t) { return true; });
  2796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2797. EXPECT_EQ("Hello World!", res->body);
  2798. EXPECT_EQ(StatusCode::OK_200, res->status);
  2799. }
  2800. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2801. Server svr;
  2802. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2803. res.set_content("Hello World!", "text/plain");
  2804. });
  2805. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2806. auto se = detail::scope_exit([&] {
  2807. svr.stop();
  2808. thread.join();
  2809. ASSERT_FALSE(svr.is_running());
  2810. });
  2811. svr.wait_until_ready();
  2812. Client cli(HOST, PORT);
  2813. cli.set_connection_timeout(std::chrono::seconds(5));
  2814. auto res =
  2815. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2816. "application/json", [](uint64_t, uint64_t) { return false; });
  2817. ASSERT_TRUE(!res);
  2818. EXPECT_EQ(Error::Canceled, res.error());
  2819. }
  2820. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2821. Server svr;
  2822. svr.set_payload_max_length(200 * 1024 * 1024);
  2823. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2824. res.set_content(LARGE_DATA, "text/plain");
  2825. });
  2826. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2827. auto se = detail::scope_exit([&] {
  2828. svr.stop();
  2829. thread.join();
  2830. ASSERT_FALSE(svr.is_running());
  2831. });
  2832. svr.wait_until_ready();
  2833. Client cli(HOST, PORT);
  2834. cli.set_payload_max_length(200 * 1024 * 1024);
  2835. cli.set_connection_timeout(std::chrono::seconds(5));
  2836. auto res =
  2837. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2838. "application/json", [](uint64_t, uint64_t) { return false; });
  2839. ASSERT_TRUE(!res);
  2840. EXPECT_EQ(Error::Canceled, res.error());
  2841. }
  2842. static std::string remove_whitespace(const std::string &input) {
  2843. std::string output;
  2844. output.reserve(input.size());
  2845. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2846. [](unsigned char c) { return !std::isspace(c); });
  2847. return output;
  2848. }
  2849. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2850. auto host = "httpbingo.org";
  2851. auto path = std::string{"/basic-auth/hello/world"};
  2852. #ifdef CPPHTTPLIB_SSL_ENABLED
  2853. auto port = 443;
  2854. SSLClient cli(host, port);
  2855. #else
  2856. auto port = 80;
  2857. Client cli(host, port);
  2858. #endif
  2859. {
  2860. auto res = cli.Get(path);
  2861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2862. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2863. }
  2864. {
  2865. auto res = cli.Get(
  2866. path, Headers{make_basic_authentication_header("hello", "world")});
  2867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2868. auto body = remove_whitespace(res->body);
  2869. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2870. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2871. EXPECT_EQ(StatusCode::OK_200, res->status);
  2872. }
  2873. {
  2874. cli.set_basic_auth("hello", "world");
  2875. auto res = cli.Get(path);
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. auto body = remove_whitespace(res->body);
  2878. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2879. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2880. EXPECT_EQ(StatusCode::OK_200, res->status);
  2881. }
  2882. {
  2883. cli.set_basic_auth("hello", "bad");
  2884. auto res = cli.Get(path);
  2885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2886. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2887. }
  2888. {
  2889. cli.set_basic_auth("bad", "world");
  2890. auto res = cli.Get(path);
  2891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2892. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2893. }
  2894. }
  2895. #ifdef CPPHTTPLIB_SSL_ENABLED
  2896. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2897. auto host = "httpbingo.org";
  2898. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2899. auto paths = std::vector<std::string>{
  2900. "/digest-auth/auth/hello/world/MD5",
  2901. "/digest-auth/auth/hello/world/SHA-256",
  2902. };
  2903. auto port = 443;
  2904. SSLClient cli(host, port);
  2905. {
  2906. auto res = cli.Get(unauth_path);
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2909. }
  2910. {
  2911. cli.set_digest_auth("hello", "world");
  2912. for (const auto &path : paths) {
  2913. auto res = cli.Get(path.c_str());
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. auto body = remove_whitespace(res->body);
  2916. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2917. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2918. EXPECT_EQ(StatusCode::OK_200, res->status);
  2919. }
  2920. cli.set_digest_auth("hello", "bad");
  2921. for (const auto &path : paths) {
  2922. auto res = cli.Get(path.c_str());
  2923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2924. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2925. }
  2926. }
  2927. }
  2928. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2929. // comma-separated list of challenges, and each challenge may itself carry a
  2930. // comma-separated auth-param list, so a server can legally offer Basic
  2931. // before Digest, either as two field lines or packed into one. Runs one 401
  2932. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2933. // value() joins them in receipt order) and checks that the retry carries a
  2934. // well-formed Digest Authorization header naming expected_realm.
  2935. static void
  2936. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2937. const std::string &expected_realm) {
  2938. std::atomic<int> hits{0};
  2939. Server svr;
  2940. svr.Get("/x", [&](const Request &req, Response &res) {
  2941. if (++hits == 1) {
  2942. res.status = StatusCode::Unauthorized_401;
  2943. for (const auto &challenge : challenges) {
  2944. res.set_header("WWW-Authenticate", challenge);
  2945. }
  2946. } else {
  2947. auto authorization = req.get_header_value("Authorization");
  2948. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2949. EXPECT_NE(std::string::npos,
  2950. authorization.find("realm=\"" + expected_realm + "\""));
  2951. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2952. res.set_content("ok", "text/plain");
  2953. }
  2954. });
  2955. auto port = svr.bind_to_any_port(HOST);
  2956. std::thread t([&]() { svr.listen_after_bind(); });
  2957. auto se = detail::scope_exit([&] {
  2958. svr.stop();
  2959. t.join();
  2960. });
  2961. svr.wait_until_ready();
  2962. Client cli(HOST, port);
  2963. cli.set_digest_auth("hello", "world");
  2964. auto res = cli.Get("/x");
  2965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2966. EXPECT_EQ(2, hits.load());
  2967. }
  2968. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2969. static const char *kDigestChallenge =
  2970. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2971. "algorithm=MD5";
  2972. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2973. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2974. "testrealm");
  2975. }
  2976. // Same challenge list with the schemes in the opposite order, to make sure
  2977. // the fix above didn't just special-case "Basic first".
  2978. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2979. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2980. "testrealm");
  2981. }
  2982. // A comma inside a quoted auth-param value must not be mistaken for the
  2983. // separator between two challenges (or two auth-params).
  2984. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2985. run_digest_challenge_list_test(
  2986. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2987. "algorithm=MD5"},
  2988. "test,realm");
  2989. }
  2990. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2991. // the params and leaves out the fragment.
  2992. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2993. Server svr;
  2994. std::string uri, target;
  2995. svr.Get("/a b", [&](const Request &req, Response &res) {
  2996. auto auth = req.get_header_value("Authorization");
  2997. if (auth.empty()) {
  2998. res.status = StatusCode::Unauthorized_401;
  2999. res.set_header("WWW-Authenticate",
  3000. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3001. return;
  3002. }
  3003. auto b = auth.find("uri=\"") + 5;
  3004. uri = auth.substr(b, auth.find('"', b) - b);
  3005. target = req.target;
  3006. });
  3007. auto port = svr.bind_to_any_port(HOST);
  3008. std::thread t([&]() { svr.listen_after_bind(); });
  3009. auto se = detail::scope_exit([&] {
  3010. svr.stop();
  3011. t.join();
  3012. });
  3013. svr.wait_until_ready();
  3014. Client cli(HOST, port);
  3015. cli.set_digest_auth("hello", "world");
  3016. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3018. EXPECT_EQ("/a%20b?x=1", target);
  3019. EXPECT_EQ(target, uri);
  3020. }
  3021. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3022. // make_digest_authentication_header() dereferences both unconditionally, so
  3023. // a server sending a challenge missing either one must not be treated as
  3024. // usable -- doing so used to crash the client with std::out_of_range.
  3025. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3026. Server svr;
  3027. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3028. res.status = StatusCode::Unauthorized_401;
  3029. res.set_header("WWW-Authenticate", challenge);
  3030. });
  3031. auto port = svr.bind_to_any_port(HOST);
  3032. std::thread t([&]() { svr.listen_after_bind(); });
  3033. auto se = detail::scope_exit([&] {
  3034. svr.stop();
  3035. t.join();
  3036. });
  3037. svr.wait_until_ready();
  3038. Client cli(HOST, port);
  3039. cli.set_digest_auth("hello", "world");
  3040. auto res = cli.Get("/x");
  3041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3042. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3043. }
  3044. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3045. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3046. }
  3047. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3048. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3049. }
  3050. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3051. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3052. }
  3053. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3054. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3055. // when storing the values, so the header builder has to re-escape them (and
  3056. // keep algorithm a bare token); otherwise the value breaks out of its
  3057. // quoted-string and injects extra auth-params into the client's Authorization.
  3058. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3059. std::atomic<int> hits{0};
  3060. std::string authorization;
  3061. Server svr;
  3062. svr.Get("/x", [&](const Request &req, Response &res) {
  3063. if (++hits == 1) {
  3064. res.status = StatusCode::Unauthorized_401;
  3065. // On the wire the quotes embedded in the values are backslash-escaped.
  3066. res.set_header("WWW-Authenticate",
  3067. "Digest realm=\"testrealm\", "
  3068. "nonce=\"n\\\"; injected=\\\"x\", "
  3069. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3070. } else {
  3071. authorization = req.get_header_value("Authorization");
  3072. res.set_content("ok", "text/plain");
  3073. }
  3074. });
  3075. auto port = svr.bind_to_any_port(HOST);
  3076. std::thread t([&]() { svr.listen_after_bind(); });
  3077. auto se = detail::scope_exit([&] {
  3078. svr.stop();
  3079. t.join();
  3080. });
  3081. svr.wait_until_ready();
  3082. Client cli(HOST, port);
  3083. cli.set_digest_auth("hello", "world");
  3084. auto res = cli.Get("/x");
  3085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3086. EXPECT_EQ(2, hits.load());
  3087. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3088. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3089. // inside its quoted-string rather than starting an "injected" auth-param.
  3090. EXPECT_NE(std::string::npos,
  3091. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3092. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3093. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3094. }
  3095. #endif
  3096. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3097. auto host = "google.com";
  3098. auto another_host = "example.com";
  3099. auto wrong_ip = "0.0.0.0";
  3100. #ifdef CPPHTTPLIB_SSL_ENABLED
  3101. SSLClient cli(host);
  3102. #else
  3103. Client cli(host);
  3104. #endif
  3105. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3106. auto res = cli.Get("/");
  3107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3108. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3109. }
  3110. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3111. auto host = "google.com";
  3112. auto wrong_ip = "0.0.0.0";
  3113. #ifdef CPPHTTPLIB_SSL_ENABLED
  3114. SSLClient cli(host);
  3115. #else
  3116. Client cli(host);
  3117. #endif
  3118. cli.set_hostname_addr_map({{host, wrong_ip}});
  3119. auto res = cli.Get("/");
  3120. ASSERT_TRUE(!res);
  3121. EXPECT_EQ(Error::Connection, res.error());
  3122. }
  3123. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3124. // A mapped value that is not an IP literal must be resolved. "localhost"
  3125. // resolves from the hosts file, so this test needs no external DNS.
  3126. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3127. auto host = "target.invalid";
  3128. Server svr;
  3129. std::string received_host;
  3130. svr.Get("/hi", [&](const Request &req, Response &res) {
  3131. received_host = req.get_header_value("Host");
  3132. res.set_content("Hello World!", "text/plain");
  3133. });
  3134. auto port = svr.bind_to_any_port(HOST);
  3135. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3136. auto se = detail::scope_exit([&] {
  3137. svr.stop();
  3138. thread.join();
  3139. ASSERT_FALSE(svr.is_running());
  3140. });
  3141. svr.wait_until_ready();
  3142. Client cli(host, port);
  3143. cli.set_hostname_addr_map({{host, HOST}});
  3144. auto res = cli.Get("/hi");
  3145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3146. EXPECT_EQ(StatusCode::OK_200, res->status);
  3147. // The mapping only redirects the connection; the identity stays host_.
  3148. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3149. }
  3150. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3151. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3152. auto host = "target.invalid";
  3153. Server svr;
  3154. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3155. res.set_content("Hello World!", "text/plain");
  3156. });
  3157. auto port = svr.bind_to_any_port("127.0.0.1");
  3158. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3159. auto se = detail::scope_exit([&] {
  3160. svr.stop();
  3161. thread.join();
  3162. ASSERT_FALSE(svr.is_running());
  3163. });
  3164. svr.wait_until_ready();
  3165. Client cli(host, port);
  3166. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3167. auto res = cli.Get("/hi");
  3168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3169. EXPECT_EQ(StatusCode::OK_200, res->status);
  3170. }
  3171. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3172. // An empty mapped value must leave host_ as the connection target. Without
  3173. // that guard the empty value would become the host argument, getaddrinfo
  3174. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3175. // loopback - silently connecting somewhere the caller never asked for.
  3176. // The server listens on loopback, so such a fallback would succeed and is
  3177. // therefore observable as a failure of this test.
  3178. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3179. Server svr;
  3180. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3181. res.set_content("Hello World!", "text/plain");
  3182. });
  3183. auto port = svr.bind_to_any_port(HOST);
  3184. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3185. auto se = detail::scope_exit([&] {
  3186. svr.stop();
  3187. thread.join();
  3188. ASSERT_FALSE(svr.is_running());
  3189. });
  3190. svr.wait_until_ready();
  3191. Client cli(blackhole, port);
  3192. cli.set_hostname_addr_map({{blackhole, ""}});
  3193. cli.set_connection_timeout(1);
  3194. auto res = cli.Get("/hi");
  3195. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3196. }
  3197. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3198. auto host = "httpbingo.org";
  3199. auto path = std::string{"/absolute-redirect/3"};
  3200. #ifdef CPPHTTPLIB_SSL_ENABLED
  3201. SSLClient cli(host);
  3202. #else
  3203. Client cli(host);
  3204. #endif
  3205. cli.set_follow_location(true);
  3206. auto res = cli.Get(path);
  3207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3208. EXPECT_EQ(StatusCode::OK_200, res->status);
  3209. }
  3210. TEST(RedirectTest, Redirect_Online) {
  3211. auto host = "httpbingo.org";
  3212. auto path = std::string{"/redirect/3"};
  3213. #ifdef CPPHTTPLIB_SSL_ENABLED
  3214. SSLClient cli(host);
  3215. #else
  3216. Client cli(host);
  3217. #endif
  3218. cli.set_follow_location(true);
  3219. auto res = cli.Get(path);
  3220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. }
  3223. TEST(RelativeRedirectTest, Redirect_Online) {
  3224. auto host = "httpbingo.org";
  3225. auto path = std::string{"/relative-redirect/3"};
  3226. #ifdef CPPHTTPLIB_SSL_ENABLED
  3227. SSLClient cli(host);
  3228. #else
  3229. Client cli(host);
  3230. #endif
  3231. cli.set_follow_location(true);
  3232. auto res = cli.Get(path);
  3233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3234. EXPECT_EQ(StatusCode::OK_200, res->status);
  3235. }
  3236. TEST(TooManyRedirectTest, Redirect_Online) {
  3237. auto host = "httpbingo.org";
  3238. auto path = std::string{"/redirect/21"};
  3239. #ifdef CPPHTTPLIB_SSL_ENABLED
  3240. SSLClient cli(host);
  3241. #else
  3242. Client cli(host);
  3243. #endif
  3244. cli.set_follow_location(true);
  3245. auto res = cli.Get(path);
  3246. ASSERT_TRUE(!res);
  3247. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3248. }
  3249. #ifdef CPPHTTPLIB_SSL_ENABLED
  3250. TEST(YahooRedirectTest, Redirect_Online) {
  3251. Client cli("yahoo.com");
  3252. auto res = cli.Get("/");
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3255. cli.set_follow_location(true);
  3256. res = cli.Get("/");
  3257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3258. EXPECT_EQ(StatusCode::OK_200, res->status);
  3259. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3260. }
  3261. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3262. #define REDIR_HOST "httpbingo.org"
  3263. #define REDIR_PATH "/redirect-to"
  3264. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3265. SSLClient cli(REDIR_HOST);
  3266. cli.set_follow_location(true);
  3267. auto res =
  3268. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::OK_200, res->status);
  3271. }
  3272. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3273. SSLClient cli(REDIR_HOST);
  3274. cli.set_follow_location(true);
  3275. Params params;
  3276. params.emplace("url", "http://example.com");
  3277. params.emplace("status_code", "302");
  3278. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. }
  3282. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3283. SSLClient cli(REDIR_HOST);
  3284. cli.set_follow_location(true);
  3285. Params params;
  3286. params.emplace("url", "http://example.com");
  3287. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3289. EXPECT_EQ(StatusCode::OK_200, res->status);
  3290. }
  3291. TEST(UrlWithSpace, Redirect_Online) {
  3292. SSLClient cli("edge.forgecdn.net");
  3293. cli.set_follow_location(true);
  3294. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3298. }
  3299. #endif
  3300. #if !defined(_WIN32) && !defined(_WIN64)
  3301. TEST(ReceiveSignals, Signal) {
  3302. auto setupSignalHandlers = []() {
  3303. struct sigaction act;
  3304. sigemptyset(&act.sa_mask);
  3305. act.sa_flags = SA_SIGINFO;
  3306. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3307. switch (sig) {
  3308. case SIGINT:
  3309. default: break;
  3310. }
  3311. };
  3312. ::sigaction(SIGINT, &act, nullptr);
  3313. };
  3314. Server svr;
  3315. int port = 0;
  3316. auto thread = std::thread([&]() {
  3317. setupSignalHandlers();
  3318. port = svr.bind_to_any_port(HOST);
  3319. svr.listen_after_bind();
  3320. });
  3321. auto se = detail::scope_exit([&] {
  3322. svr.stop();
  3323. thread.join();
  3324. ASSERT_FALSE(svr.is_running());
  3325. });
  3326. svr.wait_until_ready();
  3327. ASSERT_TRUE(svr.is_running());
  3328. pthread_kill(thread.native_handle(), SIGINT);
  3329. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3330. ASSERT_TRUE(svr.is_running());
  3331. }
  3332. #endif
  3333. TEST(RedirectToDifferentPort, Redirect) {
  3334. Server svr1;
  3335. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3336. res.set_content("Hello World!", "text/plain");
  3337. });
  3338. int svr1_port = 0;
  3339. auto thread1 = std::thread([&]() {
  3340. svr1_port = svr1.bind_to_any_port(HOST);
  3341. svr1.listen_after_bind();
  3342. });
  3343. Server svr2;
  3344. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3345. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3346. });
  3347. int svr2_port = 0;
  3348. auto thread2 = std::thread([&]() {
  3349. svr2_port = svr2.bind_to_any_port(HOST);
  3350. svr2.listen_after_bind();
  3351. });
  3352. auto se = detail::scope_exit([&] {
  3353. svr2.stop();
  3354. thread2.join();
  3355. svr1.stop();
  3356. thread1.join();
  3357. ASSERT_FALSE(svr2.is_running());
  3358. ASSERT_FALSE(svr1.is_running());
  3359. });
  3360. svr1.wait_until_ready();
  3361. svr2.wait_until_ready();
  3362. Client cli("localhost", svr2_port);
  3363. cli.set_follow_location(true);
  3364. auto res = cli.Get("/2");
  3365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3366. EXPECT_EQ(StatusCode::OK_200, res->status);
  3367. EXPECT_EQ("Hello World!", res->body);
  3368. }
  3369. // GET /redir on one server redirects to /target on another port, so the
  3370. // client follows it with a new client.
  3371. static Result
  3372. GetThroughRedirectToDifferentPort(Server::Handler target,
  3373. const std::function<void(Client &)> &setup,
  3374. const Headers &headers = Headers()) {
  3375. Server target_svr;
  3376. target_svr.Get("/target", target);
  3377. int target_port = 0;
  3378. auto target_thread = std::thread([&]() {
  3379. target_port = target_svr.bind_to_any_port(HOST);
  3380. target_svr.listen_after_bind();
  3381. });
  3382. Server origin_svr;
  3383. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3384. res.set_redirect(
  3385. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3386. });
  3387. int origin_port = 0;
  3388. auto origin_thread = std::thread([&]() {
  3389. origin_port = origin_svr.bind_to_any_port(HOST);
  3390. origin_svr.listen_after_bind();
  3391. });
  3392. auto se = detail::scope_exit([&] {
  3393. origin_svr.stop();
  3394. origin_thread.join();
  3395. target_svr.stop();
  3396. target_thread.join();
  3397. });
  3398. target_svr.wait_until_ready();
  3399. origin_svr.wait_until_ready();
  3400. Client cli("localhost", origin_port);
  3401. cli.set_follow_location(true);
  3402. setup(cli);
  3403. return cli.Get("/redir", headers);
  3404. }
  3405. static void
  3406. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3407. std::string captured_authorization;
  3408. auto result = GetThroughRedirectToDifferentPort(
  3409. [&](const Request &req, Response &res) {
  3410. captured_authorization = req.get_header_value("Authorization");
  3411. res.set_content("OK", "text/plain");
  3412. },
  3413. set_auth);
  3414. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3415. EXPECT_EQ(StatusCode::OK_200, result->status);
  3416. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3417. EXPECT_TRUE(captured_authorization.empty());
  3418. }
  3419. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3420. TestDoNotForwardCredentialsOnRedirect(
  3421. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3422. }
  3423. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3424. TestDoNotForwardCredentialsOnRedirect(
  3425. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3426. }
  3427. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3428. std::string captured_cookie;
  3429. auto result = GetThroughRedirectToDifferentPort(
  3430. [&](const Request &req, Response &res) {
  3431. captured_cookie = req.get_header_value("Cookie");
  3432. res.set_content("OK", "text/plain");
  3433. },
  3434. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3435. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3436. EXPECT_EQ(StatusCode::OK_200, result->status);
  3437. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3438. EXPECT_TRUE(captured_cookie.empty());
  3439. }
  3440. TEST(RedirectToSamePort, ForwardCookie) {
  3441. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3442. // header so that ordinary session flows keep working.
  3443. Server svr;
  3444. std::string captured_cookie;
  3445. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3446. res.set_redirect("/target", 302);
  3447. });
  3448. svr.Get("/target", [&](const Request &req, Response &res) {
  3449. captured_cookie = req.get_header_value("Cookie");
  3450. res.set_content("OK", "text/plain");
  3451. });
  3452. auto port = svr.bind_to_any_port(HOST);
  3453. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3454. auto se = detail::scope_exit([&] {
  3455. svr.stop();
  3456. thread.join();
  3457. ASSERT_FALSE(svr.is_running());
  3458. });
  3459. svr.wait_until_ready();
  3460. Client cli(HOST, port);
  3461. cli.set_follow_location(true);
  3462. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3463. auto res = cli.Get("/redir", headers);
  3464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3465. EXPECT_EQ(StatusCode::OK_200, res->status);
  3466. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3467. }
  3468. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3469. std::string authorization;
  3470. std::string trace_id;
  3471. auto result = GetThroughRedirectToDifferentPort(
  3472. [&](const Request &req, Response &res) {
  3473. authorization = req.get_header_value("Authorization");
  3474. trace_id = req.get_header_value("X-Trace-Id");
  3475. res.set_content("OK", "text/plain");
  3476. },
  3477. [](Client &cli) {
  3478. cli.set_default_headers(
  3479. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3480. });
  3481. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3482. EXPECT_EQ(StatusCode::OK_200, result->status);
  3483. // Like a header given with the request, a default one goes along unless it
  3484. // carries credentials (RFC 9110 15.4).
  3485. EXPECT_TRUE(authorization.empty());
  3486. EXPECT_EQ("42", trace_id);
  3487. }
  3488. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3489. auto result = GetThroughRedirectToDifferentPort(
  3490. [](const Request &, Response &res) {
  3491. res.set_content(std::string(2048, 'x'), "text/plain");
  3492. },
  3493. [](Client &cli) { cli.set_payload_max_length(1024); });
  3494. EXPECT_FALSE(result);
  3495. }
  3496. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3497. auto result = GetThroughRedirectToDifferentPort(
  3498. [](const Request &req, Response &res) {
  3499. // Answer after a second, or once the client gives up.
  3500. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3501. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3502. }
  3503. res.set_content("late", "text/plain");
  3504. },
  3505. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3506. ASSERT_FALSE(result);
  3507. EXPECT_EQ(Error::Read, result.error());
  3508. }
  3509. #ifdef CPPHTTPLIB_SSL_ENABLED
  3510. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3511. auto result = GetThroughRedirectToDifferentPort(
  3512. [](const Request &, Response &res) {
  3513. res.status = StatusCode::Unauthorized_401;
  3514. res.set_header("WWW-Authenticate",
  3515. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3516. },
  3517. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3518. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3519. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3520. }
  3521. #endif
  3522. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3523. Server svr;
  3524. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3525. // Port number that overflows int — should not crash
  3526. res.set_redirect("http://localhost:99999999999999999999/target");
  3527. });
  3528. auto port = svr.bind_to_any_port(HOST);
  3529. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3530. auto se = detail::scope_exit([&] {
  3531. svr.stop();
  3532. thread.join();
  3533. ASSERT_FALSE(svr.is_running());
  3534. });
  3535. svr.wait_until_ready();
  3536. Client cli(HOST, port);
  3537. cli.set_follow_location(true);
  3538. auto res = cli.Get("/redir");
  3539. // Should fail gracefully, not crash (no valid response due to bad port)
  3540. EXPECT_FALSE(res);
  3541. }
  3542. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3543. Server svr;
  3544. auto port = svr.bind_to_any_port(HOST);
  3545. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3546. // The server's own port followed by junk must not be followed
  3547. res.set_redirect("http://" + std::string(HOST) + ":" +
  3548. std::to_string(port) + "junk/target");
  3549. });
  3550. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3551. res.set_content("target", "text/plain");
  3552. });
  3553. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3554. auto se = detail::scope_exit([&] {
  3555. svr.stop();
  3556. thread.join();
  3557. ASSERT_FALSE(svr.is_running());
  3558. });
  3559. svr.wait_until_ready();
  3560. Client cli(HOST, port);
  3561. cli.set_follow_location(true);
  3562. auto res = cli.Get("/redir");
  3563. EXPECT_FALSE(res);
  3564. }
  3565. TEST(RedirectFromPageWithContent, Redirect) {
  3566. Server svr;
  3567. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3568. res.set_content("___", "text/plain");
  3569. res.set_redirect("/2");
  3570. });
  3571. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3572. res.set_content("Hello World!", "text/plain");
  3573. });
  3574. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3575. auto se = detail::scope_exit([&] {
  3576. svr.stop();
  3577. th.join();
  3578. ASSERT_FALSE(svr.is_running());
  3579. });
  3580. svr.wait_until_ready();
  3581. {
  3582. Client cli("localhost", PORT);
  3583. cli.set_follow_location(true);
  3584. std::string body;
  3585. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3586. body.append(data, data_length);
  3587. return true;
  3588. });
  3589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3590. EXPECT_EQ(StatusCode::OK_200, res->status);
  3591. EXPECT_EQ("Hello World!", body);
  3592. }
  3593. {
  3594. Client cli("localhost", PORT);
  3595. std::string body;
  3596. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3597. body.append(data, data_length);
  3598. return true;
  3599. });
  3600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3601. EXPECT_EQ(StatusCode::Found_302, res->status);
  3602. EXPECT_EQ("___", body);
  3603. }
  3604. }
  3605. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3606. Server svr;
  3607. auto port_str = std::to_string(PORT);
  3608. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3609. auto expected_host = "[::1]:" + port_str;
  3610. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3611. res.set_content("___", "text/plain");
  3612. // res.set_redirect("/2");
  3613. res.set_redirect(redirect_url);
  3614. });
  3615. svr.Get("/2", [&](const Request &req, Response &res) {
  3616. auto host_header = req.headers.find("Host");
  3617. ASSERT_TRUE(host_header != req.headers.end());
  3618. EXPECT_EQ(expected_host, host_header->second);
  3619. res.set_content("Hello World!", "text/plain");
  3620. });
  3621. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3622. auto se = detail::scope_exit([&] {
  3623. svr.stop();
  3624. th.join();
  3625. ASSERT_FALSE(svr.is_running());
  3626. });
  3627. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3628. // actually starts anything, so the condition !svr.is_running() will
  3629. // always remain true, and the loop never stops.
  3630. // This basically counts how many milliseconds have passed since the
  3631. // call to svr.listen(), and if after 5 seconds nothing started yet
  3632. // aborts the test.
  3633. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3634. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3635. ASSERT_LT(milliseconds, 5000U);
  3636. }
  3637. {
  3638. Client cli("::1", PORT);
  3639. cli.set_follow_location(true);
  3640. std::string body;
  3641. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3642. body.append(data, data_length);
  3643. return true;
  3644. });
  3645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3646. EXPECT_EQ(StatusCode::OK_200, res->status);
  3647. EXPECT_EQ("Hello World!", body);
  3648. }
  3649. {
  3650. Client cli("::1", PORT);
  3651. std::string body;
  3652. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3653. body.append(data, data_length);
  3654. return true;
  3655. });
  3656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3657. EXPECT_EQ(StatusCode::Found_302, res->status);
  3658. EXPECT_EQ("___", body);
  3659. }
  3660. }
  3661. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3662. Server svr;
  3663. svr.Get("/foo", [](const Request &req, Response &res) {
  3664. auto a = req.params.find("a");
  3665. if (a != req.params.end()) {
  3666. res.set_content((*a).second, "text/plain");
  3667. res.status = StatusCode::OK_200;
  3668. } else {
  3669. res.status = StatusCode::BadRequest_400;
  3670. }
  3671. });
  3672. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3673. auto se = detail::scope_exit([&] {
  3674. svr.stop();
  3675. thread.join();
  3676. ASSERT_FALSE(svr.is_running());
  3677. });
  3678. svr.wait_until_ready();
  3679. {
  3680. Client cli(HOST, PORT);
  3681. cli.set_path_encode(false);
  3682. auto res = cli.Get("/foo?a=explicitly+encoded");
  3683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3684. EXPECT_EQ(StatusCode::OK_200, res->status);
  3685. // This expects it back with a space, as the `+` won't have been
  3686. // url-encoded, and server-side the params get decoded turning `+`
  3687. // into spaces.
  3688. EXPECT_EQ("explicitly encoded", res->body);
  3689. }
  3690. }
  3691. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3692. // When path encoding is disabled the client must transmit the supplied
  3693. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3694. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3695. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3696. // than a space (0x20). Assert on the raw wire target to catch this.
  3697. Server svr;
  3698. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3699. svr.Get("/foo", [&](const Request &req, Response &res) {
  3700. EXPECT_EQ(expected_target, req.target);
  3701. res.status = StatusCode::OK_200;
  3702. });
  3703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3704. auto se = detail::scope_exit([&] {
  3705. svr.stop();
  3706. thread.join();
  3707. ASSERT_FALSE(svr.is_running());
  3708. });
  3709. svr.wait_until_ready();
  3710. {
  3711. Client cli(HOST, PORT);
  3712. cli.set_path_encode(false);
  3713. auto res = cli.Get(expected_target.c_str());
  3714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3715. EXPECT_EQ(StatusCode::OK_200, res->status);
  3716. }
  3717. }
  3718. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3719. // `open_stream()` used to skip the path encoding that the buffered send
  3720. // path applies, so the same `path` produced different bytes in the request
  3721. // line depending on which API was used. Assert the two agree.
  3722. Server svr;
  3723. std::string target;
  3724. svr.Get(".*", [&](const Request &req, Response &res) {
  3725. target = req.target;
  3726. res.status = StatusCode::OK_200;
  3727. });
  3728. auto port = svr.bind_to_any_port(HOST);
  3729. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3730. auto se = detail::scope_exit([&] {
  3731. svr.stop();
  3732. thread.join();
  3733. ASSERT_FALSE(svr.is_running());
  3734. });
  3735. svr.wait_until_ready();
  3736. struct {
  3737. const char *path;
  3738. const char *expected;
  3739. } cases[] = {
  3740. {"/a b?x=1", "/a%20b?x=1"},
  3741. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3742. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3743. };
  3744. for (const auto &c : cases) {
  3745. Client cli(HOST, port);
  3746. target.clear();
  3747. auto res = cli.Get(c.path);
  3748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3749. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3750. auto buffered_target = target;
  3751. target.clear();
  3752. auto handle = cli.open_stream("GET", c.path);
  3753. EXPECT_TRUE(handle.is_valid())
  3754. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3755. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3756. }
  3757. }
  3758. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3759. // The `set_path_encode(false)` contract — transmit the supplied target
  3760. // verbatim — must hold for the streaming API too.
  3761. Server svr;
  3762. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3763. std::string target;
  3764. svr.Get("/foo", [&](const Request &req, Response &res) {
  3765. target = req.target;
  3766. res.status = StatusCode::OK_200;
  3767. });
  3768. auto port = svr.bind_to_any_port(HOST);
  3769. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3770. auto se = detail::scope_exit([&] {
  3771. svr.stop();
  3772. thread.join();
  3773. ASSERT_FALSE(svr.is_running());
  3774. });
  3775. svr.wait_until_ready();
  3776. {
  3777. Client cli(HOST, port);
  3778. cli.set_path_encode(false);
  3779. auto handle = cli.open_stream("GET", expected_target);
  3780. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3781. EXPECT_EQ(expected_target, target);
  3782. }
  3783. }
  3784. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3785. // With path encoding enabled a CR/LF in the target is percent-encoded
  3786. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3787. // write_request_line still backstops `set_path_encode(false)`, which is
  3788. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3789. Server svr;
  3790. // Captured before routing: the decoded path contains a newline, which a
  3791. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3792. std::string target;
  3793. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3794. target = req.target;
  3795. res.status = StatusCode::OK_200;
  3796. return Server::HandlerResponse::Handled;
  3797. });
  3798. auto port = svr.bind_to_any_port(HOST);
  3799. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3800. auto se = detail::scope_exit([&] {
  3801. svr.stop();
  3802. thread.join();
  3803. ASSERT_FALSE(svr.is_running());
  3804. });
  3805. svr.wait_until_ready();
  3806. {
  3807. Client cli(HOST, port);
  3808. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3809. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3810. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3811. }
  3812. }
  3813. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3814. // Every control character is percent-encoded, not just CR/LF, so the target
  3815. // passes the request-target check in write_request_line.
  3816. Server svr;
  3817. std::string target;
  3818. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3819. target = req.target;
  3820. res.status = StatusCode::OK_200;
  3821. return Server::HandlerResponse::Handled;
  3822. });
  3823. auto port = svr.bind_to_any_port(HOST);
  3824. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3825. auto se = detail::scope_exit([&] {
  3826. svr.stop();
  3827. thread.join();
  3828. ASSERT_FALSE(svr.is_running());
  3829. });
  3830. svr.wait_until_ready();
  3831. {
  3832. Client cli(HOST, port);
  3833. auto res = cli.Get("/a\tb\x1b\x7f");
  3834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3835. EXPECT_EQ("/a%09b%1B%7F", target);
  3836. }
  3837. }
  3838. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3839. // Nothing may reach the wire: a raw CR/LF target would split the request
  3840. // line and inject headers.
  3841. Server svr;
  3842. // Pre-routing so that "not called" means nothing reached the server at all,
  3843. // rather than merely failing to match a handler pattern.
  3844. auto handler_called = false;
  3845. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3846. handler_called = true;
  3847. res.status = StatusCode::OK_200;
  3848. return Server::HandlerResponse::Handled;
  3849. });
  3850. auto port = svr.bind_to_any_port(HOST);
  3851. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3852. auto se = detail::scope_exit([&] {
  3853. svr.stop();
  3854. thread.join();
  3855. ASSERT_FALSE(svr.is_running());
  3856. });
  3857. svr.wait_until_ready();
  3858. {
  3859. Client cli(HOST, port);
  3860. cli.set_path_encode(false);
  3861. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3862. EXPECT_FALSE(handle.is_valid());
  3863. EXPECT_EQ(Error::Write, handle.error);
  3864. EXPECT_FALSE(handler_called);
  3865. }
  3866. }
  3867. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3868. // Which of the two branches runs is decided by whether the query component
  3869. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3870. // an empty query and must still fall back to building one from
  3871. // `req.params`, while a non-empty query must win over `req.params`.
  3872. Server svr;
  3873. std::string target;
  3874. svr.Get("/foo", [&](const Request &req, Response &res) {
  3875. target = req.target;
  3876. res.status = StatusCode::OK_200;
  3877. });
  3878. auto port = svr.bind_to_any_port(HOST);
  3879. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3880. auto se = detail::scope_exit([&] {
  3881. svr.stop();
  3882. thread.join();
  3883. ASSERT_FALSE(svr.is_running());
  3884. });
  3885. svr.wait_until_ready();
  3886. {
  3887. // Trailing `?` -> empty query component -> `req.params` is used.
  3888. Client cli(HOST, port);
  3889. Request req;
  3890. req.method = "GET";
  3891. req.path = "/foo?";
  3892. req.params.emplace("a", "1");
  3893. target.clear();
  3894. auto res = cli.send(req);
  3895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3896. EXPECT_EQ("/foo?a=1", target);
  3897. }
  3898. {
  3899. // Non-empty query in `req.path` -> `req.params` is not appended.
  3900. Client cli(HOST, port);
  3901. Request req;
  3902. req.method = "GET";
  3903. req.path = "/foo?b=2";
  3904. req.params.emplace("a", "1");
  3905. target.clear();
  3906. auto res = cli.send(req);
  3907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3908. EXPECT_EQ("/foo?b=2", target);
  3909. }
  3910. }
  3911. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3912. Server svr;
  3913. svr.Get("/", [](const Request &req, Response &) {
  3914. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3915. });
  3916. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3917. auto se = detail::scope_exit([&] {
  3918. svr.stop();
  3919. thread.join();
  3920. ASSERT_FALSE(svr.is_running());
  3921. });
  3922. svr.wait_until_ready();
  3923. {
  3924. Client cli(HOST, PORT);
  3925. cli.set_path_encode(false);
  3926. auto res = cli.Get("/?something=%0A");
  3927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3928. EXPECT_EQ(StatusCode::OK_200, res->status);
  3929. }
  3930. }
  3931. TEST(BindServerTest, BindDualStack) {
  3932. Server svr;
  3933. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3934. res.set_content("Hello World!", "text/plain");
  3935. });
  3936. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3937. auto se = detail::scope_exit([&] {
  3938. svr.stop();
  3939. thread.join();
  3940. ASSERT_FALSE(svr.is_running());
  3941. });
  3942. svr.wait_until_ready();
  3943. {
  3944. Client cli("127.0.0.1", PORT);
  3945. auto res = cli.Get("/1");
  3946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3947. EXPECT_EQ(StatusCode::OK_200, res->status);
  3948. EXPECT_EQ("Hello World!", res->body);
  3949. }
  3950. {
  3951. Client cli("::1", PORT);
  3952. auto res = cli.Get("/1");
  3953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3954. EXPECT_EQ(StatusCode::OK_200, res->status);
  3955. EXPECT_EQ("Hello World!", res->body);
  3956. }
  3957. }
  3958. TEST(BindServerTest, BindAndListenSeparately) {
  3959. Server svr;
  3960. int port = svr.bind_to_any_port("0.0.0.0");
  3961. ASSERT_TRUE(svr.is_valid());
  3962. ASSERT_TRUE(port > 0);
  3963. svr.stop();
  3964. }
  3965. // Reports whether anything is still listening on a loopback port. A plain
  3966. // connect() is used instead of a Client request because a socket left bound by
  3967. // mistake accepts the connection into its backlog and never answers, which
  3968. // would hang the test instead of failing it.
  3969. static bool is_loopback_port_accepting(int port) {
  3970. sockaddr_in addr{};
  3971. addr.sin_family = AF_INET;
  3972. addr.sin_port = htons(static_cast<uint16_t>(port));
  3973. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3974. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3975. EXPECT_NE(sock, INVALID_SOCKET);
  3976. if (sock == INVALID_SOCKET) { return false; }
  3977. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3978. static_cast<socklen_t>(sizeof(addr)));
  3979. detail::close_socket(sock);
  3980. return ret == 0;
  3981. }
  3982. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3983. Server svr;
  3984. auto port = svr.bind_to_any_port("127.0.0.1");
  3985. ASSERT_TRUE(port > 0);
  3986. svr.stop();
  3987. // bind_to_any_port() already called listen(2), so until stop() closed the
  3988. // descriptor the port kept accepting connections into the backlog. ASSERT
  3989. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3990. // below blocks forever in the accept loop.
  3991. ASSERT_FALSE(is_loopback_port_accepting(port));
  3992. // Nothing is left to accept on, so listen_after_bind() must report failure
  3993. // instead of returning success without ever serving.
  3994. EXPECT_FALSE(svr.listen_after_bind());
  3995. // The failed listen marks the server decommissioned, so a waiter returns
  3996. // instead of spinning forever.
  3997. svr.wait_until_ready();
  3998. }
  3999. #ifdef CPPHTTPLIB_SSL_ENABLED
  4000. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4001. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4002. CLIENT_CA_CERT_DIR);
  4003. int port = svr.bind_to_any_port("0.0.0.0");
  4004. ASSERT_TRUE(svr.is_valid());
  4005. ASSERT_TRUE(port > 0);
  4006. svr.stop();
  4007. }
  4008. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4009. // or a rejected CustomRoute() registration would not stop the server binding.
  4010. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4012. CLIENT_CA_CERT_DIR);
  4013. ASSERT_TRUE(svr.is_valid());
  4014. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4015. EXPECT_FALSE(svr.is_valid());
  4016. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4017. }
  4018. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4019. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4020. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4021. int port = svr.bind_to_any_port("0.0.0.0");
  4022. ASSERT_TRUE(svr.is_valid());
  4023. ASSERT_TRUE(port > 0);
  4024. svr.stop();
  4025. }
  4026. TEST(BindServerTest, UpdateCertsPem) {
  4027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4028. int port = svr.bind_to_any_port("0.0.0.0");
  4029. ASSERT_TRUE(svr.is_valid());
  4030. ASSERT_TRUE(port > 0);
  4031. // Read PEM files
  4032. std::string cert_pem, key_pem, ca_pem;
  4033. read_file(SERVER_CERT_FILE, cert_pem);
  4034. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4035. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4036. // Update server certificates using PEM API
  4037. ASSERT_TRUE(
  4038. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4039. ASSERT_TRUE(svr.is_valid());
  4040. svr.stop();
  4041. }
  4042. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4043. // Start server with client CA (enables client auth)
  4044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4045. ASSERT_TRUE(svr.is_valid());
  4046. bool handler_called = false;
  4047. svr.Get("/test", [&](const Request &req, Response &res) {
  4048. handler_called = true;
  4049. // Verify client certificate is present
  4050. auto cert = req.peer_cert();
  4051. EXPECT_TRUE(static_cast<bool>(cert));
  4052. res.set_content("ok", "text/plain");
  4053. });
  4054. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4055. auto se = detail::scope_exit([&] {
  4056. svr.stop();
  4057. t.join();
  4058. ASSERT_FALSE(svr.is_running());
  4059. });
  4060. svr.wait_until_ready();
  4061. // Read PEM files
  4062. std::string cert_pem, key_pem, ca_pem;
  4063. read_file(SERVER_CERT_FILE, cert_pem);
  4064. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4065. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4066. // Update server certificates and client CA using PEM API while server running
  4067. ASSERT_TRUE(
  4068. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4069. // Connect with client certificate
  4070. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4071. cli.enable_server_certificate_verification(false);
  4072. cli.set_connection_timeout(30);
  4073. auto res = cli.Get("/test");
  4074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4075. ASSERT_EQ(StatusCode::OK_200, res->status);
  4076. ASSERT_TRUE(handler_called);
  4077. EXPECT_EQ("ok", res->body);
  4078. }
  4079. // Puts a CA that did not sign the client's certificate in the old one's place.
  4080. static bool replace_client_ca(SSLServer &svr) {
  4081. std::string cert_pem, key_pem, ca_pem;
  4082. read_file(SERVER_CERT_FILE, cert_pem);
  4083. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4084. read_file(SERVER_CERT2_FILE, ca_pem);
  4085. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4086. ca_pem.c_str());
  4087. }
  4088. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4089. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4090. ASSERT_TRUE(svr.is_valid());
  4091. svr.Get("/test", [](const Request &, Response &res) {
  4092. res.set_content("ok", "text/plain");
  4093. });
  4094. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4095. auto se = detail::scope_exit([&] {
  4096. svr.stop();
  4097. t.join();
  4098. ASSERT_FALSE(svr.is_running());
  4099. });
  4100. svr.wait_until_ready();
  4101. auto get = [] {
  4102. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4103. cli.enable_server_certificate_verification(false);
  4104. return cli.Get("/test");
  4105. };
  4106. ASSERT_TRUE(get());
  4107. ASSERT_TRUE(replace_client_ca(svr));
  4108. EXPECT_FALSE(get());
  4109. }
  4110. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4111. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4113. ASSERT_TRUE(svr.is_valid());
  4114. tls::set_verify_callback(svr.tls_context(),
  4115. [](const tls::VerifyContext &) -> bool {
  4116. throw std::runtime_error("verify");
  4117. });
  4118. svr.Get("/test", [](const Request &, Response &res) {
  4119. res.set_content("ok", "text/plain");
  4120. });
  4121. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4122. auto se = detail::scope_exit([&] {
  4123. svr.stop();
  4124. t.join();
  4125. ASSERT_FALSE(svr.is_running());
  4126. });
  4127. svr.wait_until_ready();
  4128. auto get = [] {
  4129. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4130. cli.enable_server_certificate_verification(false);
  4131. return cli.Get("/test");
  4132. };
  4133. EXPECT_FALSE(get());
  4134. // The handshake is over, so an update does not wait for it.
  4135. std::string cert_pem, key_pem;
  4136. read_file(SERVER_CERT_FILE, cert_pem);
  4137. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4138. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4139. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4140. return v.preverify_ok;
  4141. });
  4142. auto res = get();
  4143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4144. EXPECT_EQ("ok", res->body);
  4145. }
  4146. #endif
  4147. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4148. // Sends each request over a new connection with a client certificate,
  4149. // resuming the session of the one before when there is one.
  4150. class ResumingClient {
  4151. public:
  4152. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4153. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4154. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4155. SSL_FILETYPE_PEM);
  4156. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4157. // callback, not through SSL_get1_session().
  4158. SSL_CTX_set_app_data(ctx_, this);
  4159. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4160. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4161. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4162. auto self = static_cast<ResumingClient *>(
  4163. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4164. SSL_SESSION_free(self->session_);
  4165. self->session_ = session;
  4166. return 1; // Keeps the reference
  4167. });
  4168. }
  4169. ~ResumingClient() {
  4170. SSL_SESSION_free(session_);
  4171. SSL_CTX_free(ctx_);
  4172. }
  4173. // Tells whether the request was answered.
  4174. bool get() {
  4175. auto error = Error::Success;
  4176. auto sock = detail::create_client_socket(
  4177. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4178. /*connection_timeout_sec=*/5, 0,
  4179. /*read_timeout_sec=*/5, 0,
  4180. /*write_timeout_sec=*/5, 0, std::string(), error);
  4181. if (sock == INVALID_SOCKET) { return false; }
  4182. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4183. auto ssl = SSL_new(ctx_);
  4184. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4185. SSL_set_fd(ssl, static_cast<int>(sock));
  4186. if (session_) { SSL_set_session(ssl, session_); }
  4187. if (SSL_connect(ssl) != 1) { return false; }
  4188. reused_ = SSL_session_reused(ssl) == 1;
  4189. // Reading the response also takes in a TLS 1.3 session ticket.
  4190. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4191. "Connection: close\r\n\r\n";
  4192. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4193. std::string res;
  4194. char buf[256];
  4195. int n;
  4196. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4197. res.append(buf, static_cast<size_t>(n));
  4198. }
  4199. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4200. SSL_shutdown(ssl);
  4201. return res.find("200 OK") != std::string::npos;
  4202. }
  4203. // Whether the last connection resumed a session
  4204. bool reused() const { return reused_; }
  4205. private:
  4206. SSL_CTX *ctx_;
  4207. SSL_SESSION *session_ = nullptr;
  4208. bool reused_ = false;
  4209. };
  4210. // A client that resumes its session gets through, but not once the client CA
  4211. // has changed, as a resumed session does not show the certificate again.
  4212. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4213. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4214. ASSERT_TRUE(svr.is_valid());
  4215. svr.Get("/test", [](const Request &, Response &res) {
  4216. res.set_content("ok", "text/plain");
  4217. });
  4218. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4219. auto se = detail::scope_exit([&] {
  4220. svr.stop();
  4221. t.join();
  4222. ASSERT_FALSE(svr.is_running());
  4223. });
  4224. svr.wait_until_ready();
  4225. ResumingClient cli;
  4226. ASSERT_TRUE(cli.get());
  4227. ASSERT_TRUE(cli.get());
  4228. EXPECT_TRUE(cli.reused());
  4229. ASSERT_TRUE(replace_client_ca(svr));
  4230. EXPECT_FALSE(cli.get());
  4231. }
  4232. // A resumed session does not show the certificate again, so the server does
  4233. // not resume one with a verify callback to run on it.
  4234. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4236. ASSERT_TRUE(svr.is_valid());
  4237. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4238. return v.preverify_ok;
  4239. });
  4240. svr.Get("/test", [](const Request &, Response &res) {
  4241. res.set_content("ok", "text/plain");
  4242. });
  4243. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4244. auto se = detail::scope_exit([&] {
  4245. svr.stop();
  4246. t.join();
  4247. ASSERT_FALSE(svr.is_running());
  4248. });
  4249. svr.wait_until_ready();
  4250. ResumingClient cli;
  4251. ASSERT_TRUE(cli.get());
  4252. ASSERT_TRUE(cli.get());
  4253. EXPECT_FALSE(cli.reused());
  4254. }
  4255. #endif
  4256. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4257. // wolfSSL shares its session cache between contexts, so a resumed session
  4258. // could carry a client certificate checked against another server's CA, or
  4259. // against a client CA since replaced.
  4260. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4261. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4262. ASSERT_TRUE(svr.is_valid());
  4263. // Trusts a CA that did not sign the client's certificate.
  4264. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4265. ASSERT_TRUE(other.is_valid());
  4266. for (auto s : {&svr, &other}) {
  4267. s->Get("/test", [](const Request &, Response &res) {
  4268. res.set_content("ok", "text/plain");
  4269. });
  4270. }
  4271. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4272. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4273. auto se = detail::scope_exit([&] {
  4274. other.stop();
  4275. svr.stop();
  4276. t2.join();
  4277. t.join();
  4278. });
  4279. svr.wait_until_ready();
  4280. other.wait_until_ready();
  4281. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4282. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4283. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4284. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4285. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4286. ASSERT_EQ(WOLFSSL_SUCCESS,
  4287. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4288. WOLFSSL_FILETYPE_PEM));
  4289. WOLFSSL_SESSION *session = nullptr;
  4290. auto session_se = detail::scope_exit([&] {
  4291. if (session) { wolfSSL_SESSION_free(session); }
  4292. });
  4293. // A request over a new connection, resuming `session` when there is one and
  4294. // keeping the connection's own in its place. Tells whether it was answered.
  4295. auto get = [&](int port) {
  4296. auto error = Error::Success;
  4297. auto sock = detail::create_client_socket(
  4298. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4299. /*connection_timeout_sec=*/5, 0,
  4300. /*read_timeout_sec=*/5, 0,
  4301. /*write_timeout_sec=*/5, 0, std::string(), error);
  4302. if (sock == INVALID_SOCKET) { return false; }
  4303. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4304. auto ssl = wolfSSL_new(ctx);
  4305. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4306. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4307. if (session) { wolfSSL_set_session(ssl, session); }
  4308. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4309. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4310. "Connection: close\r\n\r\n";
  4311. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4312. std::string res;
  4313. char buf[256];
  4314. int n;
  4315. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4316. res.append(buf, static_cast<size_t>(n));
  4317. }
  4318. wolfSSL_shutdown(ssl);
  4319. if (session) { wolfSSL_SESSION_free(session); }
  4320. session = wolfSSL_get1_session(ssl);
  4321. return res.find("200 OK") != std::string::npos;
  4322. };
  4323. ASSERT_TRUE(get(PORT));
  4324. EXPECT_FALSE(get(PORT + 1));
  4325. ASSERT_TRUE(get(PORT));
  4326. ASSERT_TRUE(replace_client_ca(svr));
  4327. EXPECT_FALSE(get(PORT));
  4328. }
  4329. #endif
  4330. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4331. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4332. ASSERT_TRUE(svr.is_valid());
  4333. svr.Get("/test", [](const Request &, Response &res) {
  4334. res.set_content("ok", "text/plain");
  4335. });
  4336. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4337. auto se = detail::scope_exit([&] {
  4338. svr.stop();
  4339. t.join();
  4340. ASSERT_FALSE(svr.is_running());
  4341. });
  4342. svr.wait_until_ready();
  4343. // A connection that sends no ClientHello keeps its handshake in progress,
  4344. // once the server has had a moment to start it.
  4345. auto error = Error::Success;
  4346. auto sock = detail::create_client_socket(
  4347. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4348. /*connection_timeout_sec=*/5, 0,
  4349. /*read_timeout_sec=*/5, 0,
  4350. /*write_timeout_sec=*/5, 0, std::string(), error);
  4351. ASSERT_NE(INVALID_SOCKET, sock);
  4352. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4353. std::string cert_pem, key_pem;
  4354. read_file(SERVER_CERT_FILE, cert_pem);
  4355. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4356. auto update = std::async(std::launch::async, [&]() {
  4357. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4358. });
  4359. EXPECT_EQ(std::future_status::timeout,
  4360. update.wait_for(std::chrono::milliseconds(200)));
  4361. detail::close_socket(sock);
  4362. EXPECT_TRUE(update.get());
  4363. SSLClient cli(HOST, PORT);
  4364. cli.enable_server_certificate_verification(false);
  4365. auto res = cli.Get("/test");
  4366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4367. EXPECT_EQ(StatusCode::OK_200, res->status);
  4368. }
  4369. #endif
  4370. TEST(ErrorHandlerTest, ContentLength) {
  4371. Server svr;
  4372. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4373. res.status = StatusCode::OK_200;
  4374. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4375. "text/html"); // <= Content-Length still 13
  4376. });
  4377. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4378. res.set_content("Hello World!\n", "text/plain");
  4379. res.status = 524;
  4380. });
  4381. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4382. auto se = detail::scope_exit([&] {
  4383. svr.stop();
  4384. thread.join();
  4385. ASSERT_FALSE(svr.is_running());
  4386. });
  4387. svr.wait_until_ready();
  4388. {
  4389. Client cli(HOST, PORT);
  4390. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4392. EXPECT_EQ(StatusCode::OK_200, res->status);
  4393. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4394. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4395. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4396. }
  4397. }
  4398. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4399. TEST(ExceptionTest, WithoutExceptionHandler) {
  4400. Server svr;
  4401. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4402. throw std::runtime_error("exception...");
  4403. });
  4404. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4405. throw std::runtime_error("exception\r\n...");
  4406. });
  4407. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4408. auto se = detail::scope_exit([&] {
  4409. svr.stop();
  4410. listen_thread.join();
  4411. ASSERT_FALSE(svr.is_running());
  4412. });
  4413. svr.wait_until_ready();
  4414. Client cli("localhost", PORT);
  4415. {
  4416. auto res = cli.Get("/exception");
  4417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4418. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4419. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4420. }
  4421. {
  4422. auto res = cli.Get("/unknown");
  4423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4424. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4425. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4426. }
  4427. }
  4428. TEST(ExceptionTest, WithExceptionHandler) {
  4429. Server svr;
  4430. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4431. std::exception_ptr ep) {
  4432. EXPECT_FALSE(ep == nullptr);
  4433. try {
  4434. std::rethrow_exception(ep);
  4435. } catch (std::exception &e) {
  4436. EXPECT_EQ("abc", std::string(e.what()));
  4437. } catch (...) {}
  4438. res.status = StatusCode::InternalServerError_500;
  4439. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4440. "text/html"); // <= Content-Length still 13 at this point
  4441. });
  4442. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4443. res.set_content("Hello World!\n", "text/plain");
  4444. throw std::runtime_error("abc");
  4445. });
  4446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4447. auto se = detail::scope_exit([&] {
  4448. svr.stop();
  4449. thread.join();
  4450. ASSERT_FALSE(svr.is_running());
  4451. });
  4452. svr.wait_until_ready();
  4453. for (size_t i = 0; i < 10; i++) {
  4454. Client cli(HOST, PORT);
  4455. for (size_t j = 0; j < 100; j++) {
  4456. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4458. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4459. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4460. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4461. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4462. }
  4463. cli.set_keep_alive(true);
  4464. for (size_t j = 0; j < 100; j++) {
  4465. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4467. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4468. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4469. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4470. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4471. }
  4472. }
  4473. }
  4474. TEST(ExceptionTest, AndErrorHandler) {
  4475. Server svr;
  4476. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4477. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4478. });
  4479. svr.set_exception_handler(
  4480. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4481. EXPECT_FALSE(ep == nullptr);
  4482. try {
  4483. std::rethrow_exception(ep);
  4484. } catch (std::exception &e) {
  4485. res.set_content(e.what(), "text/html");
  4486. } catch (...) {}
  4487. res.status = StatusCode::InternalServerError_500;
  4488. });
  4489. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4490. throw std::runtime_error("EXCEPTION");
  4491. });
  4492. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4493. res.set_content("ERROR", "text/html");
  4494. res.status = StatusCode::InternalServerError_500;
  4495. });
  4496. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4497. auto se = detail::scope_exit([&] {
  4498. svr.stop();
  4499. thread.join();
  4500. ASSERT_FALSE(svr.is_running());
  4501. });
  4502. svr.wait_until_ready();
  4503. Client cli(HOST, PORT);
  4504. {
  4505. auto res = cli.Get("/exception");
  4506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4507. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4508. EXPECT_EQ("EXCEPTION", res->body);
  4509. }
  4510. {
  4511. auto res = cli.Get("/error");
  4512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4513. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4514. EXPECT_EQ("ERROR", res->body);
  4515. }
  4516. {
  4517. auto res = cli.Get("/invalid");
  4518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4519. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4520. EXPECT_EQ("NOT_FOUND", res->body);
  4521. }
  4522. }
  4523. #endif
  4524. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4525. // process_request() wraps only routing() in a try/catch, so an exception from
  4526. // any other user callback used to unwind into the task queue - which does not
  4527. // catch - and terminate the process. Each test below runs the server on a
  4528. // single worker thread: a guard that catches the exception but still loses the
  4529. // thread would otherwise be hidden by a spare worker serving the follow-up
  4530. // request. Note that a regression here aborts the whole test binary rather
  4531. // than failing one test.
  4532. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4533. Server svr;
  4534. svr.new_task_queue = [] { return new ThreadPool(1); };
  4535. std::atomic<int> reported{0};
  4536. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4537. if (err == Error::UserCallbackException) { reported++; }
  4538. });
  4539. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4540. res.set_content_provider(
  4541. 1024, "text/plain",
  4542. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4543. sink.write("hello", 5);
  4544. throw std::runtime_error("from the content provider");
  4545. });
  4546. });
  4547. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4548. res.set_content("ok", "text/plain");
  4549. });
  4550. auto port = svr.bind_to_any_port(HOST);
  4551. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4552. auto se = detail::scope_exit([&] {
  4553. svr.stop();
  4554. listen_thread.join();
  4555. ASSERT_FALSE(svr.is_running());
  4556. });
  4557. svr.wait_until_ready();
  4558. {
  4559. Client cli(HOST, port);
  4560. cli.set_read_timeout(5, 0);
  4561. EXPECT_FALSE(cli.Get("/throw"));
  4562. }
  4563. EXPECT_TRUE(svr.is_running());
  4564. EXPECT_EQ(1, reported.load());
  4565. // A request on a fresh connection is still served.
  4566. {
  4567. Client cli(HOST, port);
  4568. auto res = cli.Get("/ok");
  4569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4570. EXPECT_EQ(StatusCode::OK_200, res->status);
  4571. EXPECT_EQ("ok", res->body);
  4572. }
  4573. }
  4574. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4575. Server svr;
  4576. svr.new_task_queue = [] { return new ThreadPool(1); };
  4577. std::atomic<bool> should_throw{true};
  4578. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4579. res.set_content("hi", "text/plain");
  4580. });
  4581. svr.set_post_routing_handler(
  4582. [&](const Request & /*req*/, Response & /*res*/) {
  4583. if (should_throw) {
  4584. throw std::runtime_error("from the post-routing handler");
  4585. }
  4586. });
  4587. auto port = svr.bind_to_any_port(HOST);
  4588. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4589. auto se = detail::scope_exit([&] {
  4590. svr.stop();
  4591. listen_thread.join();
  4592. ASSERT_FALSE(svr.is_running());
  4593. });
  4594. svr.wait_until_ready();
  4595. {
  4596. Client cli(HOST, port);
  4597. cli.set_read_timeout(5, 0);
  4598. EXPECT_FALSE(cli.Get("/hi"));
  4599. }
  4600. EXPECT_TRUE(svr.is_running());
  4601. should_throw = false;
  4602. {
  4603. Client cli(HOST, port);
  4604. auto res = cli.Get("/hi");
  4605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4606. EXPECT_EQ(StatusCode::OK_200, res->status);
  4607. EXPECT_EQ("hi", res->body);
  4608. }
  4609. }
  4610. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4611. // The guard reports the caught exception through the error logger, which is
  4612. // a user callback too. A logger that throws has to be contained as well, or
  4613. // the process would terminate from inside the catch.
  4614. Server svr;
  4615. svr.new_task_queue = [] { return new ThreadPool(1); };
  4616. std::atomic<int> reported{0};
  4617. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4618. if (err == Error::UserCallbackException) {
  4619. reported++;
  4620. throw std::runtime_error("from the error logger");
  4621. }
  4622. });
  4623. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4624. res.set_content_provider(
  4625. 1024, "text/plain",
  4626. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4627. sink.write("hello", 5);
  4628. throw std::runtime_error("from the content provider");
  4629. });
  4630. });
  4631. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4632. res.set_content("ok", "text/plain");
  4633. });
  4634. auto port = svr.bind_to_any_port(HOST);
  4635. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4636. auto se = detail::scope_exit([&] {
  4637. svr.stop();
  4638. listen_thread.join();
  4639. ASSERT_FALSE(svr.is_running());
  4640. });
  4641. svr.wait_until_ready();
  4642. {
  4643. Client cli(HOST, port);
  4644. cli.set_read_timeout(5, 0);
  4645. EXPECT_FALSE(cli.Get("/throw"));
  4646. }
  4647. EXPECT_TRUE(svr.is_running());
  4648. EXPECT_EQ(1, reported.load());
  4649. {
  4650. Client cli(HOST, port);
  4651. auto res = cli.Get("/ok");
  4652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4653. EXPECT_EQ(StatusCode::OK_200, res->status);
  4654. EXPECT_EQ("ok", res->body);
  4655. }
  4656. }
  4657. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4658. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4659. // so the exception unwinds through the ws::WebSocket object on its way to
  4660. // the guard. None of the HTTP cases above cross that.
  4661. Server svr;
  4662. svr.new_task_queue = [] { return new ThreadPool(1); };
  4663. std::atomic<int> reported{0};
  4664. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4665. if (err == Error::UserCallbackException) { reported++; }
  4666. });
  4667. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4668. throw std::runtime_error("from the WebSocket handler");
  4669. });
  4670. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4671. res.set_content("ok", "text/plain");
  4672. });
  4673. auto port = svr.bind_to_any_port(HOST);
  4674. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4675. auto se = detail::scope_exit([&] {
  4676. svr.stop();
  4677. listen_thread.join();
  4678. ASSERT_FALSE(svr.is_running());
  4679. });
  4680. svr.wait_until_ready();
  4681. {
  4682. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4683. "/ws");
  4684. auto res = client.connect();
  4685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4686. // The server dropped the connection instead of dying.
  4687. std::string msg;
  4688. EXPECT_FALSE(client.read(msg));
  4689. client.close();
  4690. }
  4691. EXPECT_TRUE(svr.is_running());
  4692. EXPECT_EQ(1, reported.load());
  4693. {
  4694. Client cli(HOST, port);
  4695. auto res = cli.Get("/ok");
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. EXPECT_EQ(StatusCode::OK_200, res->status);
  4698. EXPECT_EQ("ok", res->body);
  4699. }
  4700. }
  4701. #ifdef CPPHTTPLIB_SSL_ENABLED
  4702. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4703. // SSLServer::process_and_close_socket() is a separate overload with its own
  4704. // guard, so it is exercised on its own.
  4705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4706. ASSERT_TRUE(svr.is_valid());
  4707. svr.new_task_queue = [] { return new ThreadPool(1); };
  4708. std::atomic<int> reported{0};
  4709. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4710. if (err == Error::UserCallbackException) { reported++; }
  4711. });
  4712. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4713. res.set_content_provider(
  4714. 1024, "text/plain",
  4715. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4716. sink.write("hello", 5);
  4717. throw std::runtime_error("from the content provider");
  4718. });
  4719. });
  4720. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4721. res.set_content("ok", "text/plain");
  4722. });
  4723. auto port = svr.bind_to_any_port(HOST);
  4724. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4725. auto se = detail::scope_exit([&] {
  4726. svr.stop();
  4727. listen_thread.join();
  4728. ASSERT_FALSE(svr.is_running());
  4729. });
  4730. svr.wait_until_ready();
  4731. {
  4732. SSLClient cli(HOST, port);
  4733. cli.enable_server_certificate_verification(false);
  4734. cli.set_read_timeout(5, 0);
  4735. EXPECT_FALSE(cli.Get("/throw"));
  4736. }
  4737. EXPECT_TRUE(svr.is_running());
  4738. EXPECT_EQ(1, reported.load());
  4739. {
  4740. SSLClient cli(HOST, port);
  4741. cli.enable_server_certificate_verification(false);
  4742. auto res = cli.Get("/ok");
  4743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4744. EXPECT_EQ(StatusCode::OK_200, res->status);
  4745. EXPECT_EQ("ok", res->body);
  4746. }
  4747. }
  4748. #endif
  4749. #endif
  4750. TEST(NoContentTest, ContentLength) {
  4751. Server svr;
  4752. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4753. res.status = StatusCode::NoContent_204;
  4754. });
  4755. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4756. auto se = detail::scope_exit([&] {
  4757. svr.stop();
  4758. thread.join();
  4759. ASSERT_FALSE(svr.is_running());
  4760. });
  4761. svr.wait_until_ready();
  4762. {
  4763. Client cli(HOST, PORT);
  4764. auto res = cli.Get("/hi");
  4765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4766. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4767. // RFC 9110 8.6: none in a 204 response
  4768. EXPECT_FALSE(res->has_header("Content-Length"));
  4769. }
  4770. }
  4771. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4772. Server svr;
  4773. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4774. res.set_header("Content-Length", "5");
  4775. res.set_content("hello world", "text/plain");
  4776. });
  4777. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4778. // A body that reads as the last chunk, were it taken as chunked
  4779. res.set_header("Transfer-Encoding", "chunked");
  4780. res.set_content("0\r\n\r\n", "text/plain");
  4781. });
  4782. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4783. res.set_header("Content-Length", "2");
  4784. res.set_content_provider(5, "text/plain",
  4785. [](size_t offset, size_t length, DataSink &sink) {
  4786. sink.write(&"hello"[offset], length);
  4787. return true;
  4788. });
  4789. });
  4790. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4791. res.set_header("Content-Length", "1234");
  4792. });
  4793. thread t = thread([&] { svr.listen(HOST, PORT); });
  4794. auto se = detail::scope_exit([&] {
  4795. svr.stop();
  4796. t.join();
  4797. ASSERT_FALSE(svr.is_running());
  4798. });
  4799. svr.wait_until_ready();
  4800. Client cli(HOST, PORT);
  4801. cli.set_read_timeout(1, 0);
  4802. auto expect_body = [&](const Result &res, const std::string &body) {
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. EXPECT_EQ(body, res->body);
  4805. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4806. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4807. };
  4808. Headers identity{{"Accept-Encoding", ""}};
  4809. expect_body(cli.Get("/body", identity), "hello world");
  4810. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4811. expect_body(cli.Get("/body",
  4812. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4813. "he");
  4814. expect_body(cli.Get("/provider", identity), "hello");
  4815. expect_body(cli.Get("/empty", identity), "");
  4816. // A HEAD response may give the length of the body a GET would get.
  4817. auto res = cli.Head("/empty");
  4818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4819. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4820. }
  4821. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4822. Server svr;
  4823. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4824. res.set_content("short", "text/plain");
  4825. });
  4826. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4827. res.body += " with a footer";
  4828. res.set_header("Transfer-Encoding", "chunked");
  4829. });
  4830. thread t = thread([&] { svr.listen(HOST, PORT); });
  4831. auto se = detail::scope_exit([&] {
  4832. svr.stop();
  4833. t.join();
  4834. ASSERT_FALSE(svr.is_running());
  4835. });
  4836. svr.wait_until_ready();
  4837. Client cli(HOST, PORT);
  4838. cli.set_read_timeout(1, 0);
  4839. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4841. EXPECT_EQ("short with a footer", res->body);
  4842. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4843. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4844. }
  4845. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4846. Server svr;
  4847. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4848. res.set_header("Content-Length", "3");
  4849. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4850. sink.write("abc", 3);
  4851. sink.done();
  4852. return true;
  4853. });
  4854. });
  4855. thread t = thread([&] { svr.listen(HOST, PORT); });
  4856. auto se = detail::scope_exit([&] {
  4857. svr.stop();
  4858. t.join();
  4859. ASSERT_FALSE(svr.is_running());
  4860. });
  4861. svr.wait_until_ready();
  4862. Client cli(HOST, PORT);
  4863. cli.set_keep_alive(true);
  4864. auto res = cli.Get("/");
  4865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4866. EXPECT_EQ("abc", res->body);
  4867. EXPECT_FALSE(res->has_header("Content-Length"));
  4868. EXPECT_EQ("close", res->get_header_value("Connection"));
  4869. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4870. // No body to delimit
  4871. auto head = cli.Head("/");
  4872. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4873. EXPECT_FALSE(head->has_header("Connection"));
  4874. }
  4875. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4876. #ifdef CPPHTTPLIB_SSL_ENABLED
  4877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4878. ASSERT_TRUE(svr.is_valid());
  4879. #else
  4880. Server svr;
  4881. #endif
  4882. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4883. if (req.path == "/routing_handler") {
  4884. res.set_header("PRE_ROUTING", "on");
  4885. res.set_content("Routing Handler", "text/plain");
  4886. return httplib::Server::HandlerResponse::Handled;
  4887. }
  4888. return httplib::Server::HandlerResponse::Unhandled;
  4889. });
  4890. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4891. res.set_content("Error", "text/html");
  4892. });
  4893. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4894. if (req.path == "/routing_handler") {
  4895. res.set_header("POST_ROUTING", "on");
  4896. }
  4897. });
  4898. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4899. res.set_content("Hello World!\n", "text/plain");
  4900. });
  4901. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4902. auto se = detail::scope_exit([&] {
  4903. svr.stop();
  4904. thread.join();
  4905. ASSERT_FALSE(svr.is_running());
  4906. });
  4907. svr.wait_until_ready();
  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("/routing_handler");
  4916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4917. EXPECT_EQ(StatusCode::OK_200, res->status);
  4918. EXPECT_EQ("Routing Handler", res->body);
  4919. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4920. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4921. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4922. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4923. }
  4924. {
  4925. #ifdef CPPHTTPLIB_SSL_ENABLED
  4926. SSLClient cli(HOST, PORT);
  4927. cli.enable_server_certificate_verification(false);
  4928. #else
  4929. Client cli(HOST, PORT);
  4930. #endif
  4931. auto res = cli.Get("/hi");
  4932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4933. EXPECT_EQ(StatusCode::OK_200, res->status);
  4934. EXPECT_EQ("Hello World!\n", res->body);
  4935. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4936. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4937. }
  4938. {
  4939. #ifdef CPPHTTPLIB_SSL_ENABLED
  4940. SSLClient cli(HOST, PORT);
  4941. cli.enable_server_certificate_verification(false);
  4942. #else
  4943. Client cli(HOST, PORT);
  4944. #endif
  4945. auto res = cli.Get("/aaa");
  4946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4947. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4948. EXPECT_EQ("Error", res->body);
  4949. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4950. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4951. }
  4952. }
  4953. TEST(RequestHandlerTest, PreRequestHandler) {
  4954. auto route_path = "/user/:user";
  4955. Server svr;
  4956. svr.Get("/hi", [](const Request &, Response &res) {
  4957. res.set_content("hi", "text/plain");
  4958. });
  4959. svr.Get(route_path, [](const Request &req, Response &res) {
  4960. res.set_content(req.path_params.at("user"), "text/plain");
  4961. });
  4962. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4963. if (req.matched_route == route_path) {
  4964. auto user = req.path_params.at("user");
  4965. if (user != "john") {
  4966. res.status = StatusCode::Forbidden_403;
  4967. res.set_content("error", "text/html");
  4968. return Server::HandlerResponse::Handled;
  4969. }
  4970. }
  4971. return Server::HandlerResponse::Unhandled;
  4972. });
  4973. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4974. auto se = detail::scope_exit([&] {
  4975. svr.stop();
  4976. thread.join();
  4977. ASSERT_FALSE(svr.is_running());
  4978. });
  4979. svr.wait_until_ready();
  4980. Client cli(HOST, PORT);
  4981. {
  4982. auto res = cli.Get("/hi");
  4983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4984. EXPECT_EQ(StatusCode::OK_200, res->status);
  4985. EXPECT_EQ("hi", res->body);
  4986. }
  4987. {
  4988. auto res = cli.Get("/user/john");
  4989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4990. EXPECT_EQ(StatusCode::OK_200, res->status);
  4991. EXPECT_EQ("john", res->body);
  4992. }
  4993. {
  4994. auto res = cli.Get("/user/invalid-user");
  4995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4996. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4997. EXPECT_EQ("error", res->body);
  4998. }
  4999. }
  5000. // The pre-request handler must run before the request body is read, so a
  5001. // rejected request never forces the server to buffer a (potentially large)
  5002. // body. Here the posted body is larger than the payload limit: if the body
  5003. // were read first the server would answer 413, but because the pre-request
  5004. // handler runs first it answers 403 and the body is never read.
  5005. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5006. Server svr;
  5007. svr.set_payload_max_length(8);
  5008. auto handler_ran = false;
  5009. svr.Post("/reject", [&](const Request &req, Response &res) {
  5010. handler_ran = true;
  5011. res.set_content(req.body, "text/plain");
  5012. });
  5013. svr.Post("/accept", [](const Request &req, Response &res) {
  5014. res.set_content(req.body, "text/plain");
  5015. });
  5016. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5017. if (req.matched_route == "/reject") {
  5018. res.status = StatusCode::Forbidden_403;
  5019. res.set_content("denied", "text/plain");
  5020. return Server::HandlerResponse::Handled;
  5021. }
  5022. return Server::HandlerResponse::Unhandled;
  5023. });
  5024. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5025. auto se = detail::scope_exit([&] {
  5026. svr.stop();
  5027. thread.join();
  5028. ASSERT_FALSE(svr.is_running());
  5029. });
  5030. svr.wait_until_ready();
  5031. Client cli(HOST, PORT);
  5032. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5033. // rejects with 403 before the body is read, so 413 is never reached.
  5034. {
  5035. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5037. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5038. EXPECT_EQ("denied", res->body);
  5039. EXPECT_FALSE(handler_ran);
  5040. }
  5041. // An approved route still reads the body and enforces the payload limit.
  5042. {
  5043. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5045. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5046. }
  5047. }
  5048. TEST(UserDataTest, BasicOperations) {
  5049. httplib::UserData ud;
  5050. // Initially empty
  5051. EXPECT_FALSE(ud.has("key"));
  5052. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5053. // set and get
  5054. ud.set("key", 42);
  5055. EXPECT_TRUE(ud.has("key"));
  5056. auto *p = ud.get<int>("key");
  5057. ASSERT_NE(nullptr, p);
  5058. EXPECT_EQ(42, *p);
  5059. // Type mismatch → nullptr
  5060. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5061. // Overwrite with different type
  5062. ud.set("key", std::string("hello"));
  5063. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5064. auto *s = ud.get<std::string>("key");
  5065. ASSERT_NE(nullptr, s);
  5066. EXPECT_EQ("hello", *s);
  5067. // erase
  5068. ud.erase("key");
  5069. EXPECT_FALSE(ud.has("key"));
  5070. // clear
  5071. ud.set("a", 1);
  5072. ud.set("b", 2);
  5073. ud.clear();
  5074. EXPECT_FALSE(ud.has("a"));
  5075. EXPECT_FALSE(ud.has("b"));
  5076. }
  5077. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5078. struct AuthCtx {
  5079. std::string user_id;
  5080. };
  5081. Server svr;
  5082. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5083. res.user_data.set("auth", AuthCtx{"alice"});
  5084. return Server::HandlerResponse::Unhandled;
  5085. });
  5086. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5087. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5088. ASSERT_NE(nullptr, ctx);
  5089. res.set_content("Hello " + ctx->user_id, "text/plain");
  5090. });
  5091. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5092. auto se = detail::scope_exit([&] {
  5093. svr.stop();
  5094. thread.join();
  5095. ASSERT_FALSE(svr.is_running());
  5096. });
  5097. svr.wait_until_ready();
  5098. Client cli(HOST, PORT);
  5099. auto res = cli.Get("/me");
  5100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5101. EXPECT_EQ(StatusCode::OK_200, res->status);
  5102. EXPECT_EQ("Hello alice", res->body);
  5103. }
  5104. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5105. struct RoleCtx {
  5106. std::string role;
  5107. };
  5108. Server svr;
  5109. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5110. res.user_data.set("role", RoleCtx{"admin"});
  5111. return Server::HandlerResponse::Unhandled;
  5112. });
  5113. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5114. auto *ctx = res.user_data.get<RoleCtx>("role");
  5115. ASSERT_NE(nullptr, ctx);
  5116. res.set_content(ctx->role, "text/plain");
  5117. });
  5118. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5119. auto se = detail::scope_exit([&] {
  5120. svr.stop();
  5121. thread.join();
  5122. ASSERT_FALSE(svr.is_running());
  5123. });
  5124. svr.wait_until_ready();
  5125. Client cli(HOST, PORT);
  5126. auto res = cli.Get("/role");
  5127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5128. EXPECT_EQ(StatusCode::OK_200, res->status);
  5129. EXPECT_EQ("admin", res->body);
  5130. }
  5131. TEST(InvalidFormatTest, StatusCode) {
  5132. Server svr;
  5133. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5134. res.set_content("Hello World!\n", "text/plain");
  5135. res.status = 9999; // Status should be a three-digit code...
  5136. });
  5137. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5138. auto se = detail::scope_exit([&] {
  5139. svr.stop();
  5140. thread.join();
  5141. ASSERT_FALSE(svr.is_running());
  5142. });
  5143. svr.wait_until_ready();
  5144. {
  5145. Client cli(HOST, PORT);
  5146. auto res = cli.Get("/hi");
  5147. ASSERT_FALSE(res);
  5148. }
  5149. }
  5150. TEST(URLFragmentTest, WithFragment) {
  5151. Server svr;
  5152. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5153. EXPECT_TRUE(req.target == "/hi");
  5154. });
  5155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5156. auto se = detail::scope_exit([&] {
  5157. svr.stop();
  5158. thread.join();
  5159. ASSERT_FALSE(svr.is_running());
  5160. });
  5161. svr.wait_until_ready();
  5162. {
  5163. Client cli(HOST, PORT);
  5164. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5165. EXPECT_TRUE(res);
  5166. EXPECT_EQ(StatusCode::OK_200, res->status);
  5167. res = cli.Get("/hi%23key1=val1=key2=val2");
  5168. EXPECT_TRUE(res);
  5169. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5170. }
  5171. }
  5172. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5173. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5174. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5175. Server svr;
  5176. std::vector<std::string> targets;
  5177. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5178. targets.push_back(req.target);
  5179. });
  5180. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5181. auto se = detail::scope_exit([&] {
  5182. svr.stop();
  5183. thread.join();
  5184. ASSERT_FALSE(svr.is_running());
  5185. });
  5186. svr.wait_until_ready();
  5187. Client cli(HOST, PORT);
  5188. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5189. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5190. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5191. // A '?' after the '#' belongs to the fragment, not to the query.
  5192. Request req;
  5193. req.method = "GET";
  5194. req.path = "/hi#f?x=1";
  5195. req.params.emplace("a", "1");
  5196. Response res;
  5197. auto error = Error::Success;
  5198. EXPECT_TRUE(cli.send(req, res, error));
  5199. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5200. "/hi?a=1"}),
  5201. targets);
  5202. }
  5203. TEST(HeaderWriter, SetHeaderWriter) {
  5204. Server svr;
  5205. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5206. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5207. return detail::write_headers(strm, hdrs);
  5208. });
  5209. svr.Get("/hi", [](const Request &req, Response &res) {
  5210. auto it = req.headers.find("CustomClientHeader");
  5211. EXPECT_TRUE(it != req.headers.end());
  5212. EXPECT_EQ(it->second, "CustomClientValue");
  5213. res.set_content("Hello World!\n", "text/plain");
  5214. });
  5215. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5216. auto se = detail::scope_exit([&] {
  5217. svr.stop();
  5218. thread.join();
  5219. ASSERT_FALSE(svr.is_running());
  5220. });
  5221. svr.wait_until_ready();
  5222. {
  5223. Client cli(HOST, PORT);
  5224. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5225. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5226. return detail::write_headers(strm, hdrs);
  5227. });
  5228. auto res = cli.Get("/hi");
  5229. EXPECT_TRUE(res);
  5230. EXPECT_EQ(StatusCode::OK_200, res->status);
  5231. auto it = res->headers.find("CustomServerHeader");
  5232. EXPECT_TRUE(it != res->headers.end());
  5233. EXPECT_EQ(it->second, "CustomServerValue");
  5234. }
  5235. }
  5236. class ServerTest : public ::testing::Test {
  5237. protected:
  5238. ServerTest()
  5239. : cli_(HOST, PORT)
  5240. #ifdef CPPHTTPLIB_SSL_ENABLED
  5241. ,
  5242. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5243. #endif
  5244. {
  5245. #ifdef CPPHTTPLIB_SSL_ENABLED
  5246. cli_.enable_server_certificate_verification(false);
  5247. #endif
  5248. // Allow LARGE_DATA (100MB) responses
  5249. cli_.set_payload_max_length(200 * 1024 * 1024);
  5250. }
  5251. virtual void SetUp() {
  5252. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5253. svr_.set_payload_max_length(200 * 1024 * 1024);
  5254. svr_.set_mount_point("/", "./www");
  5255. svr_.set_mount_point("/mount", "./www2");
  5256. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5257. svr_.Get("/hi",
  5258. [&](const Request & /*req*/, Response &res) {
  5259. res.set_content("Hello World!", "text/plain");
  5260. })
  5261. .Get("/file_content",
  5262. [&](const Request & /*req*/, Response &res) {
  5263. res.set_file_content("./www/dir/test.html");
  5264. })
  5265. .Get("/file_content_with_content_type",
  5266. [&](const Request & /*req*/, Response &res) {
  5267. res.set_file_content("./www/file", "text/plain");
  5268. })
  5269. .Get("/invalid_file_content",
  5270. [&](const Request & /*req*/, Response &res) {
  5271. res.set_file_content("./www/dir/invalid_file_path");
  5272. })
  5273. .Get("/http_response_splitting",
  5274. [&](const Request & /*req*/, Response &res) {
  5275. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5276. EXPECT_EQ(0U, res.headers.size());
  5277. EXPECT_FALSE(res.has_header("a"));
  5278. res.set_header("a", "1\nSet-Cookie: a=1");
  5279. EXPECT_EQ(0U, res.headers.size());
  5280. EXPECT_FALSE(res.has_header("a"));
  5281. res.set_header("a", "1\rSet-Cookie: a=1");
  5282. EXPECT_EQ(0U, res.headers.size());
  5283. EXPECT_FALSE(res.has_header("a"));
  5284. res.set_header("a\r\nb", "0");
  5285. EXPECT_EQ(0U, res.headers.size());
  5286. EXPECT_FALSE(res.has_header("a"));
  5287. res.set_header("a\rb", "0");
  5288. EXPECT_EQ(0U, res.headers.size());
  5289. EXPECT_FALSE(res.has_header("a"));
  5290. res.set_header("a\nb", "0");
  5291. EXPECT_EQ(0U, res.headers.size());
  5292. EXPECT_FALSE(res.has_header("a"));
  5293. res.set_redirect("1\r\nSet-Cookie: a=1");
  5294. EXPECT_EQ(0U, res.headers.size());
  5295. EXPECT_FALSE(res.has_header("Location"));
  5296. })
  5297. .Get("/slow",
  5298. [&](const Request & /*req*/, Response &res) {
  5299. std::this_thread::sleep_for(std::chrono::seconds(4));
  5300. res.set_content("slow", "text/plain");
  5301. })
  5302. #if 0
  5303. .Post("/slowpost",
  5304. [&](const Request & /*req*/, Response &res) {
  5305. std::this_thread::sleep_for(std::chrono::seconds(2));
  5306. res.set_content("slow", "text/plain");
  5307. })
  5308. #endif
  5309. .Get("/remote_addr",
  5310. [&](const Request &req, Response &res) {
  5311. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5312. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5313. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5314. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5315. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5316. #endif
  5317. res.set_content(req.remote_addr, "text/plain");
  5318. })
  5319. .Get("/local_addr",
  5320. [&](const Request &req, Response &res) {
  5321. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5322. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5323. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5324. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5325. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5326. #endif
  5327. auto local_addr = req.local_addr;
  5328. auto local_port = std::to_string(req.local_port);
  5329. res.set_content(local_addr.append(":").append(local_port),
  5330. "text/plain");
  5331. })
  5332. .Get("/endwith%",
  5333. [&](const Request & /*req*/, Response &res) {
  5334. res.set_content("Hello World!", "text/plain");
  5335. })
  5336. .Get("/a\\+\\+b",
  5337. [&](const Request &req, Response &res) {
  5338. ASSERT_TRUE(req.has_param("a +b"));
  5339. auto val = req.get_param_value("a +b");
  5340. res.set_content(val, "text/plain");
  5341. })
  5342. .Get("/", [&](const Request & /*req*/,
  5343. Response &res) { res.set_redirect("/hi"); })
  5344. .Post("/1",
  5345. [](const Request & /*req*/, Response &res) {
  5346. res.set_redirect("/2", StatusCode::SeeOther_303);
  5347. })
  5348. .Get("/2",
  5349. [](const Request & /*req*/, Response &res) {
  5350. res.set_content("redirected.", "text/plain");
  5351. res.status = StatusCode::OK_200;
  5352. })
  5353. .Post("/person",
  5354. [&](const Request &req, Response &res) {
  5355. if (req.has_param("name") && req.has_param("note")) {
  5356. persons_[req.get_param_value("name")] =
  5357. req.get_param_value("note");
  5358. } else {
  5359. res.status = StatusCode::BadRequest_400;
  5360. }
  5361. })
  5362. .Put("/person",
  5363. [&](const Request &req, Response &res) {
  5364. if (req.has_param("name") && req.has_param("note")) {
  5365. persons_[req.get_param_value("name")] =
  5366. req.get_param_value("note");
  5367. } else {
  5368. res.status = StatusCode::BadRequest_400;
  5369. }
  5370. })
  5371. .Get("/person/(.*)",
  5372. [&](const Request &req, Response &res) {
  5373. string name = req.matches[1];
  5374. if (persons_.find(name) != persons_.end()) {
  5375. auto note = persons_[name];
  5376. res.set_content(note, "text/plain");
  5377. } else {
  5378. res.status = StatusCode::NotFound_404;
  5379. }
  5380. })
  5381. .Delete("/person",
  5382. [&](const Request &req, Response &res) {
  5383. if (req.has_param("name")) {
  5384. string name = req.get_param_value("name");
  5385. if (persons_.find(name) != persons_.end()) {
  5386. persons_.erase(name);
  5387. res.set_content("DELETED", "text/plain");
  5388. } else {
  5389. res.status = StatusCode::NotFound_404;
  5390. }
  5391. } else {
  5392. res.status = StatusCode::BadRequest_400;
  5393. }
  5394. })
  5395. .Post("/x-www-form-urlencoded-json",
  5396. [&](const Request &req, Response &res) {
  5397. auto json = req.get_param_value("json");
  5398. ASSERT_EQ(JSON_DATA, json);
  5399. res.set_content(json, "appliation/json");
  5400. res.status = StatusCode::OK_200;
  5401. })
  5402. .Get("/streamed-chunked",
  5403. [&](const Request & /*req*/, Response &res) {
  5404. res.set_chunked_content_provider(
  5405. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5406. sink.os << "123";
  5407. sink.os << "456";
  5408. sink.os << "789";
  5409. sink.done();
  5410. return true;
  5411. });
  5412. })
  5413. .Get("/streamed-chunked-with-prohibited-trailer",
  5414. [&](const Request & /*req*/, Response &res) {
  5415. auto i = new int(0);
  5416. // Declare both a prohibited trailer (Content-Length) and an
  5417. // allowed one
  5418. res.set_header("Trailer", "Content-Length, X-Allowed");
  5419. res.set_chunked_content_provider(
  5420. "text/plain",
  5421. [i](size_t /*offset*/, DataSink &sink) {
  5422. switch (*i) {
  5423. case 0: sink.os << "123"; break;
  5424. case 1: sink.os << "456"; break;
  5425. case 2: sink.os << "789"; break;
  5426. case 3: {
  5427. sink.done_with_trailer(
  5428. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5429. } break;
  5430. }
  5431. (*i)++;
  5432. return true;
  5433. },
  5434. [i](bool success) {
  5435. EXPECT_TRUE(success);
  5436. delete i;
  5437. });
  5438. })
  5439. .Get("/streamed-chunked2",
  5440. [&](const Request & /*req*/, Response &res) {
  5441. auto i = new int(0);
  5442. res.set_chunked_content_provider(
  5443. "text/plain",
  5444. [i](size_t /*offset*/, DataSink &sink) {
  5445. switch (*i) {
  5446. case 0: sink.os << "123"; break;
  5447. case 1: sink.os << "456"; break;
  5448. case 2: sink.os << "789"; break;
  5449. case 3: sink.done(); break;
  5450. }
  5451. (*i)++;
  5452. return true;
  5453. },
  5454. [i](bool success) {
  5455. EXPECT_TRUE(success);
  5456. delete i;
  5457. });
  5458. })
  5459. .Get("/streamed-chunked-with-trailer",
  5460. [&](const Request & /*req*/, Response &res) {
  5461. auto i = new int(0);
  5462. res.set_header("Trailer", "Dummy1, Dummy2");
  5463. res.set_chunked_content_provider(
  5464. "text/plain",
  5465. [i](size_t /*offset*/, DataSink &sink) {
  5466. switch (*i) {
  5467. case 0: sink.os << "123"; break;
  5468. case 1: sink.os << "456"; break;
  5469. case 2: sink.os << "789"; break;
  5470. case 3: {
  5471. sink.done_with_trailer(
  5472. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5473. } break;
  5474. }
  5475. (*i)++;
  5476. return true;
  5477. },
  5478. [i](bool success) {
  5479. EXPECT_TRUE(success);
  5480. delete i;
  5481. });
  5482. })
  5483. .Get("/streamed",
  5484. [&](const Request & /*req*/, Response &res) {
  5485. res.set_content_provider(
  5486. 6, "text/plain",
  5487. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5488. sink.os << (offset < 3 ? "a" : "b");
  5489. return true;
  5490. });
  5491. })
  5492. .Get("/streamed-without-length",
  5493. [&](const Request & /*req*/, Response &res) {
  5494. auto data = new std::string("abcdefg");
  5495. res.set_content_provider(
  5496. "text/plain",
  5497. [data](size_t offset, DataSink &sink) {
  5498. if (offset < data->size()) {
  5499. sink.os << data->substr(offset);
  5500. }
  5501. sink.done();
  5502. return true;
  5503. },
  5504. [data](bool success) {
  5505. EXPECT_TRUE(success);
  5506. delete data;
  5507. });
  5508. })
  5509. .Get("/streamed-with-range",
  5510. [&](const Request &req, Response &res) {
  5511. auto data = new std::string("abcdefg");
  5512. // An explicit status keeps the server from picking the 206 it
  5513. // would otherwise choose for a ranged request, so the response
  5514. // is not a partial representation.
  5515. auto status = req.get_param_value("status");
  5516. if (status == "200") {
  5517. res.status = StatusCode::OK_200;
  5518. } else if (status == "403") {
  5519. res.status = StatusCode::Forbidden_403;
  5520. }
  5521. res.set_content_provider(
  5522. data->size(), "text/plain",
  5523. [data](size_t offset, size_t length, DataSink &sink) {
  5524. size_t DATA_CHUNK_SIZE = 4;
  5525. const auto &d = *data;
  5526. auto out_len =
  5527. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5528. auto ret =
  5529. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5530. EXPECT_TRUE(ret);
  5531. return true;
  5532. },
  5533. [data, &req](bool success) {
  5534. EXPECT_EQ(success, !req.has_param("error"));
  5535. delete data;
  5536. });
  5537. })
  5538. .Get("/streamed-cancel",
  5539. [&](const Request & /*req*/, Response &res) {
  5540. res.set_content_provider(
  5541. size_t(-1), "text/plain",
  5542. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5543. sink.os << "data_chunk";
  5544. return true;
  5545. });
  5546. })
  5547. .Get("/regex-with-delimiter",
  5548. [&](const Request &req, Response & /*res*/) {
  5549. ASSERT_TRUE(req.has_param("key"));
  5550. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5551. })
  5552. .Get("/with-range",
  5553. [&](const Request & /*req*/, Response &res) {
  5554. res.set_content("abcdefg", "text/plain");
  5555. })
  5556. .Get("/test-start-time",
  5557. [&](const Request &req, Response & /*res*/) {
  5558. EXPECT_NE(req.start_time_,
  5559. std::chrono::steady_clock::time_point::min());
  5560. })
  5561. .Get("/with-range-customized-response",
  5562. [&](const Request & /*req*/, Response &res) {
  5563. res.status = StatusCode::BadRequest_400;
  5564. res.set_content(JSON_DATA, "application/json");
  5565. })
  5566. .Post("/chunked",
  5567. [&](const Request &req, Response & /*res*/) {
  5568. EXPECT_EQ(req.body, "dechunked post body");
  5569. })
  5570. .Post("/large-chunked",
  5571. [&](const Request &req, Response & /*res*/) {
  5572. std::string expected(6 * 30 * 1024u, 'a');
  5573. EXPECT_EQ(req.body, expected);
  5574. })
  5575. .Post("/multipart",
  5576. [&](const Request &req, Response & /*res*/) {
  5577. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5578. req.form.get_field_count("text2") +
  5579. req.form.get_field_count("file3") +
  5580. req.form.get_field_count("file4"));
  5581. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5582. req.form.get_file_count("file2"));
  5583. ASSERT_TRUE(!req.form.has_file("???"));
  5584. ASSERT_TRUE(!req.form.has_field("???"));
  5585. ASSERT_TRUE(req.body.empty());
  5586. {
  5587. const auto &text = req.form.get_field("text1");
  5588. EXPECT_EQ("text default", text);
  5589. }
  5590. {
  5591. const auto &text = req.form.get_field("text2");
  5592. EXPECT_EQ("aωb", text);
  5593. }
  5594. {
  5595. const auto &file = req.form.get_file("file1");
  5596. EXPECT_EQ("hello.txt", file.filename);
  5597. EXPECT_EQ("text/plain", file.content_type);
  5598. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5599. }
  5600. {
  5601. const auto &file = req.form.get_file("file2");
  5602. EXPECT_EQ("world.json", file.filename);
  5603. EXPECT_EQ("application/json", file.content_type);
  5604. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5605. }
  5606. {
  5607. const auto &text = req.form.get_field("file3");
  5608. EXPECT_EQ(0u, text.size());
  5609. }
  5610. {
  5611. const auto &text = req.form.get_field("file4");
  5612. EXPECT_EQ(0u, text.size());
  5613. }
  5614. })
  5615. .Post("/multipart/multi_file_values",
  5616. [&](const Request &req, Response & /*res*/) {
  5617. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5618. req.form.get_field_count("multi_text1"));
  5619. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5620. ASSERT_TRUE(!req.form.has_file("???"));
  5621. ASSERT_TRUE(!req.form.has_field("???"));
  5622. ASSERT_TRUE(req.body.empty());
  5623. {
  5624. const auto &text = req.form.get_field("text");
  5625. EXPECT_EQ("default text", text);
  5626. }
  5627. {
  5628. const auto &text1_values = req.form.get_fields("multi_text1");
  5629. EXPECT_EQ(2u, text1_values.size());
  5630. EXPECT_EQ("aaaaa", text1_values[0]);
  5631. EXPECT_EQ("bbbbb", text1_values[1]);
  5632. }
  5633. {
  5634. const auto &file1_values = req.form.get_files("multi_file1");
  5635. EXPECT_EQ(2u, file1_values.size());
  5636. auto file1 = file1_values[0];
  5637. EXPECT_EQ(file1.filename, "hello.txt");
  5638. EXPECT_EQ(file1.content_type, "text/plain");
  5639. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5640. auto file2 = file1_values[1];
  5641. EXPECT_EQ(file2.filename, "world.json");
  5642. EXPECT_EQ(file2.content_type, "application/json");
  5643. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5644. }
  5645. })
  5646. .Post("/empty",
  5647. [&](const Request &req, Response &res) {
  5648. EXPECT_EQ(req.body, "");
  5649. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5650. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5651. res.set_content("empty", "text/plain");
  5652. })
  5653. .Post("/empty-no-content-type",
  5654. [&](const Request &req, Response &res) {
  5655. EXPECT_EQ(req.body, "");
  5656. EXPECT_FALSE(req.has_header("Content-Type"));
  5657. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5658. res.set_content("empty-no-content-type", "text/plain");
  5659. })
  5660. .Post("/path-only",
  5661. [&](const Request &req, Response &res) {
  5662. EXPECT_EQ(req.body, "");
  5663. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5664. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5665. res.set_content("path-only", "text/plain");
  5666. })
  5667. .Post("/path-headers-only",
  5668. [&](const Request &req, Response &res) {
  5669. EXPECT_EQ(req.body, "");
  5670. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5671. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5672. EXPECT_EQ("world", req.get_header_value("hello"));
  5673. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5674. res.set_content("path-headers-only", "text/plain");
  5675. })
  5676. .Post("/post-large",
  5677. [&](const Request &req, Response &res) {
  5678. EXPECT_EQ(req.body, LARGE_DATA);
  5679. res.set_content(req.body, "text/plain");
  5680. })
  5681. .Post("/post-loopback",
  5682. [&](const Request &, Response &res,
  5683. ContentReader const &content_reader) {
  5684. std::string body;
  5685. content_reader([&](const char *data, size_t data_length) {
  5686. body.append(data, data_length);
  5687. return true;
  5688. });
  5689. res.set_content(body, "text/plain");
  5690. })
  5691. .Put("/put-loopback",
  5692. [&](const Request &, Response &res,
  5693. ContentReader const &content_reader) {
  5694. std::string body;
  5695. content_reader([&](const char *data, size_t data_length) {
  5696. body.append(data, data_length);
  5697. return true;
  5698. });
  5699. res.set_content(body, "text/plain");
  5700. })
  5701. .Patch("/patch-loopback",
  5702. [&](const Request &, Response &res,
  5703. ContentReader const &content_reader) {
  5704. std::string body;
  5705. content_reader([&](const char *data, size_t data_length) {
  5706. body.append(data, data_length);
  5707. return true;
  5708. });
  5709. res.set_content(body, "text/plain");
  5710. })
  5711. .Put("/empty-no-content-type",
  5712. [&](const Request &req, Response &res) {
  5713. EXPECT_EQ(req.body, "");
  5714. EXPECT_FALSE(req.has_header("Content-Type"));
  5715. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5716. res.set_content("empty-no-content-type", "text/plain");
  5717. })
  5718. .Put("/put",
  5719. [&](const Request &req, Response &res) {
  5720. EXPECT_EQ(req.body, "PUT");
  5721. res.set_content(req.body, "text/plain");
  5722. })
  5723. .Put("/put-large",
  5724. [&](const Request &req, Response &res) {
  5725. EXPECT_EQ(req.body, LARGE_DATA);
  5726. res.set_content(req.body, "text/plain");
  5727. })
  5728. .Patch("/patch",
  5729. [&](const Request &req, Response &res) {
  5730. EXPECT_EQ(req.body, "PATCH");
  5731. res.set_content(req.body, "text/plain");
  5732. })
  5733. .Delete("/delete",
  5734. [&](const Request & /*req*/, Response &res) {
  5735. res.set_content("DELETE", "text/plain");
  5736. })
  5737. .Delete("/delete-body",
  5738. [&](const Request &req, Response &res) {
  5739. EXPECT_EQ(req.body, "content");
  5740. res.set_content(req.body, "text/plain");
  5741. })
  5742. .Options(R"(\*)",
  5743. [&](const Request & /*req*/, Response &res) {
  5744. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5745. })
  5746. .CustomRoute("PROPFIND", "/dav/:id",
  5747. [&](const Request &req, Response &res) {
  5748. res.set_header("x-body-size",
  5749. std::to_string(req.body.size()));
  5750. res.set_header("x-matched-route", req.matched_route);
  5751. res.set_header("x-dav-id", req.path_params.at("id"));
  5752. res.status = StatusCode::MultiStatus_207;
  5753. res.set_content(req.body, "application/xml");
  5754. })
  5755. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5756. [&](const Request &req, Response &res) {
  5757. res.set_header("x-dav-match", req.matches[1]);
  5758. res.status = StatusCode::MultiStatus_207;
  5759. })
  5760. .CustomRoute("MKCOL", "/dav-mkcol",
  5761. [&](const Request &req, Response &res) {
  5762. EXPECT_TRUE(req.body.empty());
  5763. res.status = StatusCode::Created_201;
  5764. })
  5765. .CustomRoute(
  5766. "REPORT", "/dav-report",
  5767. [&](const Request & /*req*/, Response &res,
  5768. const ContentReader &content_reader) {
  5769. std::string body;
  5770. content_reader([&](const char *data, size_t data_length) {
  5771. body.append(data, data_length);
  5772. return true;
  5773. });
  5774. res.set_header("x-body-size", std::to_string(body.size()));
  5775. res.status = StatusCode::MultiStatus_207;
  5776. res.set_content(body, "application/xml");
  5777. })
  5778. .Get("/request-target",
  5779. [&](const Request &req, Response & /*res*/) {
  5780. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5781. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5782. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5783. })
  5784. .Get("/long-query-value",
  5785. [&](const Request &req, Response & /*res*/) {
  5786. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5787. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5788. })
  5789. .Get("/too-long-query-value",
  5790. [&](const Request &req, Response & /*res*/) {
  5791. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5792. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5793. })
  5794. .Get("/array-param",
  5795. [&](const Request &req, Response & /*res*/) {
  5796. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5797. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5798. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5799. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5800. })
  5801. .Get("/array-param-values",
  5802. [&](const Request &req, Response & /*res*/) {
  5803. auto values = req.get_param_values("array");
  5804. EXPECT_EQ(3u, values.size());
  5805. EXPECT_EQ("value1", values[0]);
  5806. EXPECT_EQ("value2", values[1]);
  5807. EXPECT_EQ("value3", values[2]);
  5808. auto empty = req.get_param_values("nonexistent");
  5809. EXPECT_TRUE(empty.empty());
  5810. })
  5811. .Post("/validate-no-multiple-headers",
  5812. [&](const Request &req, Response & /*res*/) {
  5813. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5814. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5815. })
  5816. .Post("/content_receiver",
  5817. [&](const Request &req, Response &res,
  5818. const ContentReader &content_reader) {
  5819. if (req.is_multipart_form_data()) {
  5820. std::vector<FormData> items;
  5821. content_reader(
  5822. [&](const FormData &file) {
  5823. items.push_back(file);
  5824. return true;
  5825. },
  5826. [&](const char *data, size_t data_length) {
  5827. items.back().content.append(data, data_length);
  5828. return true;
  5829. });
  5830. EXPECT_EQ(5u, items.size());
  5831. {
  5832. const auto &file = get_file_value(items, "text1");
  5833. EXPECT_TRUE(file.filename.empty());
  5834. EXPECT_EQ("text default", file.content);
  5835. }
  5836. {
  5837. const auto &file = get_file_value(items, "text2");
  5838. EXPECT_TRUE(file.filename.empty());
  5839. EXPECT_EQ("aωb", file.content);
  5840. }
  5841. {
  5842. const auto &file = get_file_value(items, "file1");
  5843. EXPECT_EQ("hello.txt", file.filename);
  5844. EXPECT_EQ("text/plain", file.content_type);
  5845. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5846. }
  5847. {
  5848. const auto &file = get_file_value(items, "file2");
  5849. EXPECT_EQ("world.json", file.filename);
  5850. EXPECT_EQ("application/json", file.content_type);
  5851. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5852. }
  5853. {
  5854. const auto &file = get_file_value(items, "file3");
  5855. EXPECT_TRUE(file.filename.empty());
  5856. EXPECT_EQ("application/octet-stream", file.content_type);
  5857. EXPECT_EQ(0u, file.content.size());
  5858. }
  5859. } else {
  5860. std::string body;
  5861. content_reader([&](const char *data, size_t data_length) {
  5862. EXPECT_EQ(7U, data_length);
  5863. body.append(data, data_length);
  5864. return true;
  5865. });
  5866. EXPECT_EQ(body, "content");
  5867. res.set_content(body, "text/plain");
  5868. }
  5869. })
  5870. .Put("/content_receiver",
  5871. [&](const Request & /*req*/, Response &res,
  5872. const ContentReader &content_reader) {
  5873. std::string body;
  5874. content_reader([&](const char *data, size_t data_length) {
  5875. body.append(data, data_length);
  5876. return true;
  5877. });
  5878. EXPECT_EQ(body, "content");
  5879. res.set_content(body, "text/plain");
  5880. })
  5881. .Patch("/content_receiver",
  5882. [&](const Request & /*req*/, Response &res,
  5883. const ContentReader &content_reader) {
  5884. std::string body;
  5885. content_reader([&](const char *data, size_t data_length) {
  5886. body.append(data, data_length);
  5887. return true;
  5888. });
  5889. EXPECT_EQ(body, "content");
  5890. res.set_content(body, "text/plain");
  5891. })
  5892. .Post("/query-string-and-body",
  5893. [&](const Request &req, Response & /*res*/) {
  5894. ASSERT_TRUE(req.has_param("key"));
  5895. EXPECT_EQ(req.get_param_value("key"), "value");
  5896. EXPECT_EQ(req.body, "content");
  5897. })
  5898. .Get("/last-request",
  5899. [&](const Request &req, Response & /*res*/) {
  5900. EXPECT_EQ("close", req.get_header_value("Connection"));
  5901. })
  5902. .Get(R"(/redirect/(\d+))",
  5903. [&](const Request &req, Response &res) {
  5904. auto num = std::stoi(req.matches[1]) + 1;
  5905. std::string url = "/redirect/" + std::to_string(num);
  5906. res.set_redirect(url);
  5907. })
  5908. .Post("/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. .Put("/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. .Patch("/binary",
  5925. [&](const Request &req, Response &res) {
  5926. EXPECT_EQ(4U, req.body.size());
  5927. EXPECT_EQ("application/octet-stream",
  5928. req.get_header_value("Content-Type"));
  5929. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5930. res.set_content(req.body, "application/octet-stream");
  5931. })
  5932. .Delete("/binary",
  5933. [&](const Request &req, Response &res) {
  5934. EXPECT_EQ(4U, req.body.size());
  5935. EXPECT_EQ("application/octet-stream",
  5936. req.get_header_value("Content-Type"));
  5937. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5938. res.set_content(req.body, "application/octet-stream");
  5939. })
  5940. .Get("/issue1772",
  5941. [&](const Request & /*req*/, Response &res) {
  5942. res.status = 401;
  5943. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5944. })
  5945. .Delete("/issue609",
  5946. [](const httplib::Request &, httplib::Response &res,
  5947. const httplib::ContentReader &) {
  5948. res.set_content("ok", "text/plain");
  5949. })
  5950. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5951. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5952. .Get("/compress",
  5953. [&](const Request & /*req*/, Response &res) {
  5954. res.set_content(
  5955. "12345678901234567890123456789012345678901234567890123456789"
  5956. "01234567890123456789012345678901234567890",
  5957. "text/plain");
  5958. })
  5959. .Get("/compress-with-charset",
  5960. [&](const Request & /*req*/, Response &res) {
  5961. res.set_content(
  5962. "12345678901234567890123456789012345678901234567890123456789"
  5963. "01234567890123456789012345678901234567890",
  5964. "application/json; charset=utf-8");
  5965. })
  5966. .Get("/nocompress",
  5967. [&](const Request & /*req*/, Response &res) {
  5968. res.set_content(
  5969. "12345678901234567890123456789012345678901234567890123456789"
  5970. "01234567890123456789012345678901234567890",
  5971. "application/octet-stream");
  5972. })
  5973. .Post("/compress-multipart",
  5974. [&](const Request &req, Response & /*res*/) {
  5975. EXPECT_EQ(2u, req.form.fields.size());
  5976. ASSERT_TRUE(!req.form.has_field("???"));
  5977. {
  5978. const auto &text = req.form.get_field("key1");
  5979. EXPECT_EQ("test", text);
  5980. }
  5981. {
  5982. const auto &text = req.form.get_field("key2");
  5983. EXPECT_EQ("--abcdefg123", text);
  5984. }
  5985. })
  5986. #endif
  5987. ;
  5988. persons_["john"] = "programmer";
  5989. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5990. svr_.wait_until_ready();
  5991. }
  5992. virtual void TearDown() {
  5993. svr_.stop();
  5994. if (!request_threads_.empty()) {
  5995. std::this_thread::sleep_for(std::chrono::seconds(1));
  5996. for (auto &t : request_threads_) {
  5997. t.join();
  5998. }
  5999. }
  6000. t_.join();
  6001. }
  6002. map<string, string> persons_;
  6003. #ifdef CPPHTTPLIB_SSL_ENABLED
  6004. SSLClient cli_;
  6005. SSLServer svr_;
  6006. #else
  6007. Client cli_;
  6008. Server svr_;
  6009. #endif
  6010. thread t_;
  6011. std::vector<thread> request_threads_;
  6012. };
  6013. TEST_F(ServerTest, GetMethod200) {
  6014. auto res = cli_.Get("/hi");
  6015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6016. EXPECT_EQ("HTTP/1.1", res->version);
  6017. EXPECT_EQ(StatusCode::OK_200, res->status);
  6018. EXPECT_EQ("OK", res->reason);
  6019. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6020. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6021. EXPECT_EQ("Hello World!", res->body);
  6022. }
  6023. TEST_F(ServerTest, GetEmptyFile) {
  6024. auto res = cli_.Get("/empty_file");
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::OK_200, res->status);
  6027. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6028. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6029. EXPECT_EQ("", res->body);
  6030. }
  6031. TEST_F(ServerTest, GetFileContent) {
  6032. auto res = cli_.Get("/file_content");
  6033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6034. EXPECT_EQ(StatusCode::OK_200, res->status);
  6035. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6036. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6037. EXPECT_EQ("test.html", res->body);
  6038. }
  6039. TEST_F(ServerTest, GetFileContentWithRange) {
  6040. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6042. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6043. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6044. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6045. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6046. EXPECT_EQ("est", res->body);
  6047. }
  6048. TEST_F(ServerTest, GetFileContentWithContentType) {
  6049. auto res = cli_.Get("/file_content_with_content_type");
  6050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6051. EXPECT_EQ(StatusCode::OK_200, res->status);
  6052. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6053. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6054. EXPECT_EQ("file\n", res->body);
  6055. }
  6056. TEST_F(ServerTest, GetInvalidFileContent) {
  6057. auto res = cli_.Get("/invalid_file_content");
  6058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6059. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6060. }
  6061. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6062. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ("HTTP/1.1", res->version);
  6065. EXPECT_EQ(StatusCode::OK_200, res->status);
  6066. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6067. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6068. EXPECT_EQ("Hello World!", res->body);
  6069. }
  6070. TEST_F(ServerTest, GetMethod302) {
  6071. auto res = cli_.Get("/");
  6072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6073. EXPECT_EQ(StatusCode::Found_302, res->status);
  6074. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6075. }
  6076. TEST_F(ServerTest, GetMethod302Redirect) {
  6077. cli_.set_follow_location(true);
  6078. auto res = cli_.Get("/");
  6079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6080. EXPECT_EQ(StatusCode::OK_200, res->status);
  6081. EXPECT_EQ("Hello World!", res->body);
  6082. EXPECT_EQ("/hi", res->location);
  6083. }
  6084. TEST_F(ServerTest, GetMethod404) {
  6085. auto res = cli_.Get("/invalid");
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6088. }
  6089. TEST_F(ServerTest, HeadMethod200) {
  6090. auto res = cli_.Head("/hi");
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::OK_200, res->status);
  6093. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6094. EXPECT_TRUE(res->body.empty());
  6095. }
  6096. TEST_F(ServerTest, HeadMethod200Static) {
  6097. auto res = cli_.Head("/mount/dir/index.html");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::OK_200, res->status);
  6100. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6101. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6102. EXPECT_TRUE(res->body.empty());
  6103. }
  6104. TEST_F(ServerTest, HeadMethod404) {
  6105. auto res = cli_.Head("/invalid");
  6106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6107. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6108. EXPECT_TRUE(res->body.empty());
  6109. }
  6110. TEST_F(ServerTest, GetMethodPersonJohn) {
  6111. auto res = cli_.Get("/person/john");
  6112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6113. EXPECT_EQ(StatusCode::OK_200, res->status);
  6114. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6115. EXPECT_EQ("programmer", res->body);
  6116. }
  6117. TEST_F(ServerTest, PostMethod1) {
  6118. auto res = cli_.Get("/person/john1");
  6119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6120. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6121. res = cli_.Post("/person", "name=john1&note=coder",
  6122. "application/x-www-form-urlencoded");
  6123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6124. ASSERT_EQ(StatusCode::OK_200, res->status);
  6125. res = cli_.Get("/person/john1");
  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, PostMethod2) {
  6132. auto res = cli_.Get("/person/john2");
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6135. Params params;
  6136. params.emplace("name", "john2");
  6137. params.emplace("note", "coder");
  6138. res = cli_.Post("/person", params);
  6139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6140. ASSERT_EQ(StatusCode::OK_200, res->status);
  6141. res = cli_.Get("/person/john2");
  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, PutMethod3) {
  6148. auto res = cli_.Get("/person/john3");
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6151. Params params;
  6152. params.emplace("name", "john3");
  6153. params.emplace("note", "coder");
  6154. res = cli_.Put("/person", params);
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. ASSERT_EQ(StatusCode::OK_200, res->status);
  6157. res = cli_.Get("/person/john3");
  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. }
  6163. TEST_F(ServerTest, DeleteMethod1) {
  6164. auto res = cli_.Get("/person/john4");
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6167. Params params;
  6168. params.emplace("name", "john4");
  6169. params.emplace("note", "coder");
  6170. res = cli_.Post("/person", params);
  6171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6172. ASSERT_EQ(StatusCode::OK_200, res->status);
  6173. res = cli_.Get("/person/john4");
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. ASSERT_EQ(StatusCode::OK_200, res->status);
  6176. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6177. ASSERT_EQ("coder", res->body);
  6178. Params delete_params;
  6179. delete_params.emplace("name", "john4");
  6180. res = cli_.Delete("/person", delete_params);
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. ASSERT_EQ(StatusCode::OK_200, res->status);
  6183. ASSERT_EQ("DELETED", res->body);
  6184. res = cli_.Get("/person/john4");
  6185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6186. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6187. }
  6188. TEST_F(ServerTest, DeleteMethod2) {
  6189. auto res = cli_.Get("/person/john5");
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6192. Params params;
  6193. params.emplace("name", "john5");
  6194. params.emplace("note", "developer");
  6195. res = cli_.Post("/person", params);
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. ASSERT_EQ(StatusCode::OK_200, res->status);
  6198. res = cli_.Get("/person/john5");
  6199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6200. ASSERT_EQ(StatusCode::OK_200, res->status);
  6201. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6202. ASSERT_EQ("developer", res->body);
  6203. Params delete_params;
  6204. delete_params.emplace("name", "john5");
  6205. Headers headers;
  6206. headers.emplace("Custom-Header", "test-value");
  6207. res = cli_.Delete("/person", headers, delete_params);
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. ASSERT_EQ(StatusCode::OK_200, res->status);
  6210. ASSERT_EQ("DELETED", res->body);
  6211. res = cli_.Get("/person/john5");
  6212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6213. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6214. }
  6215. TEST_F(ServerTest, DeleteMethod3) {
  6216. auto res = cli_.Get("/person/john6");
  6217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6218. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6219. Params params;
  6220. params.emplace("name", "john6");
  6221. params.emplace("note", "tester");
  6222. res = cli_.Post("/person", params);
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. ASSERT_EQ(StatusCode::OK_200, res->status);
  6225. res = cli_.Get("/person/john6");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. ASSERT_EQ(StatusCode::OK_200, res->status);
  6228. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6229. ASSERT_EQ("tester", res->body);
  6230. Params delete_params;
  6231. delete_params.emplace("name", "john6");
  6232. Headers headers;
  6233. headers.emplace("Custom-Header", "test-value");
  6234. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6236. ASSERT_EQ(StatusCode::OK_200, res->status);
  6237. ASSERT_EQ("DELETED", res->body);
  6238. res = cli_.Get("/person/john6");
  6239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6240. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6241. }
  6242. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6243. Params params;
  6244. params.emplace("json", JSON_DATA);
  6245. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. ASSERT_EQ(StatusCode::OK_200, res->status);
  6248. ASSERT_EQ(JSON_DATA, res->body);
  6249. }
  6250. TEST_F(ServerTest, PostEmptyContent) {
  6251. auto res = cli_.Post("/empty", "", "text/plain");
  6252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6253. ASSERT_EQ(StatusCode::OK_200, res->status);
  6254. ASSERT_EQ("empty", res->body);
  6255. }
  6256. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6257. auto res = cli_.Post("/empty-no-content-type");
  6258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6259. ASSERT_EQ(StatusCode::OK_200, res->status);
  6260. ASSERT_EQ("empty-no-content-type", res->body);
  6261. }
  6262. TEST_F(ServerTest, PostPathOnly) {
  6263. auto res = cli_.Post("/path-only");
  6264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6265. ASSERT_EQ(StatusCode::OK_200, res->status);
  6266. ASSERT_EQ("path-only", res->body);
  6267. }
  6268. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6269. auto res = cli_.Post("/path-headers-only",
  6270. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. ASSERT_EQ(StatusCode::OK_200, res->status);
  6273. ASSERT_EQ("path-headers-only", res->body);
  6274. }
  6275. TEST_F(ServerTest, PostLarge) {
  6276. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6278. ASSERT_EQ(StatusCode::OK_200, res->status);
  6279. EXPECT_EQ(LARGE_DATA, res->body);
  6280. }
  6281. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6282. auto res = cli_.Put("/empty-no-content-type");
  6283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6284. ASSERT_EQ(StatusCode::OK_200, res->status);
  6285. ASSERT_EQ("empty-no-content-type", res->body);
  6286. }
  6287. TEST_F(ServerTest, GetMethodDir) {
  6288. auto res = cli_.Get("/dir/");
  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. auto body = R"(<html>
  6293. <head>
  6294. </head>
  6295. <body>
  6296. <a href="/dir/test.html">Test</a>
  6297. <a href="/hi">hi</a>
  6298. </body>
  6299. </html>
  6300. )";
  6301. EXPECT_EQ(body, res->body);
  6302. }
  6303. TEST_F(ServerTest, GetMethodDirTest) {
  6304. auto res = cli_.Get("/dir/test.html");
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. EXPECT_EQ(StatusCode::OK_200, res->status);
  6307. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6308. EXPECT_EQ("test.html", res->body);
  6309. }
  6310. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6311. auto res = cli_.Get("/dir/../dir/test.html");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::OK_200, res->status);
  6314. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6315. EXPECT_EQ("test.html", res->body);
  6316. }
  6317. TEST_F(ServerTest, GetMethodInvalidPath) {
  6318. auto res = cli_.Get("/dir/../test.html");
  6319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6320. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6321. }
  6322. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6323. auto res = cli_.Get("/../www/dir/test.html");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6326. }
  6327. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6328. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6331. }
  6332. TEST_F(ServerTest, GetMethodDirMountTest) {
  6333. auto res = cli_.Get("/mount/dir/test.html");
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::OK_200, res->status);
  6336. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6337. EXPECT_EQ("test.html", res->body);
  6338. }
  6339. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6340. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6342. EXPECT_EQ(StatusCode::OK_200, res->status);
  6343. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6344. EXPECT_EQ("test.html", res->body);
  6345. }
  6346. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6347. auto res = cli_.Get("/mount/dir/../test.html");
  6348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6349. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6350. }
  6351. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6352. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6354. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6355. }
  6356. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6357. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6359. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6360. }
  6361. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6362. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6365. }
  6366. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6367. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6370. }
  6371. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6372. auto res = cli_.Get("/mount/dir");
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6375. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6376. }
  6377. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6378. auto res = cli_.Get("//dir");
  6379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6380. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6381. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6382. }
  6383. TEST_F(ServerTest, PostMethod303) {
  6384. auto res = cli_.Post("/1", "body", "text/plain");
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6387. EXPECT_EQ("/2", res->get_header_value("Location"));
  6388. }
  6389. TEST_F(ServerTest, PostMethod303Redirect) {
  6390. cli_.set_follow_location(true);
  6391. auto res = cli_.Post("/1", "body", "text/plain");
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::OK_200, res->status);
  6394. EXPECT_EQ("redirected.", res->body);
  6395. EXPECT_EQ("/2", res->location);
  6396. }
  6397. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6398. auto res = cli_.Get("/dir/test.abcde");
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::OK_200, res->status);
  6401. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6402. EXPECT_EQ("abcde", res->body);
  6403. }
  6404. TEST_F(ServerTest, StaticFileRange) {
  6405. auto res =
  6406. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6408. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6409. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6410. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6411. EXPECT_EQ(true, res->has_header("Content-Range"));
  6412. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6413. EXPECT_EQ(std::string("cd"), res->body);
  6414. }
  6415. TEST_F(ServerTest, StaticFileRanges) {
  6416. auto res = cli_.Get("/dir/test.abcde",
  6417. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6419. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6420. EXPECT_TRUE(
  6421. res->get_header_value("Content-Type")
  6422. .find(
  6423. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6424. 0);
  6425. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6426. }
  6427. TEST_F(ServerTest, StaticFileRangeHead) {
  6428. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6431. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6432. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6433. EXPECT_EQ(true, res->has_header("Content-Range"));
  6434. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6435. }
  6436. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6437. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6439. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6440. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6441. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6442. EXPECT_EQ(true, res->has_header("Content-Range"));
  6443. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6444. res->get_header_value("Content-Range"));
  6445. EXPECT_EQ("LAST\n", res->body);
  6446. }
  6447. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6448. auto res =
  6449. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6452. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6453. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6454. EXPECT_EQ(true, res->has_header("Content-Range"));
  6455. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6456. }
  6457. TEST_F(ServerTest, StaticFileBigFile) {
  6458. auto res = cli_.Get("/dir/1MB.txt");
  6459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6460. EXPECT_EQ(StatusCode::OK_200, res->status);
  6461. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6462. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6463. }
  6464. TEST_F(ServerTest, InvalidBaseDirMount) {
  6465. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6466. }
  6467. TEST_F(ServerTest, Binary) {
  6468. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6469. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6470. "application/octet-stream");
  6471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6472. ASSERT_EQ(StatusCode::OK_200, res->status);
  6473. ASSERT_EQ(4U, res->body.size());
  6474. res = cli_.Put("/binary", binary.data(), binary.size(),
  6475. "application/octet-stream");
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. ASSERT_EQ(StatusCode::OK_200, res->status);
  6478. ASSERT_EQ(4U, res->body.size());
  6479. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6480. "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_.Delete("/binary", binary.data(), binary.size(),
  6485. "application/octet-stream");
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. ASSERT_EQ(StatusCode::OK_200, res->status);
  6488. ASSERT_EQ(4U, res->body.size());
  6489. }
  6490. TEST_F(ServerTest, BinaryString) {
  6491. auto binary = std::string("\x00\x01\x02\x03", 4);
  6492. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6494. ASSERT_EQ(StatusCode::OK_200, res->status);
  6495. ASSERT_EQ(4U, res->body.size());
  6496. res = cli_.Put("/binary", binary, "application/octet-stream");
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. ASSERT_EQ(StatusCode::OK_200, res->status);
  6499. ASSERT_EQ(4U, res->body.size());
  6500. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6502. ASSERT_EQ(StatusCode::OK_200, res->status);
  6503. ASSERT_EQ(4U, res->body.size());
  6504. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. ASSERT_EQ(StatusCode::OK_200, res->status);
  6507. ASSERT_EQ(4U, res->body.size());
  6508. }
  6509. TEST_F(ServerTest, EmptyRequest) {
  6510. auto res = cli_.Get("");
  6511. ASSERT_TRUE(!res);
  6512. EXPECT_EQ(Error::Connection, res.error());
  6513. }
  6514. TEST_F(ServerTest, LongRequest) {
  6515. std::string request;
  6516. for (size_t i = 0; i < 545; i++) {
  6517. request += "/TooLongRequest";
  6518. }
  6519. request += "OK";
  6520. auto res = cli_.Get(request.c_str());
  6521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6523. }
  6524. TEST_F(ServerTest, TooLongRequest) {
  6525. std::string request;
  6526. for (size_t i = 0; i < 546; i++) {
  6527. request += "/TooLongRequest";
  6528. }
  6529. request += "_NG";
  6530. auto start = std::chrono::high_resolution_clock::now();
  6531. cli_.set_keep_alive(true);
  6532. auto res = cli_.Get(request.c_str());
  6533. auto end = std::chrono::high_resolution_clock::now();
  6534. auto elapsed =
  6535. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6536. .count();
  6537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6538. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6539. EXPECT_LE(elapsed, 1000);
  6540. EXPECT_EQ("close", res->get_header_value("Connection"));
  6541. EXPECT_FALSE(cli_.is_socket_open());
  6542. }
  6543. TEST_F(ServerTest, AlmostTooLongRequest) {
  6544. // test for #2046 - URI length check shouldn't include other content on req
  6545. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6546. // leading /, space, HTTP/1.1)
  6547. std::string request =
  6548. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6549. auto res = cli_.Get(request.c_str());
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6552. }
  6553. TEST_F(ServerTest, LongHeader) {
  6554. Request req;
  6555. req.method = "GET";
  6556. req.path = "/hi";
  6557. std::string host_and_port;
  6558. host_and_port += HOST;
  6559. host_and_port += ":";
  6560. host_and_port += std::to_string(PORT);
  6561. req.headers.emplace("Host", host_and_port.c_str());
  6562. req.headers.emplace("Accept", "*/*");
  6563. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6564. req.headers.emplace(
  6565. "Header-Name",
  6566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6578. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6579. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6594. "@@@@@@@@@@@@@@@@");
  6595. auto res = std::make_shared<Response>();
  6596. auto error = Error::Success;
  6597. auto ret = cli_.send(req, *res, error);
  6598. ASSERT_TRUE(ret);
  6599. EXPECT_EQ(StatusCode::OK_200, res->status);
  6600. }
  6601. TEST_F(ServerTest, LongQueryValue) {
  6602. auto start = std::chrono::high_resolution_clock::now();
  6603. cli_.set_keep_alive(true);
  6604. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6605. auto end = std::chrono::high_resolution_clock::now();
  6606. auto elapsed =
  6607. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6608. .count();
  6609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6610. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6611. EXPECT_LE(elapsed, 1000);
  6612. EXPECT_EQ("close", res->get_header_value("Connection"));
  6613. EXPECT_FALSE(cli_.is_socket_open());
  6614. }
  6615. TEST_F(ServerTest, TooLongQueryValue) {
  6616. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6617. ASSERT_FALSE(res);
  6618. EXPECT_EQ(Error::Read, res.error());
  6619. }
  6620. TEST_F(ServerTest, TooLongHeader) {
  6621. Request req;
  6622. req.method = "GET";
  6623. req.path = "/hi";
  6624. std::string host_and_port;
  6625. host_and_port += HOST;
  6626. host_and_port += ":";
  6627. host_and_port += std::to_string(PORT);
  6628. req.headers.emplace("Host", host_and_port.c_str());
  6629. req.headers.emplace("Accept", "*/*");
  6630. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6631. req.headers.emplace(
  6632. "Header-Name",
  6633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6657. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6661. "@@@@@@@@@@@@@@@@@");
  6662. auto res = std::make_shared<Response>();
  6663. auto error = Error::Success;
  6664. auto ret = cli_.send(req, *res, error);
  6665. ASSERT_TRUE(ret);
  6666. EXPECT_EQ(StatusCode::OK_200, res->status);
  6667. }
  6668. TEST_F(ServerTest, HeaderCountAtLimit) {
  6669. // Test with headers just under the 100 limit
  6670. httplib::Headers headers;
  6671. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6672. // This should keep us just under the 100 header limit
  6673. for (int i = 0; i < 95; i++) {
  6674. std::string name = "X-Test-Header-" + std::to_string(i);
  6675. std::string value = "value" + std::to_string(i);
  6676. headers.emplace(name, value);
  6677. }
  6678. // This should work fine as we're under the limit
  6679. auto res = cli_.Get("/hi", headers);
  6680. EXPECT_TRUE(res);
  6681. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6682. }
  6683. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6684. // Test with many headers to exceed the 100 limit
  6685. httplib::Headers headers;
  6686. // Add 150 headers to definitely exceed the 100 limit
  6687. for (int i = 0; i < 150; i++) {
  6688. std::string name = "X-Test-Header-" + std::to_string(i);
  6689. std::string value = "value" + std::to_string(i);
  6690. headers.emplace(name, value);
  6691. }
  6692. // This should fail due to exceeding header count limit
  6693. cli_.set_keep_alive(true);
  6694. auto res = cli_.Get("/hi", headers);
  6695. // The server should respond with 400 Bad Request
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6698. EXPECT_EQ("close", res->get_header_value("Connection"));
  6699. EXPECT_FALSE(cli_.is_socket_open());
  6700. }
  6701. TEST_F(ServerTest, PercentEncoding) {
  6702. auto res = cli_.Get("/e%6edwith%");
  6703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6704. EXPECT_EQ(StatusCode::OK_200, res->status);
  6705. }
  6706. TEST_F(ServerTest, PercentEncodingUnicode) {
  6707. auto res = cli_.Get("/e%u006edwith%");
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::OK_200, res->status);
  6710. }
  6711. TEST_F(ServerTest, InvalidPercentEncoding) {
  6712. auto res = cli_.Get("/%endwith%");
  6713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6715. }
  6716. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6717. auto res = cli_.Get("/%uendwith%");
  6718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6719. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6720. }
  6721. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6722. auto res = cli_.Get("/hello?aaa=bbb%");
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6725. }
  6726. TEST_F(ServerTest, PlusSignEncoding) {
  6727. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6729. EXPECT_EQ(StatusCode::OK_200, res->status);
  6730. EXPECT_EQ("a +b", res->body);
  6731. }
  6732. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6733. // This test simulates a potential DoS attack using many headers
  6734. // to verify our security fix prevents memory exhaustion
  6735. httplib::Headers attack_headers;
  6736. // Attempt to add many headers like an attacker would (200 headers to far
  6737. // exceed limit)
  6738. for (int i = 0; i < 200; i++) {
  6739. std::string name = "X-Attack-Header-" + std::to_string(i);
  6740. std::string value = "attack_payload_" + std::to_string(i);
  6741. attack_headers.emplace(name, value);
  6742. }
  6743. // Try to POST with excessive headers
  6744. cli_.set_keep_alive(true);
  6745. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6746. // Should either fail or return 400 Bad Request due to security limit
  6747. if (res) {
  6748. // If we get a response, it should be 400 Bad Request
  6749. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6750. EXPECT_EQ("close", res->get_header_value("Connection"));
  6751. }
  6752. EXPECT_FALSE(cli_.is_socket_open());
  6753. }
  6754. TEST_F(ServerTest, MultipartFormData) {
  6755. UploadFormDataItems items = {
  6756. {"text1", "text default", "", ""},
  6757. {"text2", "aωb", "", ""},
  6758. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6759. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6760. {"file3", "", "", "application/octet-stream"},
  6761. {"file4", "", "", " application/json tmp-string "}};
  6762. auto res = cli_.Post("/multipart", items);
  6763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6764. EXPECT_EQ(StatusCode::OK_200, res->status);
  6765. }
  6766. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6767. UploadFormDataItems items = {
  6768. {"text", "default text", "", ""},
  6769. {"multi_text1", "aaaaa", "", ""},
  6770. {"multi_text1", "bbbbb", "", ""},
  6771. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6772. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6773. "application/json"},
  6774. };
  6775. auto res = cli_.Post("/multipart/multi_file_values", items);
  6776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6777. EXPECT_EQ(StatusCode::OK_200, res->status);
  6778. }
  6779. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6780. auto res = cli_.Get("/hi");
  6781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6782. EXPECT_EQ(StatusCode::OK_200, res->status);
  6783. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6784. EXPECT_EQ("Hello World!", res->body);
  6785. }
  6786. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6787. Request req;
  6788. req.method = "POST";
  6789. req.path = "/chunked";
  6790. std::string host_and_port;
  6791. host_and_port += HOST;
  6792. host_and_port += ":";
  6793. host_and_port += std::to_string(PORT);
  6794. req.headers.emplace("Host", host_and_port.c_str());
  6795. req.headers.emplace("Accept", "*/*");
  6796. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6797. req.headers.emplace("Content-Type", "text/plain");
  6798. req.headers.emplace("Content-Length", "0");
  6799. req.headers.emplace(
  6800. "Transfer-Encoding",
  6801. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6802. // Client does not chunk, so make a chunked body manually.
  6803. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6804. auto res = std::make_shared<Response>();
  6805. auto error = Error::Success;
  6806. auto ret = cli_.send(req, *res, error);
  6807. ASSERT_TRUE(ret);
  6808. EXPECT_EQ(StatusCode::OK_200, res->status);
  6809. }
  6810. template <typename ClientT>
  6811. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6812. int expected_status) {
  6813. Request req;
  6814. req.method = "POST";
  6815. req.path = "/chunked";
  6816. std::string host_and_port;
  6817. host_and_port += HOST;
  6818. host_and_port += ":";
  6819. host_and_port += std::to_string(PORT);
  6820. req.headers.emplace("Host", host_and_port.c_str());
  6821. req.headers.emplace("Content-Length", "0");
  6822. req.headers.emplace("Transfer-Encoding", "chunked");
  6823. req.body = body;
  6824. auto res = std::make_shared<Response>();
  6825. auto error = Error::Success;
  6826. ASSERT_TRUE(cli.send(req, *res, error));
  6827. EXPECT_EQ(expected_status, res->status);
  6828. }
  6829. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6830. // rather than treat them as valid lengths.
  6831. template <typename ClientT>
  6832. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6833. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6834. }
  6835. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6836. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6837. }
  6838. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6839. expect_chunked_body_rejected(
  6840. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6841. }
  6842. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6843. // chunk-size line carries no CR, LF or other control character ahead of its
  6844. // terminator. Such a line must be refused rather than read as extension text.
  6845. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6846. expect_chunked_body_rejected(
  6847. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6848. }
  6849. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6850. expect_chunked_body_rejected(
  6851. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6852. }
  6853. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6854. expect_chunked_body_rejected(
  6855. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6856. }
  6857. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6858. // The literal stays split: a hex escape consumes every hex digit that
  6859. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6860. expect_chunked_body_rejected(
  6861. cli_, "4;a\x01"
  6862. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6863. }
  6864. TEST_F(ServerTest, AcceptsChunkExtension) {
  6865. expect_chunked_body_status(cli_,
  6866. "4;name=value\r\ndech\r\n"
  6867. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6868. "0;last\r\n\r\n",
  6869. StatusCode::OK_200);
  6870. }
  6871. TEST_F(ServerTest, GetStreamed2) {
  6872. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6874. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6875. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6876. EXPECT_EQ(true, res->has_header("Content-Range"));
  6877. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6878. EXPECT_EQ(std::string("ab"), res->body);
  6879. }
  6880. TEST_F(ServerTest, GetStreamed) {
  6881. auto res = cli_.Get("/streamed");
  6882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6883. EXPECT_EQ(StatusCode::OK_200, res->status);
  6884. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6885. EXPECT_EQ(std::string("aaabbb"), res->body);
  6886. }
  6887. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6888. auto res = cli_.Get("/streamed-without-length",
  6889. Headers{make_range_header({{0, -1}})});
  6890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6891. EXPECT_EQ(StatusCode::OK_200, res->status);
  6892. EXPECT_EQ(false, res->has_header("Content-Length"));
  6893. EXPECT_EQ(false, res->has_header("Content-Range"));
  6894. EXPECT_EQ(std::string("abcdefg"), res->body);
  6895. }
  6896. TEST_F(ServerTest, GetStreamedWithRange1) {
  6897. auto res =
  6898. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6901. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6902. EXPECT_EQ(true, res->has_header("Content-Range"));
  6903. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6904. EXPECT_EQ(std::string("def"), res->body);
  6905. }
  6906. TEST_F(ServerTest, GetStreamedWithRange2) {
  6907. auto res =
  6908. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6910. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6911. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6912. EXPECT_EQ(true, res->has_header("Content-Range"));
  6913. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6914. EXPECT_EQ(std::string("bcdefg"), res->body);
  6915. }
  6916. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6917. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6919. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6920. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6921. EXPECT_EQ(true, res->has_header("Content-Range"));
  6922. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6923. EXPECT_EQ(std::string("efg"), res->body);
  6924. }
  6925. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6926. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6927. // the entire representation.
  6928. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6929. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6932. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6933. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6934. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6935. }
  6936. }
  6937. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6938. auto res =
  6939. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6941. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6942. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6943. EXPECT_EQ(false, res->has_header("Content-Range"));
  6944. EXPECT_EQ(0U, res->body.size());
  6945. }
  6946. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6947. // Only a 206 is served as a partial representation. Under any other status
  6948. // `apply_ranges()` reported the full content length, so the body must match
  6949. // that header, and the content provider must never be asked for an offset
  6950. // outside the representation.
  6951. auto check = [&](int status, const char *range) {
  6952. auto path =
  6953. std::string("/streamed-with-range?status=") + std::to_string(status);
  6954. auto ctx = path + " Range: " + range;
  6955. auto res = cli_.Get(path, Headers{{"Range", range}});
  6956. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6957. EXPECT_EQ(status, res->status) << ctx;
  6958. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6959. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6960. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6961. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6962. };
  6963. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6964. check(403, "bytes=3-5");
  6965. // The offset is far past the representation.
  6966. check(403, "bytes=100000-100200");
  6967. // `first_pos` is still -1 here, and the bounds asserts in
  6968. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6969. check(403, "bytes=-3");
  6970. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6971. // multipart branch would have written one that is empty.
  6972. check(403, "bytes=1-2, 4-5");
  6973. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6974. // covers the whole representation.
  6975. check(200, "bytes=3-5");
  6976. check(200, "bytes=1-2, 4-5");
  6977. }
  6978. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6979. auto res =
  6980. cli_.Get("/streamed-with-range",
  6981. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6982. "92233720368547758079223372036854775807"}});
  6983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6984. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6985. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6986. EXPECT_EQ(false, res->has_header("Content-Range"));
  6987. EXPECT_EQ(0U, res->body.size());
  6988. }
  6989. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6990. auto res = cli_.Get(
  6991. "/with-range",
  6992. Headers{{"Range",
  6993. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6994. {"Accept-Encoding", ""}});
  6995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6996. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6997. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6998. EXPECT_EQ(true, res->has_header("Content-Range"));
  6999. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7000. EXPECT_EQ(std::string("abcdefg"), res->body);
  7001. }
  7002. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7003. auto res = cli_.Get("/with-range", Headers{
  7004. {"Range", "bytes=0-"},
  7005. {"Accept-Encoding", ""},
  7006. });
  7007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7008. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7009. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7010. EXPECT_EQ(true, res->has_header("Content-Range"));
  7011. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7012. EXPECT_EQ(std::string("abcdefg"), res->body);
  7013. }
  7014. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7015. auto res = cli_.Get("/streamed-with-range",
  7016. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7018. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7019. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7020. EXPECT_EQ(false, res->has_header("Content-Range"));
  7021. EXPECT_EQ(267U, res->body.size());
  7022. // Check that both range contents are present
  7023. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7024. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7025. // Check that Content-Range headers are present for both ranges
  7026. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7027. std::string::npos);
  7028. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7029. std::string::npos);
  7030. }
  7031. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7032. Ranges ranges;
  7033. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7034. ranges.emplace_back(0, -1);
  7035. }
  7036. auto res = cli_.Get("/streamed-with-range?error",
  7037. Headers{{make_range_header(ranges)}});
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7040. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7041. EXPECT_EQ(false, res->has_header("Content-Range"));
  7042. EXPECT_EQ(0U, res->body.size());
  7043. }
  7044. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7045. auto res = cli_.Get("/streamed-with-range",
  7046. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7049. EXPECT_EQ(5U, res->body.size());
  7050. // Check that overlapping ranges are coalesced into a single range
  7051. EXPECT_EQ("bcdef", res->body);
  7052. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7053. // Should be single range, not multipart
  7054. EXPECT_TRUE(res->has_header("Content-Range"));
  7055. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7056. }
  7057. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7058. auto res = cli_.Get("/streamed-with-range",
  7059. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7062. EXPECT_EQ(268U, res->body.size());
  7063. // Check that both range contents are present
  7064. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7065. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7066. // Check that Content-Range headers are present for both ranges
  7067. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7068. std::string::npos);
  7069. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7070. std::string::npos);
  7071. }
  7072. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7073. auto res = cli_.Get("/streamed-with-range",
  7074. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7077. EXPECT_EQ(269U, res->body.size());
  7078. // Check that both duplicate range contents are present
  7079. size_t first_abc = res->body.find("abc\r\n");
  7080. EXPECT_TRUE(first_abc != std::string::npos);
  7081. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7082. EXPECT_TRUE(second_abc != std::string::npos);
  7083. // Check that Content-Range headers are present for both ranges
  7084. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7085. EXPECT_TRUE(first_range != std::string::npos);
  7086. size_t second_range =
  7087. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7088. EXPECT_TRUE(second_range != std::string::npos);
  7089. }
  7090. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7091. auto res =
  7092. cli_.Get("/streamed-with-range?error",
  7093. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7096. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7097. EXPECT_EQ(false, res->has_header("Content-Range"));
  7098. EXPECT_EQ(0U, res->body.size());
  7099. }
  7100. TEST_F(ServerTest, GetStreamedEndless) {
  7101. uint64_t offset = 0;
  7102. auto res = cli_.Get("/streamed-cancel",
  7103. [&](const char * /*data*/, uint64_t data_length) {
  7104. if (offset < 100) {
  7105. offset += data_length;
  7106. return true;
  7107. }
  7108. return false;
  7109. });
  7110. ASSERT_TRUE(!res);
  7111. EXPECT_EQ(Error::Canceled, res.error());
  7112. }
  7113. TEST_F(ServerTest, ClientStop) {
  7114. std::atomic_size_t count{4};
  7115. std::vector<std::thread> threads;
  7116. for (auto i = count.load(); i != 0; --i) {
  7117. threads.emplace_back([&]() {
  7118. auto res = cli_.Get("/streamed-cancel",
  7119. [&](const char *, uint64_t) { return true; });
  7120. --count;
  7121. ASSERT_TRUE(!res);
  7122. EXPECT_TRUE(res.error() == Error::Canceled ||
  7123. res.error() == Error::Read || res.error() == Error::Write);
  7124. });
  7125. }
  7126. std::this_thread::sleep_for(std::chrono::seconds(2));
  7127. while (count != 0) {
  7128. cli_.stop();
  7129. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7130. }
  7131. for (auto &t : threads) {
  7132. t.join();
  7133. }
  7134. }
  7135. TEST_F(ServerTest, GetWithRange1) {
  7136. auto res = cli_.Get("/with-range", Headers{
  7137. make_range_header({{3, 5}}),
  7138. {"Accept-Encoding", ""},
  7139. });
  7140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7141. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7142. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7143. EXPECT_EQ(true, res->has_header("Content-Range"));
  7144. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7145. EXPECT_EQ(std::string("def"), res->body);
  7146. }
  7147. TEST_F(ServerTest, GetWithRange2) {
  7148. auto res = cli_.Get("/with-range", Headers{
  7149. make_range_header({{1, -1}}),
  7150. {"Accept-Encoding", ""},
  7151. });
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7154. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7155. EXPECT_EQ(true, res->has_header("Content-Range"));
  7156. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7157. EXPECT_EQ(std::string("bcdefg"), res->body);
  7158. }
  7159. TEST_F(ServerTest, GetWithRange3) {
  7160. auto res = cli_.Get("/with-range", Headers{
  7161. make_range_header({{0, 0}}),
  7162. {"Accept-Encoding", ""},
  7163. });
  7164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7165. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7166. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7167. EXPECT_EQ(true, res->has_header("Content-Range"));
  7168. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7169. EXPECT_EQ(std::string("a"), res->body);
  7170. }
  7171. TEST_F(ServerTest, GetWithRange4) {
  7172. auto res = cli_.Get("/with-range", Headers{
  7173. make_range_header({{-1, 2}}),
  7174. {"Accept-Encoding", ""},
  7175. });
  7176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7177. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7178. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7179. EXPECT_EQ(true, res->has_header("Content-Range"));
  7180. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7181. EXPECT_EQ(std::string("fg"), res->body);
  7182. }
  7183. TEST_F(ServerTest, GetWithRange5) {
  7184. auto res = cli_.Get("/with-range", Headers{
  7185. make_range_header({{0, 5}}),
  7186. {"Accept-Encoding", ""},
  7187. });
  7188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7189. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7190. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7191. EXPECT_EQ(true, res->has_header("Content-Range"));
  7192. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7193. EXPECT_EQ(std::string("abcdef"), res->body);
  7194. }
  7195. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7196. auto res =
  7197. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7199. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7200. }
  7201. TEST_F(ServerTest, GetWithRangeMultipart) {
  7202. auto res =
  7203. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7205. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7206. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7207. EXPECT_EQ(false, res->has_header("Content-Range"));
  7208. EXPECT_EQ(267U, res->body.size());
  7209. }
  7210. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7211. auto res = cli_.Get("/with-range",
  7212. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7214. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7215. }
  7216. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7217. auto res = cli_.Get("/with-range-customized-response",
  7218. Headers{{make_range_header({{1, 2}})}});
  7219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7220. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7221. EXPECT_EQ(true, res->has_header("Content-Length"));
  7222. EXPECT_EQ(false, res->has_header("Content-Range"));
  7223. EXPECT_EQ(JSON_DATA, res->body);
  7224. }
  7225. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7226. auto res = cli_.Get("/with-range-customized-response",
  7227. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7229. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7230. EXPECT_EQ(true, res->has_header("Content-Length"));
  7231. EXPECT_EQ(false, res->has_header("Content-Range"));
  7232. EXPECT_EQ(JSON_DATA, res->body);
  7233. }
  7234. TEST_F(ServerTest, Issue1772) {
  7235. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7237. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7238. }
  7239. TEST_F(ServerTest, Issue609) {
  7240. auto res = cli_.Delete("/issue609");
  7241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7242. EXPECT_EQ(StatusCode::OK_200, res->status);
  7243. EXPECT_EQ(std::string("ok"), res->body);
  7244. }
  7245. TEST_F(ServerTest, GetStreamedChunked) {
  7246. auto res = cli_.Get("/streamed-chunked");
  7247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7248. EXPECT_EQ(StatusCode::OK_200, res->status);
  7249. EXPECT_EQ(std::string("123456789"), res->body);
  7250. }
  7251. TEST_F(ServerTest, GetStreamedChunked2) {
  7252. auto res = cli_.Get("/streamed-chunked2");
  7253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7254. EXPECT_EQ(StatusCode::OK_200, res->status);
  7255. EXPECT_EQ(std::string("123456789"), res->body);
  7256. }
  7257. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7258. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7260. EXPECT_EQ(StatusCode::OK_200, res->status);
  7261. EXPECT_EQ(std::string("123456789"), res->body);
  7262. EXPECT_TRUE(res->has_header("Trailer"));
  7263. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7264. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7265. // Trailers are now stored separately from headers (security fix)
  7266. EXPECT_EQ(2U, res->trailers.size());
  7267. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7268. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7269. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7270. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7271. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7272. // Verify trailers are NOT in headers (security verification)
  7273. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7274. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7275. }
  7276. TEST_F(ServerTest, LargeChunkedPost) {
  7277. Request req;
  7278. req.method = "POST";
  7279. req.path = "/large-chunked";
  7280. std::string host_and_port;
  7281. host_and_port += HOST;
  7282. host_and_port += ":";
  7283. host_and_port += std::to_string(PORT);
  7284. req.headers.emplace("Host", host_and_port.c_str());
  7285. req.headers.emplace("Accept", "*/*");
  7286. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7287. req.headers.emplace("Content-Type", "text/plain");
  7288. req.headers.emplace("Content-Length", "0");
  7289. req.headers.emplace("Transfer-Encoding", "chunked");
  7290. std::string long_string(30 * 1024u, 'a');
  7291. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7292. // Attempt to make a large enough post to exceed OS buffers, to test that
  7293. // the server handles short reads if the full chunk data isn't available.
  7294. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7295. auto res = std::make_shared<Response>();
  7296. auto error = Error::Success;
  7297. auto ret = cli_.send(req, *res, error);
  7298. ASSERT_TRUE(ret);
  7299. EXPECT_EQ(StatusCode::OK_200, res->status);
  7300. }
  7301. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7302. auto res = cli_.Get("/remote_addr");
  7303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7304. EXPECT_EQ(StatusCode::OK_200, res->status);
  7305. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7306. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7307. }
  7308. TEST_F(ServerTest, GetMethodLocalAddr) {
  7309. auto res = cli_.Get("/local_addr");
  7310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7311. EXPECT_EQ(StatusCode::OK_200, res->status);
  7312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7313. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7314. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7315. }
  7316. TEST_F(ServerTest, HTTPResponseSplitting) {
  7317. auto res = cli_.Get("/http_response_splitting");
  7318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7319. EXPECT_EQ(StatusCode::OK_200, res->status);
  7320. }
  7321. TEST_F(ServerTest, SlowRequest) {
  7322. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7323. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7324. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7325. }
  7326. #if 0
  7327. TEST_F(ServerTest, SlowPost) {
  7328. char buffer[64 * 1024];
  7329. memset(buffer, 0x42, sizeof(buffer));
  7330. auto res = cli_.Post(
  7331. "/slowpost", 64 * 1024 * 1024,
  7332. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7333. auto ret = sink.write(buffer, sizeof(buffer));
  7334. EXPECT_TRUE(ret);
  7335. return true;
  7336. },
  7337. "text/plain");
  7338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7339. EXPECT_EQ(StatusCode::OK_200, res->status);
  7340. }
  7341. TEST_F(ServerTest, SlowPostFail) {
  7342. char buffer[64 * 1024];
  7343. memset(buffer, 0x42, sizeof(buffer));
  7344. cli_.set_write_timeout(std::chrono::seconds(0));
  7345. auto res = cli_.Post(
  7346. "/slowpost", 64 * 1024 * 1024,
  7347. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7348. sink.write(buffer, sizeof(buffer));
  7349. return true;
  7350. },
  7351. "text/plain");
  7352. ASSERT_TRUE(!res);
  7353. EXPECT_EQ(Error::Write, res.error());
  7354. }
  7355. #endif
  7356. TEST_F(ServerTest, Put) {
  7357. auto res = cli_.Put("/put", "PUT", "text/plain");
  7358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7359. EXPECT_EQ(StatusCode::OK_200, res->status);
  7360. EXPECT_EQ("PUT", res->body);
  7361. }
  7362. TEST_F(ServerTest, PutWithContentProvider) {
  7363. auto res = cli_.Put(
  7364. "/put", 3,
  7365. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7366. sink.os << "PUT";
  7367. return true;
  7368. },
  7369. "text/plain");
  7370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7371. EXPECT_EQ(StatusCode::OK_200, res->status);
  7372. EXPECT_EQ("PUT", res->body);
  7373. }
  7374. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7375. auto res = cli_.Post(
  7376. "/post", 42,
  7377. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7378. return false;
  7379. },
  7380. "text/plain");
  7381. ASSERT_TRUE(!res);
  7382. EXPECT_EQ(Error::Canceled, res.error());
  7383. }
  7384. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7385. auto res = cli_.Put(
  7386. "/put",
  7387. [](size_t /*offset*/, DataSink &sink) {
  7388. sink.os << "PUT";
  7389. sink.done();
  7390. return true;
  7391. },
  7392. "text/plain");
  7393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7394. EXPECT_EQ(StatusCode::OK_200, res->status);
  7395. EXPECT_EQ("PUT", res->body);
  7396. }
  7397. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7398. auto res = cli_.Post(
  7399. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7400. "text/plain");
  7401. ASSERT_TRUE(!res);
  7402. EXPECT_EQ(Error::Canceled, res.error());
  7403. }
  7404. TEST_F(ServerTest, PostLoopBack) {
  7405. std::string body;
  7406. auto res = cli_.Post(
  7407. "/post-loopback", 9,
  7408. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7409. EXPECT_EQ(9u, length);
  7410. sink.write("123", 3);
  7411. sink.write("456", 3);
  7412. sink.write("789", 3);
  7413. return true;
  7414. },
  7415. "text/plain",
  7416. [&body](const char *data, size_t data_length) {
  7417. body.append(data, data_length);
  7418. return true;
  7419. });
  7420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7421. EXPECT_EQ(StatusCode::OK_200, res->status);
  7422. EXPECT_EQ("123456789", body);
  7423. }
  7424. TEST_F(ServerTest, PutLoopBack) {
  7425. std::string body;
  7426. auto res = cli_.Put(
  7427. "/put-loopback", 9,
  7428. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7429. EXPECT_EQ(9u, length);
  7430. sink.write("123", 3);
  7431. sink.write("456", 3);
  7432. sink.write("789", 3);
  7433. return true;
  7434. },
  7435. "text/plain",
  7436. [&body](const char *data, size_t data_length) {
  7437. body.append(data, data_length);
  7438. return true;
  7439. });
  7440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7441. EXPECT_EQ(StatusCode::OK_200, res->status);
  7442. EXPECT_EQ("123456789", body);
  7443. }
  7444. TEST_F(ServerTest, PatchLoopBack) {
  7445. std::string body;
  7446. auto res = cli_.Patch(
  7447. "/patch-loopback", 9,
  7448. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7449. EXPECT_EQ(9u, length);
  7450. sink.write("123", 3);
  7451. sink.write("456", 3);
  7452. sink.write("789", 3);
  7453. return true;
  7454. },
  7455. "text/plain",
  7456. [&body](const char *data, size_t data_length) {
  7457. body.append(data, data_length);
  7458. return true;
  7459. });
  7460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7461. EXPECT_EQ(StatusCode::OK_200, res->status);
  7462. EXPECT_EQ("123456789", body);
  7463. }
  7464. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7465. std::string body;
  7466. auto res = cli_.Post(
  7467. "/post-loopback",
  7468. [](size_t /*offset*/, DataSink &sink) {
  7469. sink.write("123", 3);
  7470. sink.write("456", 3);
  7471. sink.write("789", 3);
  7472. sink.done();
  7473. return true;
  7474. },
  7475. "text/plain",
  7476. [&body](const char *data, size_t data_length) {
  7477. body.append(data, data_length);
  7478. return true;
  7479. });
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. EXPECT_EQ(StatusCode::OK_200, res->status);
  7482. EXPECT_EQ("123456789", body);
  7483. }
  7484. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7485. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7486. cli_.set_compress(true);
  7487. auto res = cli_.Put(
  7488. "/put", 3,
  7489. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7490. sink.os << "PUT";
  7491. return true;
  7492. },
  7493. "text/plain");
  7494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7495. EXPECT_EQ(StatusCode::OK_200, res->status);
  7496. EXPECT_EQ("PUT", res->body);
  7497. }
  7498. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7499. cli_.set_compress(true);
  7500. auto res = cli_.Post(
  7501. "/post", 42,
  7502. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7503. return false;
  7504. },
  7505. "text/plain");
  7506. ASSERT_TRUE(!res);
  7507. EXPECT_EQ(Error::Canceled, res.error());
  7508. }
  7509. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7510. cli_.set_compress(true);
  7511. auto res = cli_.Put(
  7512. "/put",
  7513. [](size_t /*offset*/, DataSink &sink) {
  7514. sink.os << "PUT";
  7515. sink.done();
  7516. return true;
  7517. },
  7518. "text/plain");
  7519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7520. EXPECT_EQ(StatusCode::OK_200, res->status);
  7521. EXPECT_EQ("PUT", res->body);
  7522. }
  7523. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7524. cli_.set_compress(true);
  7525. auto res = cli_.Post(
  7526. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7527. "text/plain");
  7528. ASSERT_TRUE(!res);
  7529. EXPECT_EQ(Error::Canceled, res.error());
  7530. }
  7531. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7532. cli_.set_compress(true);
  7533. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7535. EXPECT_EQ(StatusCode::OK_200, res->status);
  7536. EXPECT_EQ(LARGE_DATA, res->body);
  7537. }
  7538. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7539. #ifdef CPPHTTPLIB_SSL_ENABLED
  7540. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7541. Client cli(s.c_str());
  7542. cli.enable_server_certificate_verification(false);
  7543. #else
  7544. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7545. Client cli(s.c_str());
  7546. #endif
  7547. cli.set_compress(true);
  7548. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7550. EXPECT_EQ(StatusCode::OK_200, res->status);
  7551. EXPECT_EQ(LARGE_DATA, res->body);
  7552. // The compressed size should be less than a 10th of the original. May vary
  7553. // depending on the zlib library.
  7554. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7555. static_cast<uint64_t>(10 * 1024 * 1024));
  7556. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7557. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7558. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7559. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7560. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7561. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7562. #endif
  7563. }
  7564. TEST_F(ServerTest, PutContentWithDeflate) {
  7565. cli_.set_compress(false);
  7566. Headers headers;
  7567. headers.emplace("Content-Encoding", "deflate");
  7568. // PUT in deflate format:
  7569. auto res = cli_.Put("/put", headers,
  7570. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. EXPECT_EQ("PUT", res->body);
  7574. }
  7575. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7576. Headers headers;
  7577. headers.emplace("Accept-Encoding", "gzip, deflate");
  7578. auto res = cli_.Get("/streamed-chunked", headers);
  7579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7580. EXPECT_EQ(StatusCode::OK_200, res->status);
  7581. EXPECT_EQ(std::string("123456789"), res->body);
  7582. }
  7583. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7584. Headers headers;
  7585. headers.emplace("Accept-Encoding", "gzip, deflate");
  7586. auto res = cli_.Get("/streamed-chunked2", headers);
  7587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7588. EXPECT_EQ(StatusCode::OK_200, res->status);
  7589. EXPECT_EQ(std::string("123456789"), res->body);
  7590. }
  7591. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7592. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7594. EXPECT_EQ(StatusCode::OK_200, res->status);
  7595. }
  7596. TEST(GzipDecompressor, ChunkedDecompression) {
  7597. std::string data;
  7598. for (size_t i = 0; i < 32 * 1024; ++i) {
  7599. data.push_back(static_cast<char>('a' + i % 26));
  7600. }
  7601. std::string compressed_data;
  7602. {
  7603. httplib::detail::gzip_compressor compressor;
  7604. bool result = compressor.compress(
  7605. data.data(), data.size(),
  7606. /*last=*/true,
  7607. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7608. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7609. compressed_data_size);
  7610. return true;
  7611. });
  7612. ASSERT_TRUE(result);
  7613. }
  7614. std::string decompressed_data;
  7615. {
  7616. httplib::detail::gzip_decompressor decompressor;
  7617. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7618. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7619. size_t chunk_size = 130;
  7620. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7621. chunk_begin += chunk_size) {
  7622. size_t current_chunk_size =
  7623. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7624. bool result = decompressor.decompress(
  7625. compressed_data.data() + chunk_begin, current_chunk_size,
  7626. [&](const char *decompressed_data_chunk,
  7627. size_t decompressed_data_chunk_size) {
  7628. decompressed_data.insert(decompressed_data.size(),
  7629. decompressed_data_chunk,
  7630. decompressed_data_chunk_size);
  7631. return true;
  7632. });
  7633. ASSERT_TRUE(result);
  7634. }
  7635. }
  7636. ASSERT_EQ(data, decompressed_data);
  7637. }
  7638. TEST(GzipDecompressor, DeflateDecompression) {
  7639. std::string original_text = "Raw deflate without gzip";
  7640. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7641. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7642. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7643. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7644. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7645. std::string decompressed_data;
  7646. {
  7647. httplib::detail::gzip_decompressor decompressor;
  7648. bool result = decompressor.decompress(
  7649. compressed_data.data(), compressed_data.size(),
  7650. [&](const char *decompressed_data_chunk,
  7651. size_t decompressed_data_chunk_size) {
  7652. decompressed_data.insert(decompressed_data.size(),
  7653. decompressed_data_chunk,
  7654. decompressed_data_chunk_size);
  7655. return true;
  7656. });
  7657. ASSERT_TRUE(result);
  7658. }
  7659. ASSERT_EQ(original_text, decompressed_data);
  7660. }
  7661. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7662. std::string original_text = "Raw deflate without gzip";
  7663. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7664. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7665. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7666. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7667. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7668. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7669. std::string decompressed_data;
  7670. {
  7671. httplib::detail::gzip_decompressor decompressor;
  7672. bool result = decompressor.decompress(
  7673. compressed_data.data(), compressed_data.size(),
  7674. [&](const char *decompressed_data_chunk,
  7675. size_t decompressed_data_chunk_size) {
  7676. decompressed_data.insert(decompressed_data.size(),
  7677. decompressed_data_chunk,
  7678. decompressed_data_chunk_size);
  7679. return true;
  7680. });
  7681. ASSERT_TRUE(result);
  7682. }
  7683. ASSERT_EQ(original_text, decompressed_data);
  7684. }
  7685. #endif
  7686. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7687. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7688. Headers headers;
  7689. headers.emplace("Accept-Encoding", "br");
  7690. auto res = cli_.Get("/streamed-chunked", headers);
  7691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7692. EXPECT_EQ(StatusCode::OK_200, res->status);
  7693. EXPECT_EQ(std::string("123456789"), res->body);
  7694. }
  7695. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7696. Headers headers;
  7697. headers.emplace("Accept-Encoding", "br");
  7698. auto res = cli_.Get("/streamed-chunked2", headers);
  7699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7700. EXPECT_EQ(StatusCode::OK_200, res->status);
  7701. EXPECT_EQ(std::string("123456789"), res->body);
  7702. }
  7703. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7704. cli_.set_compress(true);
  7705. auto res = cli_.Put(
  7706. "/put", 3,
  7707. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7708. sink.os << "PUT";
  7709. return true;
  7710. },
  7711. "text/plain");
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::OK_200, res->status);
  7714. EXPECT_EQ("PUT", res->body);
  7715. }
  7716. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7717. cli_.set_compress(true);
  7718. auto res = cli_.Put(
  7719. "/put",
  7720. [](size_t /*offset*/, DataSink &sink) {
  7721. sink.os << "PUT";
  7722. sink.done();
  7723. return true;
  7724. },
  7725. "text/plain");
  7726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7727. EXPECT_EQ(StatusCode::OK_200, res->status);
  7728. EXPECT_EQ("PUT", res->body);
  7729. }
  7730. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7731. cli_.set_compress(true);
  7732. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7734. EXPECT_EQ(StatusCode::OK_200, res->status);
  7735. EXPECT_EQ(LARGE_DATA, res->body);
  7736. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7737. }
  7738. #endif
  7739. TEST_F(ServerTest, Patch) {
  7740. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ(StatusCode::OK_200, res->status);
  7743. EXPECT_EQ("PATCH", res->body);
  7744. }
  7745. TEST_F(ServerTest, Delete) {
  7746. auto res = cli_.Delete("/delete");
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. EXPECT_EQ("DELETE", res->body);
  7750. }
  7751. TEST_F(ServerTest, DeleteContentReceiver) {
  7752. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7754. EXPECT_EQ(StatusCode::OK_200, res->status);
  7755. EXPECT_EQ("content", res->body);
  7756. }
  7757. TEST_F(ServerTest, Options) {
  7758. auto res = cli_.Options("*");
  7759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7760. EXPECT_EQ(StatusCode::OK_200, res->status);
  7761. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7762. EXPECT_TRUE(res->body.empty());
  7763. }
  7764. TEST_F(ServerTest, URL) {
  7765. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7767. EXPECT_EQ(StatusCode::OK_200, res->status);
  7768. }
  7769. TEST_F(ServerTest, ArrayParam) {
  7770. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::OK_200, res->status);
  7773. }
  7774. TEST_F(ServerTest, ArrayParamValues) {
  7775. auto res =
  7776. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7778. EXPECT_EQ(StatusCode::OK_200, res->status);
  7779. }
  7780. TEST_F(ServerTest, NoMultipleHeaders) {
  7781. Headers headers = {{"Content-Length", "5"}};
  7782. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7783. "text/plain");
  7784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7785. EXPECT_EQ(StatusCode::OK_200, res->status);
  7786. }
  7787. TEST_F(ServerTest, PostContentReceiver) {
  7788. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7790. ASSERT_EQ(StatusCode::OK_200, res->status);
  7791. ASSERT_EQ("content", res->body);
  7792. }
  7793. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7794. UploadFormDataItems items = {
  7795. {"text1", "text default", "", ""},
  7796. {"text2", "aωb", "", ""},
  7797. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7798. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7799. {"file3", "", "", "application/octet-stream"},
  7800. };
  7801. auto res = cli_.Post("/content_receiver", items);
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. EXPECT_EQ(StatusCode::OK_200, res->status);
  7804. }
  7805. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7806. UploadFormDataItems items = {
  7807. {"text1", "text default", "", ""},
  7808. {"text2", "aωb", "", ""},
  7809. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7810. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7811. {"file3", "", "", "application/octet-stream"},
  7812. };
  7813. auto boundary = std::string("+++++");
  7814. std::string body;
  7815. for (const auto &item : items) {
  7816. body += "--" + boundary + "\r\n";
  7817. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7818. if (!item.filename.empty()) {
  7819. body += "; filename=\"" + item.filename + "\"";
  7820. }
  7821. body += "\r\n";
  7822. if (!item.content_type.empty()) {
  7823. body += "Content-Type: " + item.content_type + "\r\n";
  7824. }
  7825. body += "\r\n";
  7826. body += item.content + "\r\n";
  7827. }
  7828. body += "--" + boundary + "--\r\n";
  7829. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7830. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7832. EXPECT_EQ(StatusCode::OK_200, res->status);
  7833. }
  7834. TEST(MultipartFormDataTest, FieldEscaping) {
  7835. Server svr;
  7836. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7837. const ContentReader &content_reader) {
  7838. ASSERT_TRUE(req.is_multipart_form_data());
  7839. std::vector<FormData> received;
  7840. content_reader(
  7841. [&](const FormData &file) {
  7842. received.push_back(file);
  7843. return true;
  7844. },
  7845. [&](const char *data, size_t data_length) {
  7846. received.back().content.append(data, data_length);
  7847. return true;
  7848. });
  7849. // '"', CR and LF in names and filenames are escaped following the
  7850. // WHATWG HTML standard, so each part still parses as a single part
  7851. // with no injected headers. Content types get CR/LF escaped too,
  7852. // while '"' (legal there, e.g. quoted charset) is preserved.
  7853. ASSERT_EQ(4U, received.size());
  7854. EXPECT_EQ("na%22me", received[0].name);
  7855. EXPECT_EQ("quoted name", received[0].content);
  7856. EXPECT_EQ("file", received[1].name);
  7857. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7858. received[1].filename);
  7859. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7860. EXPECT_EQ("injected", received[1].content);
  7861. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7862. EXPECT_EQ("my%22file.txt", received[2].filename);
  7863. EXPECT_EQ("cr lf name", received[2].content);
  7864. EXPECT_EQ("typed", received[3].name);
  7865. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7866. received[3].content_type);
  7867. EXPECT_EQ("typed content", received[3].content);
  7868. });
  7869. auto port = svr.bind_to_any_port("localhost");
  7870. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7871. auto se = detail::scope_exit([&] {
  7872. svr.stop();
  7873. t.join();
  7874. ASSERT_FALSE(svr.is_running());
  7875. });
  7876. svr.wait_until_ready();
  7877. Client cli("localhost", port);
  7878. UploadFormDataItems items = {
  7879. {"na\"me", "quoted name", "", ""},
  7880. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7881. "application/octet-stream"},
  7882. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7883. {"typed", "typed content", "",
  7884. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7885. };
  7886. auto res = cli.Post("/post", items);
  7887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7888. EXPECT_EQ(StatusCode::OK_200, res->status);
  7889. }
  7890. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7891. const UploadFormDataItems items = {
  7892. {"name1", "Content 1", "", ""},
  7893. {"name2", "Content 2", "file2.txt", "text/plain"},
  7894. };
  7895. Server svr;
  7896. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7897. const ContentReader &content_reader) {
  7898. ASSERT_TRUE(req.is_multipart_form_data());
  7899. std::vector<FormData> received;
  7900. content_reader(
  7901. [&](const FormData &file) {
  7902. received.push_back(file);
  7903. return true;
  7904. },
  7905. [&](const char *data, size_t data_length) {
  7906. received.back().content.append(data, data_length);
  7907. return true;
  7908. });
  7909. ASSERT_EQ(2U, received.size());
  7910. EXPECT_EQ("name1", received[0].name);
  7911. EXPECT_EQ("Content 1", received[0].content);
  7912. EXPECT_EQ("name2", received[1].name);
  7913. EXPECT_EQ("Content 2", received[1].content);
  7914. EXPECT_EQ("file2.txt", received[1].filename);
  7915. EXPECT_EQ("text/plain", received[1].content_type);
  7916. });
  7917. auto port = svr.bind_to_any_port("localhost");
  7918. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7919. auto se = detail::scope_exit([&] {
  7920. svr.stop();
  7921. t.join();
  7922. ASSERT_FALSE(svr.is_running());
  7923. });
  7924. svr.wait_until_ready();
  7925. Client cli("localhost", port);
  7926. // Whole-body serialization with a generated boundary
  7927. {
  7928. MultipartFormDataWriter writer;
  7929. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7930. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7931. writer.content_type());
  7932. auto body = writer.serialize(items);
  7933. EXPECT_EQ(body.size(), writer.content_length(items));
  7934. auto res = cli.Post("/post", body, writer.content_type());
  7935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7936. EXPECT_EQ(StatusCode::OK_200, res->status);
  7937. }
  7938. // Per-part framing with a custom boundary via a content provider
  7939. {
  7940. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7941. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7942. MultipartFormDataWriter writer("custom-boundary_123");
  7943. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7944. std::string body;
  7945. for (const auto &item : items) {
  7946. body += writer.item_begin(item);
  7947. body += item.content;
  7948. body += MultipartFormDataWriter::item_end();
  7949. }
  7950. body += writer.finish();
  7951. EXPECT_EQ(body.size(), writer.content_length(items));
  7952. auto res = cli.Post(
  7953. "/post", body.size(),
  7954. [&](size_t offset, size_t length, DataSink &sink) {
  7955. sink.write(body.data() + offset, length);
  7956. return true;
  7957. },
  7958. writer.content_type());
  7959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7960. EXPECT_EQ(StatusCode::OK_200, res->status);
  7961. }
  7962. }
  7963. TEST_F(ServerTest, PostContentReceiverGzip) {
  7964. cli_.set_compress(true);
  7965. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7967. ASSERT_EQ(StatusCode::OK_200, res->status);
  7968. ASSERT_EQ("content", res->body);
  7969. }
  7970. TEST_F(ServerTest, PutContentReceiver) {
  7971. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7973. ASSERT_EQ(StatusCode::OK_200, res->status);
  7974. ASSERT_EQ("content", res->body);
  7975. }
  7976. TEST_F(ServerTest, PatchContentReceiver) {
  7977. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7979. ASSERT_EQ(StatusCode::OK_200, res->status);
  7980. ASSERT_EQ("content", res->body);
  7981. }
  7982. template <typename ClientType>
  7983. void TestWithHeadersAndContentReceiver(
  7984. ClientType &cli,
  7985. std::function<Result(ClientType &, const std::string &, const Headers &,
  7986. const std::string &, const std::string &,
  7987. ContentReceiver, DownloadProgress)>
  7988. request_func) {
  7989. Headers headers;
  7990. headers.emplace("X-Custom-Header", "test-value");
  7991. std::string received_body;
  7992. auto res = request_func(
  7993. cli, "/content_receiver", headers, "content", "application/json",
  7994. [&](const char *data, size_t data_length) {
  7995. received_body.append(data, data_length);
  7996. return true;
  7997. },
  7998. nullptr);
  7999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8000. EXPECT_EQ(StatusCode::OK_200, res->status);
  8001. EXPECT_EQ("content", received_body);
  8002. }
  8003. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8004. #ifdef CPPHTTPLIB_SSL_ENABLED
  8005. using ClientT = SSLClient;
  8006. #else
  8007. using ClientT = Client;
  8008. #endif
  8009. TestWithHeadersAndContentReceiver<ClientT>(
  8010. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8011. const std::string &body, const std::string &content_type,
  8012. ContentReceiver receiver, DownloadProgress progress) {
  8013. return cli.Post(path, headers, body, content_type, receiver, progress);
  8014. });
  8015. }
  8016. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8017. #ifdef CPPHTTPLIB_SSL_ENABLED
  8018. using ClientT = SSLClient;
  8019. #else
  8020. using ClientT = Client;
  8021. #endif
  8022. TestWithHeadersAndContentReceiver<ClientT>(
  8023. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8024. const std::string &body, const std::string &content_type,
  8025. ContentReceiver receiver, DownloadProgress progress) {
  8026. return cli.Put(path, headers, body, content_type, receiver, progress);
  8027. });
  8028. }
  8029. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8030. #ifdef CPPHTTPLIB_SSL_ENABLED
  8031. using ClientT = SSLClient;
  8032. #else
  8033. using ClientT = Client;
  8034. #endif
  8035. TestWithHeadersAndContentReceiver<ClientT>(
  8036. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8037. const std::string &body, const std::string &content_type,
  8038. ContentReceiver receiver, DownloadProgress progress) {
  8039. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8040. });
  8041. }
  8042. template <typename ClientType>
  8043. void TestWithHeadersAndContentReceiverWithProgress(
  8044. ClientType &cli,
  8045. std::function<Result(ClientType &, const std::string &, const Headers &,
  8046. const std::string &, const std::string &,
  8047. ContentReceiver, DownloadProgress)>
  8048. request_func) {
  8049. Headers headers;
  8050. headers.emplace("X-Test-Header", "progress-test");
  8051. std::string received_body;
  8052. auto progress_called = false;
  8053. auto res = request_func(
  8054. cli, "/content_receiver", headers, "content", "text/plain",
  8055. [&](const char *data, size_t data_length) {
  8056. received_body.append(data, data_length);
  8057. return true;
  8058. },
  8059. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8060. progress_called = true;
  8061. return true;
  8062. });
  8063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8064. EXPECT_EQ(StatusCode::OK_200, res->status);
  8065. EXPECT_EQ("content", received_body);
  8066. EXPECT_TRUE(progress_called);
  8067. }
  8068. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8069. #ifdef CPPHTTPLIB_SSL_ENABLED
  8070. using ClientT = SSLClient;
  8071. #else
  8072. using ClientT = Client;
  8073. #endif
  8074. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8075. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8076. const std::string &body, const std::string &content_type,
  8077. ContentReceiver receiver, DownloadProgress progress) {
  8078. return cli.Post(path, headers, body, content_type, receiver, progress);
  8079. });
  8080. }
  8081. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8082. #ifdef CPPHTTPLIB_SSL_ENABLED
  8083. using ClientT = SSLClient;
  8084. #else
  8085. using ClientT = Client;
  8086. #endif
  8087. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8088. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8089. const std::string &body, const std::string &content_type,
  8090. ContentReceiver receiver, DownloadProgress progress) {
  8091. return cli.Put(path, headers, body, content_type, receiver, progress);
  8092. });
  8093. }
  8094. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8095. #ifdef CPPHTTPLIB_SSL_ENABLED
  8096. using ClientT = SSLClient;
  8097. #else
  8098. using ClientT = Client;
  8099. #endif
  8100. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8101. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8102. const std::string &body, const std::string &content_type,
  8103. ContentReceiver receiver, DownloadProgress progress) {
  8104. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8105. });
  8106. }
  8107. template <typename ClientType>
  8108. void TestWithHeadersAndContentReceiverError(
  8109. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8110. const Headers &, const std::string &,
  8111. const std::string &, ContentReceiver)>
  8112. request_func) {
  8113. Headers headers;
  8114. headers.emplace("X-Error-Test", "true");
  8115. std::string received_body;
  8116. auto receiver_failed = false;
  8117. auto res =
  8118. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8119. [&](const char *data, size_t data_length) {
  8120. received_body.append(data, data_length);
  8121. receiver_failed = true;
  8122. return false;
  8123. });
  8124. ASSERT_FALSE(res);
  8125. EXPECT_TRUE(receiver_failed);
  8126. }
  8127. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8128. #ifdef CPPHTTPLIB_SSL_ENABLED
  8129. using ClientT = SSLClient;
  8130. #else
  8131. using ClientT = Client;
  8132. #endif
  8133. TestWithHeadersAndContentReceiverError<ClientT>(
  8134. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8135. const std::string &body, const std::string &content_type,
  8136. ContentReceiver receiver) {
  8137. return cli.Post(path, headers, body, content_type, receiver);
  8138. });
  8139. }
  8140. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8141. #ifdef CPPHTTPLIB_SSL_ENABLED
  8142. using ClientT = SSLClient;
  8143. #else
  8144. using ClientT = Client;
  8145. #endif
  8146. TestWithHeadersAndContentReceiverError<ClientT>(
  8147. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8148. const std::string &body, const std::string &content_type,
  8149. ContentReceiver receiver) {
  8150. return cli.Put(path, headers, body, content_type, receiver);
  8151. });
  8152. }
  8153. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8154. #ifdef CPPHTTPLIB_SSL_ENABLED
  8155. using ClientT = SSLClient;
  8156. #else
  8157. using ClientT = Client;
  8158. #endif
  8159. TestWithHeadersAndContentReceiverError<ClientT>(
  8160. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8161. const std::string &body, const std::string &content_type,
  8162. ContentReceiver receiver) {
  8163. return cli.Patch(path, headers, body, content_type, receiver);
  8164. });
  8165. }
  8166. TEST_F(ServerTest, PostQueryStringAndBody) {
  8167. auto res =
  8168. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. ASSERT_EQ(StatusCode::OK_200, res->status);
  8171. }
  8172. TEST_F(ServerTest, HTTP2Magic) {
  8173. Request req;
  8174. req.method = "PRI";
  8175. req.path = "*";
  8176. req.body = "SM";
  8177. auto res = std::make_shared<Response>();
  8178. auto error = Error::Success;
  8179. auto ret = cli_.send(req, *res, error);
  8180. ASSERT_TRUE(ret);
  8181. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8182. }
  8183. TEST_F(ServerTest, KeepAlive) {
  8184. auto res = cli_.Get("/hi");
  8185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8186. EXPECT_EQ(StatusCode::OK_200, res->status);
  8187. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8188. EXPECT_EQ("Hello World!", res->body);
  8189. res = cli_.Get("/hi");
  8190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8191. EXPECT_EQ(StatusCode::OK_200, res->status);
  8192. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8193. EXPECT_EQ("Hello World!", res->body);
  8194. res = cli_.Get("/hi");
  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("Hello World!", res->body);
  8199. res = cli_.Get("/not-exist");
  8200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8201. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8202. res = cli_.Post("/empty", "", "text/plain");
  8203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8204. EXPECT_EQ(StatusCode::OK_200, res->status);
  8205. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8206. EXPECT_EQ("empty", res->body);
  8207. EXPECT_EQ("close", res->get_header_value("Connection"));
  8208. res = cli_.Post(
  8209. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8210. "text/plain");
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8214. EXPECT_EQ("empty", res->body);
  8215. cli_.set_keep_alive(false);
  8216. res = cli_.Get("/last-request");
  8217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8218. EXPECT_EQ(StatusCode::OK_200, res->status);
  8219. EXPECT_EQ("close", res->get_header_value("Connection"));
  8220. }
  8221. TEST_F(ServerTest, TooManyRedirect) {
  8222. cli_.set_follow_location(true);
  8223. auto res = cli_.Get("/redirect/0");
  8224. ASSERT_TRUE(!res);
  8225. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8226. }
  8227. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8228. Request req;
  8229. req.method = "FOOBAR";
  8230. req.path = "/hi";
  8231. cli_.set_keep_alive(true);
  8232. auto res = cli_.send(req);
  8233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8234. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8235. EXPECT_EQ("close", res->get_header_value("Connection"));
  8236. EXPECT_FALSE(cli_.is_socket_open());
  8237. }
  8238. TEST_F(ServerTest, CustomRouteReadsBody) {
  8239. const std::string xml =
  8240. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8241. Request req;
  8242. req.method = "PROPFIND";
  8243. req.path = "/dav/dir";
  8244. req.set_header("Depth", "1");
  8245. req.body = xml;
  8246. auto res = cli_.send(req);
  8247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8248. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8249. EXPECT_EQ(xml, res->body);
  8250. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8251. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8252. }
  8253. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8254. Request req;
  8255. req.method = "PROPFIND";
  8256. req.path = "/dav/42";
  8257. auto res = cli_.send(req);
  8258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8259. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8260. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8261. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8262. }
  8263. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8264. Request req;
  8265. req.method = "PROPFIND";
  8266. req.path = "/dav-re/123";
  8267. auto res = cli_.send(req);
  8268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8269. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8270. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8271. }
  8272. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8273. Request req;
  8274. req.method = "MKCOL";
  8275. req.path = "/dav-mkcol";
  8276. auto res = cli_.send(req);
  8277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8278. EXPECT_EQ(StatusCode::Created_201, res->status);
  8279. }
  8280. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8281. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8282. Request req;
  8283. req.method = "REPORT";
  8284. req.path = "/dav-report";
  8285. req.body = xml;
  8286. auto res = cli_.send(req);
  8287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8288. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8289. EXPECT_EQ(xml, res->body);
  8290. }
  8291. // A content reader route must fire even when the request carries no body,
  8292. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8293. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8294. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8295. Request req;
  8296. req.method = "REPORT";
  8297. req.path = "/dav-report";
  8298. auto res = cli_.send(req);
  8299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8300. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8301. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8302. }
  8303. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8304. Request req;
  8305. req.method = "PROPFIND";
  8306. req.path = "/not-dav";
  8307. auto res = cli_.send(req);
  8308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8310. }
  8311. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8312. Request req;
  8313. req.method = "UNLOCK";
  8314. req.path = "/dav/dir";
  8315. cli_.set_keep_alive(true);
  8316. auto res = cli_.send(req);
  8317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8318. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8319. EXPECT_EQ("close", res->get_header_value("Connection"));
  8320. EXPECT_FALSE(cli_.is_socket_open());
  8321. }
  8322. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8323. // The mount point serves this path, but only for GET and HEAD.
  8324. auto get_res = cli_.Get("/dir/index.html");
  8325. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8326. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8327. Request req;
  8328. req.method = "PROPFIND";
  8329. req.path = "/dir/index.html";
  8330. auto res = cli_.send(req);
  8331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8332. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8333. }
  8334. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8335. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8336. cli_.set_keep_alive(true);
  8337. for (auto i = 0; i < 2; i++) {
  8338. Request req;
  8339. req.method = "PROPFIND";
  8340. req.path = "/dav/dir";
  8341. req.body = xml;
  8342. auto res = cli_.send(req);
  8343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8344. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8345. EXPECT_EQ(xml, res->body);
  8346. EXPECT_TRUE(cli_.is_socket_open());
  8347. }
  8348. // A built-in method must still be served on the same connection.
  8349. cli_.set_keep_alive(false);
  8350. auto res = cli_.Get("/hi");
  8351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8352. EXPECT_EQ(StatusCode::OK_200, res->status);
  8353. EXPECT_EQ("close", res->get_header_value("Connection"));
  8354. }
  8355. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8356. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8357. Request req;
  8358. req.method = "PROPFIND";
  8359. req.path = "/dav/dir";
  8360. req.set_header("Expect", "100-continue");
  8361. req.body = xml;
  8362. auto res = cli_.send(req);
  8363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8364. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8365. EXPECT_EQ(xml, res->body);
  8366. }
  8367. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8368. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8369. TEST_F(ServerTest, Gzip) {
  8370. Headers headers;
  8371. headers.emplace("Accept-Encoding", "gzip, deflate");
  8372. auto res = cli_.Get("/compress", headers);
  8373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8374. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8375. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8376. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8377. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8378. "7890123456789012345678901234567890",
  8379. res->body);
  8380. EXPECT_EQ(StatusCode::OK_200, res->status);
  8381. }
  8382. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8383. Headers headers;
  8384. headers.emplace("Accept-Encoding", "gzip, deflate");
  8385. auto res = cli_.Get("/compress-with-charset", headers);
  8386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8387. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8388. EXPECT_EQ("application/json; charset=utf-8",
  8389. res->get_header_value("Content-Type"));
  8390. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8391. "7890123456789012345678901234567890",
  8392. res->body);
  8393. EXPECT_EQ(StatusCode::OK_200, res->status);
  8394. }
  8395. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8396. Headers headers;
  8397. headers.emplace("Accept-Encoding", "");
  8398. auto res = cli_.Get("/compress", headers);
  8399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8400. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8402. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8403. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8404. "7890123456789012345678901234567890",
  8405. res->body);
  8406. EXPECT_EQ(StatusCode::OK_200, res->status);
  8407. }
  8408. TEST_F(ServerTest, GzipWithContentReceiver) {
  8409. Headers headers;
  8410. headers.emplace("Accept-Encoding", "gzip, deflate");
  8411. std::string body;
  8412. auto res = cli_.Get("/compress", headers,
  8413. [&](const char *data, uint64_t data_length) {
  8414. EXPECT_EQ(100U, data_length);
  8415. body.append(data, data_length);
  8416. return true;
  8417. });
  8418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8419. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8420. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8421. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8422. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8423. "7890123456789012345678901234567890",
  8424. body);
  8425. EXPECT_EQ(StatusCode::OK_200, res->status);
  8426. }
  8427. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8428. Headers headers;
  8429. headers.emplace("Accept-Encoding", "gzip, deflate");
  8430. cli_.set_decompress(false);
  8431. auto res = cli_.Get("/compress", headers);
  8432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8433. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8434. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8435. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8436. EXPECT_EQ(33U, res->body.size());
  8437. EXPECT_EQ(StatusCode::OK_200, res->status);
  8438. }
  8439. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8440. Headers headers;
  8441. headers.emplace("Accept-Encoding", "");
  8442. std::string body;
  8443. auto res = cli_.Get("/compress", headers,
  8444. [&](const char *data, uint64_t data_length) {
  8445. EXPECT_EQ(100U, data_length);
  8446. body.append(data, data_length);
  8447. return true;
  8448. });
  8449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8450. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8451. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8452. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8453. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8454. "7890123456789012345678901234567890",
  8455. body);
  8456. EXPECT_EQ(StatusCode::OK_200, res->status);
  8457. }
  8458. TEST_F(ServerTest, NoGzip) {
  8459. Headers headers;
  8460. headers.emplace("Accept-Encoding", "gzip, deflate");
  8461. auto res = cli_.Get("/nocompress", headers);
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8464. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8465. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8466. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8467. "7890123456789012345678901234567890",
  8468. res->body);
  8469. EXPECT_EQ(StatusCode::OK_200, res->status);
  8470. }
  8471. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8472. Headers headers;
  8473. headers.emplace("Accept-Encoding", "gzip, deflate");
  8474. std::string body;
  8475. auto res = cli_.Get("/nocompress", headers,
  8476. [&](const char *data, uint64_t data_length) {
  8477. EXPECT_EQ(100U, data_length);
  8478. body.append(data, data_length);
  8479. return true;
  8480. });
  8481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8482. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8483. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8484. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8485. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8486. "7890123456789012345678901234567890",
  8487. body);
  8488. EXPECT_EQ(StatusCode::OK_200, res->status);
  8489. }
  8490. TEST_F(ServerTest, MultipartFormDataGzip) {
  8491. UploadFormDataItems items = {
  8492. {"key1", "test", "", ""},
  8493. {"key2", "--abcdefg123", "", ""},
  8494. };
  8495. cli_.set_compress(true);
  8496. auto res = cli_.Post("/compress-multipart", items);
  8497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8498. EXPECT_EQ(StatusCode::OK_200, res->status);
  8499. }
  8500. #endif
  8501. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8502. // Static file compression is opt-in, so these run their own server rather than
  8503. // flipping it on for the shared ServerTest fixture, which would silently
  8504. // rewrite what every other static file test is asserting.
  8505. class StaticFileCompressionTest : public ::testing::Test {
  8506. protected:
  8507. void TearDown() override {
  8508. if (t_.joinable()) {
  8509. svr_.stop();
  8510. t_.join();
  8511. }
  8512. }
  8513. int start(const std::function<void(Server &)> &configure = nullptr) {
  8514. // Serves the same tree as a directory of build-time compressed assets
  8515. // would be served: the mount point names the coding the files are already
  8516. // stored in. Registered before "/" so it is the one that matches.
  8517. svr_.set_mount_point("/pre-encoded", "./www",
  8518. {{"Content-Encoding", "gzip"}});
  8519. svr_.set_mount_point("/", "./www");
  8520. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8521. res.set_file_content("./www/dir/index.html", "text/html");
  8522. });
  8523. svr_.Get("/pre-encoded-file-content",
  8524. [](const Request & /*req*/, Response &res) {
  8525. res.set_header("Content-Encoding", "gzip");
  8526. res.set_file_content("./www/dir/index.html", "text/html");
  8527. });
  8528. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8529. res.set_content_provider(
  8530. 6, "text/plain",
  8531. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8532. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8533. return true;
  8534. });
  8535. });
  8536. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8537. res.set_content_provider(
  8538. 1000, "text/plain",
  8539. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8540. if (offset < 100) {
  8541. std::string data(100, 'A');
  8542. sink.write(data.data(), data.size());
  8543. return true;
  8544. }
  8545. std::this_thread::sleep_for(std::chrono::seconds(2));
  8546. std::string data(900, 'B');
  8547. sink.write(data.data(), data.size());
  8548. return true;
  8549. });
  8550. });
  8551. if (configure) { configure(svr_); }
  8552. auto port = svr_.bind_to_any_port(HOST);
  8553. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8554. svr_.wait_until_ready();
  8555. return port;
  8556. }
  8557. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8558. // Every file under ./www except 1MB.txt is smaller than the default
  8559. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8560. // it out of the way.
  8561. static void enable_without_floor(Server &svr) {
  8562. svr.set_static_file_compression(true);
  8563. svr.set_static_file_compression_min_length(0);
  8564. }
  8565. Server svr_;
  8566. std::thread t_;
  8567. };
  8568. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8569. auto port = start();
  8570. Client cli(HOST, port);
  8571. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8573. EXPECT_EQ(StatusCode::OK_200, res->status);
  8574. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8575. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8576. EXPECT_EQ(1048576U, res->body.size());
  8577. }
  8578. TEST_F(StaticFileCompressionTest, MountPoint) {
  8579. auto port = start(enable);
  8580. Client cli(HOST, port);
  8581. cli.set_decompress(false);
  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("text/plain", res->get_header_value("Content-Type"));
  8586. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8587. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8588. // The response stays self-delimiting: a length, not a chunked body.
  8589. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8590. EXPECT_EQ(std::to_string(res->body.size()),
  8591. res->get_header_value("Content-Length"));
  8592. EXPECT_LT(res->body.size(), 1048576U);
  8593. EXPECT_FALSE(res->body.empty());
  8594. }
  8595. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8596. auto port = start(enable);
  8597. Client cli(HOST, port);
  8598. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8600. EXPECT_EQ(StatusCode::OK_200, res->status);
  8601. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8602. EXPECT_EQ(1048576U, res->body.size());
  8603. }
  8604. TEST_F(StaticFileCompressionTest, FileContent) {
  8605. auto port = start(enable_without_floor);
  8606. Client cli(HOST, port);
  8607. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8609. EXPECT_EQ(StatusCode::OK_200, res->status);
  8610. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8611. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8612. EXPECT_EQ(104U, res->body.size());
  8613. }
  8614. // A handler that serves an already-encoded file names the coding itself. The
  8615. // file-backed path decided its coding from Accept-Encoding and the content
  8616. // type alone, so it compressed the stored bytes a second time and appended a
  8617. // second Content-Encoding field line.
  8618. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8619. auto port = start(enable_without_floor);
  8620. Client cli(HOST, port);
  8621. cli.set_decompress(false);
  8622. auto res = cli.Get("/pre-encoded-file-content",
  8623. Headers{{"Accept-Encoding", "gzip"}});
  8624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8625. EXPECT_EQ(StatusCode::OK_200, res->status);
  8626. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8627. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8628. // Vary belongs to a coding the server chose, and it chose none here.
  8629. EXPECT_FALSE(res->has_header("Vary"));
  8630. // The file travels exactly as it is stored on disk.
  8631. EXPECT_EQ(104U, res->body.size());
  8632. }
  8633. // The 1MB file clears the default floor, so this one runs the configuration a
  8634. // deployment would actually have.
  8635. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8636. auto port = start(enable);
  8637. Client cli(HOST, port);
  8638. cli.set_decompress(false);
  8639. auto res =
  8640. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8642. EXPECT_EQ(StatusCode::OK_200, res->status);
  8643. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8644. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8645. EXPECT_FALSE(res->has_header("Vary"));
  8646. EXPECT_EQ(1048576U, res->body.size());
  8647. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8648. }
  8649. TEST_F(StaticFileCompressionTest, Head) {
  8650. auto port = start(enable);
  8651. Client cli(HOST, port);
  8652. cli.set_decompress(false);
  8653. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8654. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8655. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8657. EXPECT_EQ(StatusCode::OK_200, res->status);
  8658. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8659. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8660. // HEAD still reports the size a GET would return.
  8661. EXPECT_EQ(get->get_header_value("Content-Length"),
  8662. res->get_header_value("Content-Length"));
  8663. EXPECT_TRUE(res->body.empty());
  8664. }
  8665. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8666. auto port = start(enable);
  8667. Client cli(HOST, port);
  8668. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8669. {"Accept-Encoding", "gzip"}});
  8670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8671. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8672. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8673. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8674. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8675. EXPECT_EQ("cd", res->body);
  8676. }
  8677. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8678. auto port = start(enable);
  8679. Client cli(HOST, port);
  8680. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8682. EXPECT_EQ(StatusCode::OK_200, res->status);
  8683. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8684. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8685. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8686. }
  8687. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8688. auto port = start(enable);
  8689. Client cli(HOST, port);
  8690. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8692. EXPECT_EQ(StatusCode::OK_200, res->status);
  8693. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8694. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8695. EXPECT_TRUE(res->body.empty());
  8696. }
  8697. TEST_F(StaticFileCompressionTest, MinLength) {
  8698. auto port = start(enable);
  8699. Client cli(HOST, port);
  8700. // 104 bytes, well under the default floor. Compressing it would add the
  8701. // gzip header and trailer to a body that already fits in one packet.
  8702. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8704. EXPECT_EQ(StatusCode::OK_200, res->status);
  8705. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8706. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8707. }
  8708. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8709. auto port = start([](Server &svr) {
  8710. svr.set_static_file_compression(true);
  8711. svr.set_static_file_compression_min_length(1);
  8712. });
  8713. Client cli(HOST, port);
  8714. cli.set_decompress(false);
  8715. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8717. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8718. // A 9-byte file comes back larger than it went in, because gzip's header and
  8719. // trailer outweigh anything deflate can save. That is the end of the range
  8720. // the floor exists to keep out.
  8721. EXPECT_GT(res->body.size(), 9U);
  8722. }
  8723. TEST_F(StaticFileCompressionTest, MaxLength) {
  8724. auto port = start([](Server &svr) {
  8725. svr.set_static_file_compression(true);
  8726. svr.set_static_file_compression_min_length(0);
  8727. svr.set_static_file_compression_max_length(1024);
  8728. });
  8729. Client cli(HOST, port);
  8730. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8731. // defines `small` as a macro on Windows.
  8732. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8733. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8734. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8735. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8736. // Under it: compressed.
  8737. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8738. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8739. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8740. }
  8741. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8742. auto port = start(enable_without_floor);
  8743. Client cli(HOST, port);
  8744. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8745. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8746. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8747. auto identity_etag = identity->get_header_value("ETag");
  8748. ASSERT_FALSE(identity_etag.empty());
  8749. auto gzipped =
  8750. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8751. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8752. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8753. auto gzip_etag = gzipped->get_header_value("ETag");
  8754. ASSERT_FALSE(gzip_etag.empty());
  8755. // Two representations, two validators.
  8756. EXPECT_NE(identity_etag, gzip_etag);
  8757. // Each one revalidates against the request that would produce it...
  8758. auto fresh =
  8759. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8760. {"If-None-Match", gzip_etag}});
  8761. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8762. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8763. auto fresh_identity =
  8764. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8765. {"If-None-Match", identity_etag}});
  8766. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8767. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8768. // ...and not against the other representation.
  8769. auto crossed =
  8770. cli.Get("/dir/index.html",
  8771. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8772. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8773. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8774. }
  8775. // The opt-in covers responses the server reads off disk itself. A caller's own
  8776. // known-length provider keeps its Content-Length and, more importantly, keeps
  8777. // delivering incrementally: routing it through a compressor would hold every
  8778. // write back until zlib's window filled.
  8779. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8780. auto port = start(enable);
  8781. Client cli(HOST, port);
  8782. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8784. EXPECT_EQ(StatusCode::OK_200, res->status);
  8785. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8786. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8787. EXPECT_EQ("aaabbb", res->body);
  8788. }
  8789. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8790. auto port = start(enable);
  8791. Client cli(HOST, port);
  8792. cli.set_read_timeout(1, 0);
  8793. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8794. Headers{{"Accept-Encoding", "gzip"}});
  8795. ASSERT_TRUE(handle.is_valid());
  8796. // The provider writes 100 bytes and then stalls for longer than the read
  8797. // timeout. Those first bytes have to arrive anyway: run the response through
  8798. // a compressor and zlib holds them until its window fills, so the read would
  8799. // come back empty instead.
  8800. char buf[256];
  8801. auto n = handle.read(buf, sizeof(buf));
  8802. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8803. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8804. }
  8805. #endif
  8806. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8807. TEST_F(ServerTest, Brotli) {
  8808. Headers headers;
  8809. headers.emplace("Accept-Encoding", "br");
  8810. auto res = cli_.Get("/compress", headers);
  8811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8812. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8813. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8814. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8815. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8816. "7890123456789012345678901234567890",
  8817. res->body);
  8818. EXPECT_EQ(StatusCode::OK_200, res->status);
  8819. }
  8820. #endif
  8821. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8822. TEST_F(ServerTest, Zstd) {
  8823. Headers headers;
  8824. headers.emplace("Accept-Encoding", "zstd");
  8825. auto res = cli_.Get("/compress", headers);
  8826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8827. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8828. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8829. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8830. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8831. "7890123456789012345678901234567890",
  8832. res->body);
  8833. EXPECT_EQ(StatusCode::OK_200, res->status);
  8834. }
  8835. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8836. Headers headers;
  8837. headers.emplace("Accept-Encoding", "");
  8838. auto res = cli_.Get("/compress", headers);
  8839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8840. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8841. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8842. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8843. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8844. "7890123456789012345678901234567890",
  8845. res->body);
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. }
  8848. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8849. Headers headers;
  8850. headers.emplace("Accept-Encoding", "zstd");
  8851. std::string body;
  8852. auto res = cli_.Get("/compress", headers,
  8853. [&](const char *data, uint64_t data_length) {
  8854. EXPECT_EQ(100U, data_length);
  8855. body.append(data, data_length);
  8856. return true;
  8857. });
  8858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8859. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8860. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8861. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8862. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8863. "7890123456789012345678901234567890",
  8864. body);
  8865. EXPECT_EQ(StatusCode::OK_200, res->status);
  8866. }
  8867. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8868. Headers headers;
  8869. headers.emplace("Accept-Encoding", "zstd");
  8870. cli_.set_decompress(false);
  8871. auto res = cli_.Get("/compress", headers);
  8872. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8873. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8874. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8875. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8877. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8878. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8879. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8880. EXPECT_EQ(StatusCode::OK_200, res->status);
  8881. ASSERT_EQ(26U, res->body.size());
  8882. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8883. 0);
  8884. }
  8885. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8886. Headers headers;
  8887. headers.emplace("Accept-Encoding", "");
  8888. std::string body;
  8889. auto res = cli_.Get("/compress", headers,
  8890. [&](const char *data, uint64_t data_length) {
  8891. EXPECT_EQ(100U, data_length);
  8892. body.append(data, data_length);
  8893. return true;
  8894. });
  8895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8896. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8897. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8898. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8899. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8900. "7890123456789012345678901234567890",
  8901. body);
  8902. EXPECT_EQ(StatusCode::OK_200, res->status);
  8903. }
  8904. TEST_F(ServerTest, NoZstd) {
  8905. Headers headers;
  8906. headers.emplace("Accept-Encoding", "zstd");
  8907. auto res = cli_.Get("/nocompress", headers);
  8908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8909. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8910. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8911. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8912. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8913. "7890123456789012345678901234567890",
  8914. res->body);
  8915. EXPECT_EQ(StatusCode::OK_200, res->status);
  8916. }
  8917. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8918. Headers headers;
  8919. headers.emplace("Accept-Encoding", "zstd");
  8920. std::string body;
  8921. auto res = cli_.Get("/nocompress", headers,
  8922. [&](const char *data, uint64_t data_length) {
  8923. EXPECT_EQ(100U, data_length);
  8924. body.append(data, data_length);
  8925. return true;
  8926. });
  8927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8928. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8929. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8930. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8931. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8932. "7890123456789012345678901234567890",
  8933. body);
  8934. EXPECT_EQ(StatusCode::OK_200, res->status);
  8935. }
  8936. // TODO: How to enable zstd ??
  8937. TEST_F(ServerTest, MultipartFormDataZstd) {
  8938. UploadFormDataItems items = {
  8939. {"key1", "test", "", ""},
  8940. {"key2", "--abcdefg123", "", ""},
  8941. };
  8942. Headers headers;
  8943. headers.emplace("Accept-Encoding", "zstd");
  8944. cli_.set_compress(true);
  8945. auto res = cli_.Post("/compress-multipart", headers, items);
  8946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8947. EXPECT_EQ(StatusCode::OK_200, res->status);
  8948. }
  8949. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8950. Headers headers;
  8951. headers.emplace("Accept-Encoding", "zstd");
  8952. cli_.set_compress(true);
  8953. auto res = cli_.Put(
  8954. "/put", headers, 3,
  8955. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8956. sink.os << "PUT";
  8957. return true;
  8958. },
  8959. "text/plain");
  8960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8961. EXPECT_EQ(StatusCode::OK_200, res->status);
  8962. EXPECT_EQ("PUT", res->body);
  8963. }
  8964. // Pre-compression logging tests
  8965. TEST_F(ServerTest, PreCompressionLogging) {
  8966. // Test data for compression (matches the actual /compress endpoint content)
  8967. const std::string test_content =
  8968. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8969. "3456789012345678901234567890";
  8970. // Variables to capture logging data
  8971. std::string pre_compression_body;
  8972. std::string pre_compression_content_type;
  8973. std::string pre_compression_content_encoding;
  8974. std::string post_compression_body;
  8975. std::string post_compression_content_type;
  8976. std::string post_compression_content_encoding;
  8977. // Set up pre-compression logger
  8978. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8979. const Response &res) {
  8980. pre_compression_body = res.body;
  8981. pre_compression_content_type = res.get_header_value("Content-Type");
  8982. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8983. });
  8984. // Set up post-compression logger
  8985. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8986. post_compression_body = res.body;
  8987. post_compression_content_type = res.get_header_value("Content-Type");
  8988. post_compression_content_encoding =
  8989. res.get_header_value("Content-Encoding");
  8990. });
  8991. // Test with gzip compression
  8992. Headers headers;
  8993. headers.emplace("Accept-Encoding", "gzip");
  8994. auto res = cli_.Get("/compress", headers);
  8995. // Verify response was compressed
  8996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8997. EXPECT_EQ(StatusCode::OK_200, res->status);
  8998. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8999. // Verify pre-compression logger captured uncompressed content
  9000. EXPECT_EQ(test_content, pre_compression_body);
  9001. EXPECT_EQ("text/plain", pre_compression_content_type);
  9002. EXPECT_TRUE(pre_compression_content_encoding
  9003. .empty()); // No encoding header before compression
  9004. // Verify post-compression logger captured compressed content
  9005. EXPECT_NE(test_content,
  9006. post_compression_body); // Should be different after compression
  9007. EXPECT_EQ("text/plain", post_compression_content_type);
  9008. EXPECT_EQ("gzip", post_compression_content_encoding);
  9009. // Verify compressed content is smaller
  9010. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9011. }
  9012. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9013. const std::string test_content =
  9014. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9015. "3456789012345678901234567890";
  9016. std::string pre_compression_body;
  9017. std::string post_compression_body;
  9018. svr_.set_pre_compression_logger(
  9019. [&](const Request & /*req*/, const Response &res) {
  9020. pre_compression_body = res.body;
  9021. });
  9022. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9023. post_compression_body = res.body;
  9024. });
  9025. Headers headers;
  9026. headers.emplace("Accept-Encoding", "br");
  9027. auto res = cli_.Get("/compress", headers);
  9028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9029. EXPECT_EQ(StatusCode::OK_200, res->status);
  9030. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9031. // Verify pre-compression content is uncompressed
  9032. EXPECT_EQ(test_content, pre_compression_body);
  9033. // Verify post-compression content is compressed
  9034. EXPECT_NE(test_content, post_compression_body);
  9035. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9036. }
  9037. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9038. const std::string test_content =
  9039. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9040. "3456789012345678901234567890";
  9041. std::string pre_compression_body;
  9042. std::string post_compression_body;
  9043. svr_.set_pre_compression_logger(
  9044. [&](const Request & /*req*/, const Response &res) {
  9045. pre_compression_body = res.body;
  9046. });
  9047. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9048. post_compression_body = res.body;
  9049. });
  9050. // Request without compression (use /nocompress endpoint)
  9051. Headers headers;
  9052. auto res = cli_.Get("/nocompress", headers);
  9053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9054. EXPECT_EQ(StatusCode::OK_200, res->status);
  9055. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9056. // Pre-compression logger should not be called when no compression is applied
  9057. EXPECT_TRUE(
  9058. pre_compression_body.empty()); // Pre-compression logger not called
  9059. EXPECT_EQ(
  9060. test_content,
  9061. post_compression_body); // Post-compression logger captures final content
  9062. }
  9063. TEST_F(ServerTest, LoggerSeesContentLength) {
  9064. size_t logged_content_length = 0;
  9065. std::string logged_content_length_header;
  9066. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9067. logged_content_length = res.content_length_;
  9068. logged_content_length_header = res.get_header_value("Content-Length");
  9069. });
  9070. auto res = cli_.Get("/nocompress");
  9071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9072. EXPECT_EQ(StatusCode::OK_200, res->status);
  9073. EXPECT_EQ(res->body.size(), logged_content_length);
  9074. EXPECT_EQ(std::to_string(logged_content_length),
  9075. logged_content_length_header);
  9076. }
  9077. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9078. const std::string test_content =
  9079. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9080. "3456789012345678901234567890";
  9081. std::string pre_compression_body;
  9082. bool pre_logger_called = false;
  9083. // Set only pre-compression logger
  9084. svr_.set_pre_compression_logger(
  9085. [&](const Request & /*req*/, const Response &res) {
  9086. pre_compression_body = res.body;
  9087. pre_logger_called = true;
  9088. });
  9089. Headers headers;
  9090. headers.emplace("Accept-Encoding", "gzip");
  9091. auto res = cli_.Get("/compress", headers);
  9092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9093. EXPECT_EQ(StatusCode::OK_200, res->status);
  9094. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9095. // Verify pre-compression logger was called
  9096. EXPECT_TRUE(pre_logger_called);
  9097. EXPECT_EQ(test_content, pre_compression_body);
  9098. }
  9099. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9100. {
  9101. // Test with Expect: 100-continue header - success case
  9102. // Server returns 100 Continue, client sends body, server returns 200 OK
  9103. Request req;
  9104. req.method = "POST";
  9105. req.path = "/post-large";
  9106. req.set_header("Expect", "100-continue");
  9107. req.body = LARGE_DATA;
  9108. Response res;
  9109. auto error = Error::Success;
  9110. cli_.set_keep_alive(true);
  9111. auto ret = cli_.send(req, res, error);
  9112. EXPECT_TRUE(ret);
  9113. EXPECT_EQ(StatusCode::OK_200, res.status);
  9114. EXPECT_EQ(LARGE_DATA, res.body);
  9115. }
  9116. {
  9117. // Test with Expect: 100-continue header - error case
  9118. // Client should not send the body when server returns an error
  9119. Request req;
  9120. req.method = "POST";
  9121. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9122. req.set_header("Expect", "100-continue");
  9123. req.body = LARGE_DATA;
  9124. Response res;
  9125. auto error = Error::Success;
  9126. auto start = std::chrono::high_resolution_clock::now();
  9127. cli_.set_keep_alive(true);
  9128. auto ret = cli_.send(req, res, error);
  9129. auto end = std::chrono::high_resolution_clock::now();
  9130. auto elapsed =
  9131. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9132. .count();
  9133. // With Expect: 100-continue, request completes successfully but with error
  9134. EXPECT_TRUE(ret);
  9135. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9136. EXPECT_EQ("close", res.get_header_value("Connection"));
  9137. EXPECT_FALSE(cli_.is_socket_open());
  9138. EXPECT_LE(elapsed, 2000);
  9139. }
  9140. {
  9141. // Send an extra GET request to ensure error recovery without hanging
  9142. Request req;
  9143. req.method = "GET";
  9144. req.path = "/hi";
  9145. auto start = std::chrono::high_resolution_clock::now();
  9146. auto res = cli_.send(req);
  9147. auto end = std::chrono::high_resolution_clock::now();
  9148. auto elapsed =
  9149. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9150. .count();
  9151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9152. EXPECT_EQ(StatusCode::OK_200, res->status);
  9153. EXPECT_EQ("Hello World!", res->body);
  9154. EXPECT_LE(elapsed, 500);
  9155. }
  9156. }
  9157. TEST(ZstdDecompressor, ChunkedDecompression) {
  9158. std::string data;
  9159. for (size_t i = 0; i < 32 * 1024; ++i) {
  9160. data.push_back(static_cast<char>('a' + i % 26));
  9161. }
  9162. std::string compressed_data;
  9163. {
  9164. httplib::detail::zstd_compressor compressor;
  9165. bool result = compressor.compress(
  9166. data.data(), data.size(),
  9167. /*last=*/true,
  9168. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9169. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9170. compressed_data_size);
  9171. return true;
  9172. });
  9173. ASSERT_TRUE(result);
  9174. }
  9175. std::string decompressed_data;
  9176. {
  9177. httplib::detail::zstd_decompressor decompressor;
  9178. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9179. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9180. size_t chunk_size = 130;
  9181. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9182. chunk_begin += chunk_size) {
  9183. size_t current_chunk_size =
  9184. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9185. bool result = decompressor.decompress(
  9186. compressed_data.data() + chunk_begin, current_chunk_size,
  9187. [&](const char *decompressed_data_chunk,
  9188. size_t decompressed_data_chunk_size) {
  9189. decompressed_data.insert(decompressed_data.size(),
  9190. decompressed_data_chunk,
  9191. decompressed_data_chunk_size);
  9192. return true;
  9193. });
  9194. ASSERT_TRUE(result);
  9195. }
  9196. }
  9197. ASSERT_EQ(data, decompressed_data);
  9198. }
  9199. TEST(ZstdDecompressor, Decompress) {
  9200. std::string original_text = "Compressed with ZSTD";
  9201. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9202. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9203. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9204. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9205. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9206. std::string decompressed_data;
  9207. {
  9208. httplib::detail::zstd_decompressor decompressor;
  9209. bool result = decompressor.decompress(
  9210. compressed_data.data(), compressed_data.size(),
  9211. [&](const char *decompressed_data_chunk,
  9212. size_t decompressed_data_chunk_size) {
  9213. decompressed_data.insert(decompressed_data.size(),
  9214. decompressed_data_chunk,
  9215. decompressed_data_chunk_size);
  9216. return true;
  9217. });
  9218. ASSERT_TRUE(result);
  9219. }
  9220. ASSERT_EQ(original_text, decompressed_data);
  9221. }
  9222. #endif
  9223. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9224. // separate chunks so that the server sees each part in its own read(). Used to
  9225. // place a read boundary at a specific offset of a request body.
  9226. static bool send_request_in_parts(time_t read_timeout_sec,
  9227. const std::vector<std::string> &parts,
  9228. std::string *resp = nullptr,
  9229. int port = PORT) {
  9230. auto error = Error::Success;
  9231. auto client_sock = detail::create_client_socket(
  9232. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9233. /*connection_timeout_sec=*/5, 0,
  9234. /*read_timeout_sec=*/5, 0,
  9235. /*write_timeout_sec=*/5, 0, std::string(), error);
  9236. if (client_sock == INVALID_SOCKET) { return false; }
  9237. auto ret = detail::process_client_socket(
  9238. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9239. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9240. for (size_t i = 0; i < parts.size(); i++) {
  9241. const auto &part = parts[i];
  9242. if (part.size() !=
  9243. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9244. return false;
  9245. }
  9246. if (i + 1 < parts.size()) {
  9247. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9248. }
  9249. }
  9250. char buf[512];
  9251. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9252. while (line_reader.getline()) {
  9253. if (resp) { *resp += line_reader.ptr(); }
  9254. }
  9255. return true;
  9256. });
  9257. detail::close_socket(client_sock);
  9258. return ret;
  9259. }
  9260. // Sends a raw request to a server listening at HOST:PORT.
  9261. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9262. std::string *resp = nullptr, int port = PORT) {
  9263. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9264. }
  9265. #ifdef CPPHTTPLIB_SSL_ENABLED
  9266. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9267. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9268. ASSERT_TRUE(svr.is_valid());
  9269. svr.set_read_timeout(1, 0);
  9270. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9271. auto se = detail::scope_exit([&] {
  9272. svr.stop();
  9273. t.join();
  9274. ASSERT_FALSE(svr.is_running());
  9275. });
  9276. svr.wait_until_ready();
  9277. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9278. // keeps each wait well within the read timeout. The server gives up a
  9279. // second in, so the bytes sent after that fail.
  9280. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9281. parts.resize(26, std::string(1, '\0'));
  9282. EXPECT_FALSE(send_request_in_parts(5, parts));
  9283. }
  9284. #endif
  9285. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9286. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9287. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9288. const std::vector<std::string> &parts,
  9289. std::string *resp = nullptr,
  9290. int port = PORT) {
  9291. auto error = Error::Success;
  9292. auto sock = detail::create_client_socket(
  9293. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9294. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9295. /*write_timeout_sec=*/5, 0, std::string(), error);
  9296. if (sock == INVALID_SOCKET) { return false; }
  9297. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9298. auto ctx = SSL_CTX_new(TLS_client_method());
  9299. auto ssl = SSL_new(ctx);
  9300. auto ssl_se = detail::scope_exit([&] {
  9301. SSL_free(ssl);
  9302. SSL_CTX_free(ctx);
  9303. });
  9304. SSL_set_fd(ssl, static_cast<int>(sock));
  9305. if (SSL_connect(ssl) != 1) { return false; }
  9306. for (size_t i = 0; i < parts.size(); i++) {
  9307. const auto &part = parts[i];
  9308. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9309. static_cast<int>(part.size())) {
  9310. return false;
  9311. }
  9312. if (i + 1 < parts.size()) {
  9313. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9314. }
  9315. }
  9316. char buf[512];
  9317. int n;
  9318. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9319. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9320. }
  9321. return true;
  9322. }
  9323. #endif
  9324. // The request line, then a header value a byte at a time.
  9325. static std::vector<std::string> slow_request_head_parts() {
  9326. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9327. parts.resize(26, "a");
  9328. parts.emplace_back("\r\n\r\n");
  9329. return parts;
  9330. }
  9331. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9332. // within the one-second read timeout. The server gives up a second in, before
  9333. // the head is complete.
  9334. static void
  9335. expect_slow_request_head_dropped(Server &svr,
  9336. const std::function<std::string()> &send) {
  9337. std::atomic<bool> handled(false);
  9338. svr.Get("/", [&](const Request &, Response &res) {
  9339. handled = true;
  9340. res.set_content("ok", "text/plain");
  9341. });
  9342. svr.set_read_timeout(1, 0);
  9343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9344. auto se = detail::scope_exit([&] {
  9345. svr.stop();
  9346. t.join();
  9347. ASSERT_FALSE(svr.is_running());
  9348. });
  9349. svr.wait_until_ready();
  9350. auto resp = send();
  9351. EXPECT_FALSE(handled);
  9352. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9353. }
  9354. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9355. Server svr;
  9356. expect_slow_request_head_dropped(svr, [] {
  9357. std::string resp;
  9358. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9359. return resp;
  9360. });
  9361. }
  9362. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9363. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9365. ASSERT_TRUE(svr.is_valid());
  9366. expect_slow_request_head_dropped(svr, [] {
  9367. std::string resp;
  9368. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9369. return resp;
  9370. });
  9371. }
  9372. #endif
  9373. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9374. Server svr;
  9375. std::string header_value;
  9376. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9377. header_value = req.get_header_value("foo");
  9378. res.set_content("ok", "text/plain");
  9379. });
  9380. thread t = thread([&] { svr.listen(HOST, PORT); });
  9381. auto se = detail::scope_exit([&] {
  9382. svr.stop();
  9383. t.join();
  9384. ASSERT_FALSE(svr.is_running());
  9385. });
  9386. svr.wait_until_ready();
  9387. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9388. // like characters are not treated the same - use vertical tab and escape.
  9389. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9390. "foo: \t \v bar \x1B\t \r\n"
  9391. "Connection: close\r\n"
  9392. "\r\n";
  9393. std::string res;
  9394. ASSERT_TRUE(send_request(5, req, &res));
  9395. EXPECT_EQ(header_value, "");
  9396. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9397. }
  9398. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9399. Server svr;
  9400. std::string received;
  9401. svr.Get("/order", [&](const Request &req, Response &res) {
  9402. received = entries_to_string(req.headers);
  9403. res.set_content("ok", "text/plain");
  9404. });
  9405. auto port = svr.bind_to_any_port(HOST);
  9406. thread t = thread([&] { svr.listen_after_bind(); });
  9407. auto se = detail::scope_exit([&] {
  9408. svr.stop();
  9409. t.join();
  9410. ASSERT_FALSE(svr.is_running());
  9411. });
  9412. svr.wait_until_ready();
  9413. const std::string req = "GET /order HTTP/1.1\r\n"
  9414. "Host: localhost\r\n"
  9415. "X-First: 1\r\n"
  9416. "X-Dup: a\r\n"
  9417. "X-Second: 2\r\n"
  9418. "X-Dup: b\r\n"
  9419. "Connection: close\r\n"
  9420. "\r\n";
  9421. std::string res;
  9422. ASSERT_TRUE(send_request(5, req, &res, port));
  9423. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9424. EXPECT_EQ(
  9425. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9426. received);
  9427. }
  9428. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9429. Server svr;
  9430. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9431. res.set_header("Set-Cookie", "first=1");
  9432. res.set_header("X-Between", "y");
  9433. res.set_header("Set-Cookie", "second=2");
  9434. res.set_content("ok", "text/plain");
  9435. });
  9436. auto port = svr.bind_to_any_port(HOST);
  9437. thread t = thread([&] { svr.listen_after_bind(); });
  9438. auto se = detail::scope_exit([&] {
  9439. svr.stop();
  9440. t.join();
  9441. ASSERT_FALSE(svr.is_running());
  9442. });
  9443. svr.wait_until_ready();
  9444. Client cli(HOST, port);
  9445. auto res = cli.Get("/cookies");
  9446. ASSERT_TRUE(res);
  9447. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9448. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9449. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9450. }
  9451. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9452. Server svr;
  9453. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9454. auto i = new int(0);
  9455. res.set_header("Trailer", "X-Safe, X-Reflected");
  9456. res.set_chunked_content_provider(
  9457. "text/plain",
  9458. [i](size_t /*offset*/, DataSink &sink) {
  9459. if (*i == 0) {
  9460. sink.os << "body";
  9461. } else {
  9462. Headers trailer;
  9463. // A valid trailer that must survive.
  9464. trailer.emplace("X-Safe", "safe");
  9465. // Attacker-controlled value carrying CR/LF (response splitting).
  9466. trailer.emplace("X-Reflected",
  9467. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9468. // Attacker-controlled name carrying CR/LF.
  9469. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9470. sink.done_with_trailer(trailer);
  9471. }
  9472. (*i)++;
  9473. return true;
  9474. },
  9475. [i](bool /*success*/) { delete i; });
  9476. });
  9477. thread t = thread([&] { svr.listen(HOST, PORT); });
  9478. auto se = detail::scope_exit([&] {
  9479. svr.stop();
  9480. t.join();
  9481. ASSERT_FALSE(svr.is_running());
  9482. });
  9483. svr.wait_until_ready();
  9484. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9485. "Host: " + HOST +
  9486. "\r\n"
  9487. "Connection: close\r\n"
  9488. "\r\n";
  9489. std::string res;
  9490. ASSERT_TRUE(send_request(5, req, &res));
  9491. // The injected fields must not appear anywhere in the raw response.
  9492. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9493. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9494. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9495. // Invalid trailers are dropped entirely, matching set_header().
  9496. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9497. // The valid trailer still passes through.
  9498. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9499. }
  9500. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9501. Server svr;
  9502. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9503. // res.headers is a public field an application can populate directly,
  9504. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9505. // A valid header that must survive.
  9506. res.headers.emplace("X-Safe", "safe");
  9507. // Attacker-controlled value carrying CR/LF (response splitting).
  9508. res.headers.emplace("X-Reflected",
  9509. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9510. // Attacker-controlled name carrying CR/LF.
  9511. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9512. res.set_content("body", "text/plain");
  9513. });
  9514. thread t = thread([&] { svr.listen(HOST, PORT); });
  9515. auto se = detail::scope_exit([&] {
  9516. svr.stop();
  9517. t.join();
  9518. ASSERT_FALSE(svr.is_running());
  9519. });
  9520. svr.wait_until_ready();
  9521. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9522. "Host: " + HOST +
  9523. "\r\n"
  9524. "Connection: close\r\n"
  9525. "\r\n";
  9526. std::string res;
  9527. ASSERT_TRUE(send_request(5, req, &res));
  9528. // The injected fields must not appear anywhere in the raw response.
  9529. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9530. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9531. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9532. // Invalid headers are dropped entirely, matching set_header().
  9533. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9534. // The valid header still passes through.
  9535. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9536. }
  9537. // Forward declaration: in split builds split.py strips `inline` and moves the
  9538. // definition into httplib.cc, so detail::write_request_line is not visible from
  9539. // the public httplib.h. Re-declaring it here lets the tests link against the
  9540. // symbol in both header-only and split builds.
  9541. namespace httplib {
  9542. namespace detail {
  9543. ssize_t write_request_line(Stream &strm, const std::string &method,
  9544. const std::string &path);
  9545. } // namespace detail
  9546. } // namespace httplib
  9547. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9548. // A well-formed target is written verbatim.
  9549. {
  9550. detail::BufferStream strm;
  9551. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9552. EXPECT_GT(n, 0);
  9553. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9554. }
  9555. // A target carrying CR/LF, SP or other control octets must be rejected
  9556. // before anything reaches the wire, otherwise it splits the request line and
  9557. // injects a header or a whole request.
  9558. const std::string evil_targets[] = {
  9559. "/a\r\nInjected: pwned",
  9560. "/a\rInjected",
  9561. "/a\nInjected",
  9562. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9563. "/a b",
  9564. "/a\tb",
  9565. "/a\x7f",
  9566. };
  9567. for (const auto &evil : evil_targets) {
  9568. detail::BufferStream strm;
  9569. auto n = detail::write_request_line(strm, "GET", evil);
  9570. EXPECT_LT(n, 0);
  9571. EXPECT_TRUE(strm.get_buffer().empty());
  9572. }
  9573. }
  9574. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9575. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9576. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9577. // target reaches write_request. The client must fail cleanly with
  9578. // Error::Write instead of putting a request-line-less, header-injecting
  9579. // request on the wire.
  9580. Server svr;
  9581. svr.Get("/a", [](const Request &, Response &res) {
  9582. res.set_content("ok", "text/plain");
  9583. });
  9584. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9585. auto se = detail::scope_exit([&] {
  9586. svr.stop();
  9587. thread.join();
  9588. ASSERT_FALSE(svr.is_running());
  9589. });
  9590. svr.wait_until_ready();
  9591. {
  9592. Client cli(HOST, PORT);
  9593. cli.set_path_encode(false);
  9594. // The request is rejected before anything is written, so the connection
  9595. // stays silent and the subsequent response read would otherwise block for
  9596. // the full default read timeout. Shorten it -- the assertion is on the
  9597. // error, not the timeout.
  9598. cli.set_read_timeout(1, 0);
  9599. auto res = cli.Get("/a\r\nInjected: pwned");
  9600. EXPECT_FALSE(res);
  9601. EXPECT_EQ(Error::Write, res.error());
  9602. }
  9603. }
  9604. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9605. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9606. // including extension methods.
  9607. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9608. for (const auto &method : good_methods) {
  9609. detail::BufferStream strm;
  9610. auto n = detail::write_request_line(strm, method, "/");
  9611. EXPECT_GT(n, 0);
  9612. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9613. }
  9614. // A method carrying CR/LF would split the request line and smuggle a whole
  9615. // request ahead of the real one. A space or an empty method corrupts the
  9616. // request line. All must be rejected before anything reaches the wire.
  9617. const std::string evil_methods[] = {
  9618. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9619. "GET\r\nInjected: pwned",
  9620. "GET\r",
  9621. "GET\n",
  9622. "GE T",
  9623. "",
  9624. };
  9625. for (const auto &evil : evil_methods) {
  9626. detail::BufferStream strm;
  9627. auto n = detail::write_request_line(strm, evil, "/");
  9628. EXPECT_LT(n, 0);
  9629. EXPECT_TRUE(strm.get_buffer().empty());
  9630. }
  9631. }
  9632. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9633. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9634. // through Client::send must fail with Error::Write and no request, neither
  9635. // the smuggled one nor the real one, may reach the server.
  9636. Server svr;
  9637. std::atomic<int> request_count(0);
  9638. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9639. request_count++;
  9640. res.status = StatusCode::OK_200;
  9641. return Server::HandlerResponse::Handled;
  9642. });
  9643. auto port = svr.bind_to_any_port(HOST);
  9644. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9645. auto se = detail::scope_exit([&] {
  9646. svr.stop();
  9647. thread.join();
  9648. ASSERT_FALSE(svr.is_running());
  9649. });
  9650. svr.wait_until_ready();
  9651. {
  9652. Client cli(HOST, port);
  9653. const std::string evil_methods[] = {
  9654. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9655. "GE T",
  9656. "",
  9657. };
  9658. for (const auto &evil : evil_methods) {
  9659. Request req;
  9660. req.method = evil;
  9661. req.path = "/";
  9662. auto res = cli.send(req);
  9663. EXPECT_FALSE(res);
  9664. EXPECT_EQ(Error::Write, res.error());
  9665. }
  9666. auto handle =
  9667. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9668. EXPECT_FALSE(handle.is_valid());
  9669. EXPECT_EQ(Error::Write, handle.error);
  9670. // A valid request on the same client still goes through.
  9671. auto res = cli.Get("/");
  9672. ASSERT_TRUE(res);
  9673. EXPECT_EQ(StatusCode::OK_200, res->status);
  9674. }
  9675. EXPECT_EQ(1, request_count.load());
  9676. }
  9677. // Sends a raw request and verifies that there isn't a crash or exception.
  9678. static void test_raw_request(const std::string &req,
  9679. std::string *out = nullptr) {
  9680. Server svr;
  9681. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9682. res.set_content("ok", "text/plain");
  9683. });
  9684. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9685. res.set_content("ok", "text/plain");
  9686. });
  9687. svr.Get("/header_field_value_check",
  9688. [&](const Request & /*req*/, Response &res) {
  9689. res.set_content("ok", "text/plain");
  9690. });
  9691. svr.CustomRoute("PROPFIND", "/dav",
  9692. [&](const Request & /*req*/, Response &res) {
  9693. res.status = StatusCode::MultiStatus_207;
  9694. });
  9695. // Server read timeout must be longer than the client read timeout for the
  9696. // bug to reproduce, probably to force the server to process a request
  9697. // without a trailing blank line.
  9698. const time_t client_read_timeout_sec = 1;
  9699. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9700. bool listen_thread_ok = false;
  9701. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9702. auto se = detail::scope_exit([&] {
  9703. svr.stop();
  9704. t.join();
  9705. ASSERT_FALSE(svr.is_running());
  9706. EXPECT_TRUE(listen_thread_ok);
  9707. });
  9708. svr.wait_until_ready();
  9709. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9710. }
  9711. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9712. // A certain header line causes an exception if the header property is parsed
  9713. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9714. test_raw_request(
  9715. "GET /hi HTTP/1.1\r\n"
  9716. " : "
  9717. " "
  9718. " ");
  9719. }
  9720. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9721. // A certain header line causes an exception if the header property *name* is
  9722. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9723. // greedy matcher and requires backtracking when there are a lot of ":"
  9724. // characters.
  9725. // This occurs with libc++ but not libstdc++.
  9726. test_raw_request(
  9727. "GET /hi HTTP/1.1\r\n"
  9728. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9729. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9730. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9731. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9732. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9733. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9734. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9735. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9736. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9737. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9738. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9739. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9740. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9741. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9742. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9743. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9744. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9745. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9746. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9747. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9748. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9749. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9750. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9751. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9752. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9753. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9754. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9755. "&&&%%%");
  9756. }
  9757. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9758. // Make sure this doesn't crash the server.
  9759. // In a previous version of the header line regex, the "\r" rendered the line
  9760. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9761. // a new position where the leading white space ended and the field value
  9762. // began.
  9763. // The crash occurs with libc++ but not libstdc++.
  9764. test_raw_request("GET /hi HTTP/1.1\r\n"
  9765. "a:" +
  9766. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9767. "\r\n"
  9768. "\r\n");
  9769. }
  9770. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9771. const char *rejected[] = {
  9772. // RFC 9112 §3: one SP between the parts, and nothing else
  9773. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9774. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9775. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9776. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9777. // A request-target has no fragment
  9778. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9779. // An HTTP/1.1 request needs a Host
  9780. "GET /hi HTTP/1.1\r\n\r\n",
  9781. };
  9782. for (auto request : rejected) {
  9783. std::string out;
  9784. test_raw_request(request, &out);
  9785. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9786. }
  9787. std::string out;
  9788. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9789. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9790. }
  9791. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9792. // RFC 9112 §6.1
  9793. const char *requests[] = {
  9794. "PUT /put_hi HTTP/1.1\r\n"
  9795. "Host: localhost\r\n"
  9796. "Content-Length: 0\r\n"
  9797. "Transfer-Encoding: chunked\r\n"
  9798. "\r\n"
  9799. "0\r\n\r\n",
  9800. "PUT /put_hi HTTP/1.0\r\n"
  9801. "Connection: keep-alive\r\n"
  9802. "Transfer-Encoding: chunked\r\n"
  9803. "\r\n"
  9804. "0\r\n\r\n",
  9805. };
  9806. for (auto request : requests) {
  9807. std::string out;
  9808. test_raw_request(request, &out);
  9809. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9810. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9811. }
  9812. }
  9813. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9814. std::string out;
  9815. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9816. "Content-Type: text/plain\r\n"
  9817. "Transfer-Encoding: chunked\r\n"
  9818. "\r\n"
  9819. "nothex\r\n",
  9820. &out);
  9821. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9822. }
  9823. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9824. std::string out;
  9825. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9826. "Content-Type: text/plain\r\n"
  9827. "Transfer-Encoding: chunked\r\n"
  9828. "\r\n"
  9829. "3\r\n"
  9830. "xyz\r\n"
  9831. "NaN\r\n",
  9832. &out);
  9833. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9834. }
  9835. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9836. std::string out;
  9837. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9838. "Content-Type: text/plain\r\n"
  9839. "Transfer-Encoding: chunked\r\n"
  9840. "\r\n"
  9841. // Length is too large for 64 bits.
  9842. "1ffffffffffffffff\r\n"
  9843. "xyz\r\n",
  9844. &out);
  9845. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9846. }
  9847. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9848. test_raw_request("GET /hi HTTP/1.1\r\n"
  9849. "Content-Type: text/plain\r\n\r");
  9850. }
  9851. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9852. std::string out;
  9853. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9854. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9855. }
  9856. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9857. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9858. std::string out;
  9859. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9860. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9861. }
  9862. }
  9863. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9864. std::string out;
  9865. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9866. "Host: localhost\r\n"
  9867. "Connection: close\r\n\r\n",
  9868. &out);
  9869. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9870. }
  9871. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9872. Server svr;
  9873. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9874. EXPECT_TRUE(!req.remote_addr.empty());
  9875. });
  9876. thread t = thread([&] { svr.listen(HOST, PORT); });
  9877. auto se = detail::scope_exit([&] {
  9878. svr.stop();
  9879. t.join();
  9880. ASSERT_FALSE(svr.is_running());
  9881. });
  9882. svr.wait_until_ready();
  9883. // Send an invalid request line to trigger Bad Request
  9884. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9885. std::string out;
  9886. ASSERT_TRUE(send_request(5, bad_req, &out));
  9887. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9888. }
  9889. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9890. // answered right away rather than blocking on a read that waits for EOF.
  9891. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9892. std::string out;
  9893. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9894. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9895. }
  9896. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9897. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9898. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9899. for (const auto *method : methods) {
  9900. Server svr;
  9901. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9902. EXPECT_FALSE(svr.is_valid()) << method;
  9903. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9904. }
  9905. }
  9906. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9907. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9908. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9909. for (const auto *method : methods) {
  9910. Server svr;
  9911. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9912. EXPECT_FALSE(svr.is_valid()) << method;
  9913. }
  9914. }
  9915. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9916. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9917. "COPY", "MOVE", "LOCK",
  9918. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9919. Server svr;
  9920. for (const auto *method : methods) {
  9921. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9922. }
  9923. EXPECT_TRUE(svr.is_valid());
  9924. }
  9925. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9926. Server svr;
  9927. svr.CustomRoute("POST", "/x",
  9928. [](const Request &, Response &, const ContentReader &) {});
  9929. EXPECT_FALSE(svr.is_valid());
  9930. }
  9931. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9932. Server svr;
  9933. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9934. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9935. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9936. EXPECT_FALSE(svr.is_valid());
  9937. }
  9938. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9939. Server svr;
  9940. auto captured = Error::Success;
  9941. svr.set_error_logger(
  9942. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9943. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9944. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9945. }
  9946. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9947. std::string out;
  9948. std::string request(
  9949. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9950. test_raw_request(request, &out);
  9951. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9952. }
  9953. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9954. std::string out;
  9955. std::string request(
  9956. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9957. test_raw_request(request, &out);
  9958. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9959. }
  9960. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9961. std::string out;
  9962. std::string request(
  9963. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9964. test_raw_request(request, &out);
  9965. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9966. }
  9967. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9968. std::string out;
  9969. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9970. "Host: localhost\r\n"
  9971. "Test: \r\n\r\n",
  9972. &out);
  9973. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9974. }
  9975. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9976. Server svr;
  9977. std::string x_custom;
  9978. std::string cookie;
  9979. std::string xff;
  9980. std::string x_unicode;
  9981. std::string x_iis;
  9982. svr.Get("/check", [&](const Request &req, Response &res) {
  9983. x_custom = req.get_header_value("X-Custom");
  9984. cookie = req.get_header_value("Cookie");
  9985. xff = req.get_header_value("X-Forwarded-For");
  9986. x_unicode = req.get_header_value("X-Unicode");
  9987. x_iis = req.get_header_value("X-IIS");
  9988. res.set_content("ok", "text/plain");
  9989. });
  9990. thread t = thread([&] { svr.listen(HOST, PORT); });
  9991. auto se = detail::scope_exit([&] {
  9992. svr.stop();
  9993. t.join();
  9994. ASSERT_FALSE(svr.is_running());
  9995. });
  9996. svr.wait_until_ready();
  9997. const std::string req = "GET /check HTTP/1.1\r\n"
  9998. "Host: localhost\r\n"
  9999. "X-Custom: a%0D%0AInjected: b\r\n"
  10000. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10001. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10002. "X-Unicode: %E3%81%82\r\n"
  10003. "X-IIS: %u00E9\r\n"
  10004. "Connection: close\r\n"
  10005. "\r\n";
  10006. std::string res;
  10007. ASSERT_TRUE(send_request(5, req, &res));
  10008. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10009. // Every value must be returned verbatim (wire form), with no decoding.
  10010. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10011. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10012. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10013. EXPECT_EQ("%E3%81%82", x_unicode);
  10014. EXPECT_EQ("%u00E9", x_iis);
  10015. }
  10016. // Applications that previously relied on automatic percent-decoding can
  10017. // reproduce the old behavior by explicitly calling decode_path_component()
  10018. // or, for RFC 3986 conformance, decode_uri_component().
  10019. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10020. Server svr;
  10021. std::string decoded;
  10022. svr.Get("/check", [&](const Request &req, Response &res) {
  10023. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10024. res.set_content("ok", "text/plain");
  10025. });
  10026. thread t = thread([&] { svr.listen(HOST, PORT); });
  10027. auto se = detail::scope_exit([&] {
  10028. svr.stop();
  10029. t.join();
  10030. ASSERT_FALSE(svr.is_running());
  10031. });
  10032. svr.wait_until_ready();
  10033. const std::string req = "GET /check HTTP/1.1\r\n"
  10034. "Host: localhost\r\n"
  10035. "X-Custom: hello%20world\r\n"
  10036. "Connection: close\r\n"
  10037. "\r\n";
  10038. std::string res;
  10039. ASSERT_TRUE(send_request(5, req, &res));
  10040. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10041. EXPECT_EQ("hello world", decoded);
  10042. }
  10043. // Regression test for #2033. Browsers send Referer values that include
  10044. // percent-encoded characters such as %0A inside the URL. Decoding the
  10045. // header value would either trip the post-decode CR/LF/NUL guard (the
  10046. // original bug, returning 400) or, after that guard was relaxed, silently
  10047. // store a literal LF — both unacceptable. The wire form must round-trip.
  10048. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10049. Server svr;
  10050. std::string referer;
  10051. svr.Get("/check", [&](const Request &req, Response &res) {
  10052. referer = req.get_header_value("Referer");
  10053. res.set_content("ok", "text/plain");
  10054. });
  10055. thread t = thread([&] { svr.listen(HOST, PORT); });
  10056. auto se = detail::scope_exit([&] {
  10057. svr.stop();
  10058. t.join();
  10059. ASSERT_FALSE(svr.is_running());
  10060. });
  10061. svr.wait_until_ready();
  10062. const std::string req = "GET /check HTTP/1.1\r\n"
  10063. "Host: localhost\r\n"
  10064. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10065. "Connection: close\r\n"
  10066. "\r\n";
  10067. std::string res;
  10068. ASSERT_TRUE(send_request(5, req, &res));
  10069. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10070. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10071. }
  10072. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10073. Server svr;
  10074. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10075. res.set_header("Cache-Control", "no-cache");
  10076. res.set_chunked_content_provider(
  10077. "text/event-stream", [](size_t offset, DataSink &sink) {
  10078. std::string s = "data:";
  10079. s += std::to_string(offset);
  10080. s += "\n\n";
  10081. auto ret = sink.write(s.data(), s.size());
  10082. EXPECT_TRUE(ret);
  10083. std::this_thread::sleep_for(std::chrono::seconds(1));
  10084. return true;
  10085. });
  10086. });
  10087. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10088. svr.wait_until_ready();
  10089. Client client(HOST, PORT);
  10090. const Headers headers = {{"Accept", "text/event-stream"}};
  10091. auto get_thread = std::thread([&client, &headers]() {
  10092. auto res = client.Get(
  10093. "/events", headers,
  10094. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10095. });
  10096. auto se = detail::scope_exit([&] {
  10097. svr.stop();
  10098. get_thread.join();
  10099. listen_thread.join();
  10100. ASSERT_FALSE(svr.is_running());
  10101. });
  10102. // Give GET time to get a few messages.
  10103. std::this_thread::sleep_for(std::chrono::seconds(2));
  10104. }
  10105. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10106. httplib::Server svr;
  10107. svr.Post("/hi",
  10108. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10109. res.status = StatusCode::OK_200;
  10110. });
  10111. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10112. svr.wait_until_ready();
  10113. Client cli(HOST, PORT);
  10114. auto res = cli.Post("/hi", "data", "text/plain");
  10115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10116. EXPECT_EQ(StatusCode::OK_200, res->status);
  10117. svr.stop();
  10118. thread.join();
  10119. ASSERT_FALSE(svr.is_running());
  10120. res = cli.Post("/hi", "data", "text/plain");
  10121. ASSERT_FALSE(res);
  10122. }
  10123. TEST(ServerStopTest, ListenFailure) {
  10124. Server svr;
  10125. auto t = thread([&]() {
  10126. auto ret = svr.listen("????", PORT);
  10127. EXPECT_FALSE(ret);
  10128. });
  10129. svr.wait_until_ready();
  10130. svr.stop();
  10131. t.join();
  10132. }
  10133. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10134. TEST(ServerStopTest, Decommision) {
  10135. Server svr;
  10136. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10137. for (int i = 0; i < 4; i++) {
  10138. auto is_even = !(i % 2);
  10139. std::thread t{[&] {
  10140. try {
  10141. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10142. if (is_even) {
  10143. throw std::runtime_error("Some thing that happens to go wrong.");
  10144. }
  10145. svr.listen(HOST, PORT);
  10146. } catch (...) { svr.decommission(); }
  10147. }};
  10148. svr.wait_until_ready();
  10149. // Server is up
  10150. {
  10151. Client cli(HOST, PORT);
  10152. auto res = cli.Get("/hi");
  10153. if (is_even) {
  10154. EXPECT_FALSE(res);
  10155. } else {
  10156. EXPECT_TRUE(res);
  10157. EXPECT_EQ("hi...", res->body);
  10158. }
  10159. }
  10160. svr.stop();
  10161. t.join();
  10162. // Server is down...
  10163. {
  10164. Client cli(HOST, PORT);
  10165. auto res = cli.Get("/hi");
  10166. EXPECT_FALSE(res);
  10167. }
  10168. }
  10169. }
  10170. #endif
  10171. // Helper function for string body upload progress tests
  10172. template <typename SetupHandler, typename ClientCall>
  10173. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10174. ClientCall &&client_call,
  10175. const string &body) {
  10176. Server svr;
  10177. setup_handler(svr);
  10178. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10179. auto se = detail::scope_exit([&] {
  10180. svr.stop();
  10181. t.join();
  10182. });
  10183. svr.wait_until_ready();
  10184. Client cli(HOST, PORT);
  10185. vector<uint64_t> progress_values;
  10186. bool progress_called = false;
  10187. auto res =
  10188. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10189. progress_values.push_back(current);
  10190. progress_called = true;
  10191. return true;
  10192. });
  10193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10194. EXPECT_EQ(200, res->status);
  10195. EXPECT_TRUE(progress_called);
  10196. }
  10197. TEST(UploadProgressTest, PostStringBodyBasic) {
  10198. TestStringBodyUploadProgress(
  10199. [](Server &svr) {
  10200. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10201. res.set_content("received", "text/plain");
  10202. });
  10203. },
  10204. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10205. return cli.Post("/test", body, "text/plain", progress_callback);
  10206. },
  10207. "test data for upload progress");
  10208. }
  10209. TEST(UploadProgressTest, PutStringBodyBasic) {
  10210. TestStringBodyUploadProgress(
  10211. [](Server &svr) {
  10212. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10213. res.set_content("put received", "text/plain");
  10214. });
  10215. },
  10216. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10217. return cli.Put("/test", body, "text/plain", progress_callback);
  10218. },
  10219. "put test data for upload progress");
  10220. }
  10221. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10222. TestStringBodyUploadProgress(
  10223. [](Server &svr) {
  10224. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10225. res.set_content("patch received", "text/plain");
  10226. });
  10227. },
  10228. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10229. return cli.Patch("/test", body, "text/plain", progress_callback);
  10230. },
  10231. "patch test data for upload progress");
  10232. }
  10233. // Helper function for content provider upload progress tests
  10234. template <typename SetupHandler, typename ClientCall>
  10235. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10236. ClientCall &&client_call) {
  10237. Server svr;
  10238. setup_handler(svr);
  10239. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10240. auto se = detail::scope_exit([&] {
  10241. svr.stop();
  10242. t.join();
  10243. });
  10244. svr.wait_until_ready();
  10245. Client cli(HOST, PORT);
  10246. vector<uint64_t> progress_values;
  10247. auto res =
  10248. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10249. progress_values.push_back(current);
  10250. return true;
  10251. });
  10252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10253. EXPECT_EQ(200, res->status);
  10254. EXPECT_FALSE(progress_values.empty());
  10255. }
  10256. TEST(UploadProgressTest, PostContentProviderProgress) {
  10257. TestContentProviderUploadProgress(
  10258. [](Server &svr) {
  10259. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10260. res.set_content("provider received", "text/plain");
  10261. });
  10262. },
  10263. [](Client &cli, UploadProgress progress_callback) {
  10264. return cli.Post(
  10265. "/test", 9,
  10266. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10267. sink.os << "test data";
  10268. return true;
  10269. },
  10270. "text/plain", progress_callback);
  10271. });
  10272. }
  10273. // Helper function for multipart upload progress tests
  10274. template <typename SetupHandler, typename ClientCall>
  10275. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10276. ClientCall &&client_call,
  10277. const string &endpoint) {
  10278. Server svr;
  10279. setup_handler(svr);
  10280. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10281. auto se = detail::scope_exit([&] {
  10282. svr.stop();
  10283. t.join();
  10284. });
  10285. svr.wait_until_ready();
  10286. Client cli(HOST, PORT);
  10287. vector<uint64_t> progress_values;
  10288. UploadFormDataItems items = {
  10289. {"field1", "value1", "", ""},
  10290. {"field2", "longer value for progress tracking test", "", ""},
  10291. {"file1", "file content data for upload progress", "test.txt",
  10292. "text/plain"}};
  10293. auto res = client_call(cli, endpoint, items,
  10294. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10295. progress_values.push_back(current);
  10296. return true;
  10297. });
  10298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10299. EXPECT_EQ(200, res->status);
  10300. EXPECT_FALSE(progress_values.empty());
  10301. }
  10302. TEST(UploadProgressTest, PostMultipartProgress) {
  10303. TestMultipartUploadProgress(
  10304. [](Server &svr) {
  10305. svr.Post("/multipart", [](const Request &req, Response &res) {
  10306. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10307. res.set_content("multipart received", "text/plain");
  10308. });
  10309. },
  10310. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10311. UploadProgress progress_callback) {
  10312. return cli.Post(endpoint, items, progress_callback);
  10313. },
  10314. "/multipart");
  10315. }
  10316. // Helper function for basic download progress tests
  10317. template <typename SetupHandler, typename ClientCall>
  10318. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10319. ClientCall &&client_call, const string &endpoint,
  10320. size_t expected_content_size) {
  10321. Server svr;
  10322. setup_handler(svr);
  10323. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10324. auto se = detail::scope_exit([&] {
  10325. svr.stop();
  10326. t.join();
  10327. });
  10328. svr.wait_until_ready();
  10329. Client cli(HOST, PORT);
  10330. vector<uint64_t> progress_values;
  10331. auto res = client_call(cli, endpoint,
  10332. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10333. progress_values.push_back(current);
  10334. return true;
  10335. });
  10336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10337. EXPECT_EQ(200, res->status);
  10338. EXPECT_FALSE(progress_values.empty());
  10339. EXPECT_EQ(expected_content_size, res->body.size());
  10340. }
  10341. TEST(DownloadProgressTest, GetBasic) {
  10342. TestBasicDownloadProgress(
  10343. [](Server &svr) {
  10344. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10345. string content(1000, 'D');
  10346. res.set_content(content, "text/plain");
  10347. });
  10348. },
  10349. [](Client &cli, const string &endpoint,
  10350. DownloadProgress progress_callback) {
  10351. return cli.Get(endpoint, progress_callback);
  10352. },
  10353. "/download", 1000u);
  10354. }
  10355. // Helper function for content receiver download progress tests
  10356. template <typename SetupHandler, typename ClientCall>
  10357. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10358. ClientCall &&client_call,
  10359. const string &endpoint,
  10360. size_t expected_content_size) {
  10361. Server svr;
  10362. setup_handler(svr);
  10363. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10364. auto se = detail::scope_exit([&] {
  10365. svr.stop();
  10366. t.join();
  10367. });
  10368. svr.wait_until_ready();
  10369. Client cli(HOST, PORT);
  10370. vector<uint64_t> progress_values;
  10371. string received_body;
  10372. auto res = client_call(
  10373. cli, endpoint,
  10374. [&](const char *data, size_t data_length) -> bool {
  10375. received_body.append(data, data_length);
  10376. return true;
  10377. },
  10378. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10379. progress_values.push_back(current);
  10380. return true;
  10381. });
  10382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10383. EXPECT_EQ(200, res->status);
  10384. EXPECT_FALSE(progress_values.empty());
  10385. EXPECT_EQ(expected_content_size, received_body.size());
  10386. EXPECT_TRUE(res->body.empty());
  10387. }
  10388. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10389. TestContentReceiverDownloadProgress(
  10390. [](Server &svr) {
  10391. svr.Get("/download-receiver",
  10392. [](const Request & /*req*/, Response &res) {
  10393. string content(2000, 'R');
  10394. res.set_content(content, "text/plain");
  10395. });
  10396. },
  10397. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10398. DownloadProgress progress_callback) {
  10399. return cli.Get(endpoint, content_receiver, progress_callback);
  10400. },
  10401. "/download-receiver", 2000u);
  10402. }
  10403. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10404. // A provider reaching a pass with nothing to hand over - an empty buffer
  10405. // popped off a queue, say - must not be taken to mean the body is finished.
  10406. // It used to end the loop with the terminating chunk unwritten while the
  10407. // server still considered the response complete, so the peer waited for an
  10408. // end that never arrived.
  10409. Server svr;
  10410. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10411. auto step = std::make_shared<int>(0);
  10412. res.set_chunked_content_provider("text/plain",
  10413. [step](size_t /*offset*/, DataSink &sink) {
  10414. switch ((*step)++) {
  10415. case 0: sink.write("", 0); break;
  10416. case 1: sink.write("hello", 5); break;
  10417. default: sink.done(); break;
  10418. }
  10419. return true;
  10420. });
  10421. });
  10422. auto port = svr.bind_to_any_port(HOST);
  10423. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10424. auto listen_se = detail::scope_exit([&] {
  10425. svr.stop();
  10426. listen_thread.join();
  10427. ASSERT_FALSE(svr.is_running());
  10428. });
  10429. svr.wait_until_ready();
  10430. Client cli(HOST, port);
  10431. // Without the fix the body is never terminated, so bound the wait rather
  10432. // than letting the test hang on the default read timeout.
  10433. cli.set_read_timeout(5, 0);
  10434. auto res = cli.Get("/stream");
  10435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10436. EXPECT_EQ(StatusCode::OK_200, res->status);
  10437. EXPECT_EQ("hello", res->body);
  10438. }
  10439. TEST(StreamingTest, NoContentLengthStreaming) {
  10440. Server svr;
  10441. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10442. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10443. if (offset < 6) {
  10444. sink.os << (offset < 3 ? "a" : "b");
  10445. } else {
  10446. sink.done();
  10447. }
  10448. return true;
  10449. });
  10450. });
  10451. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10452. auto listen_se = detail::scope_exit([&] {
  10453. svr.stop();
  10454. listen_thread.join();
  10455. ASSERT_FALSE(svr.is_running());
  10456. });
  10457. svr.wait_until_ready();
  10458. Client client(HOST, PORT);
  10459. auto get_thread = std::thread([&client]() {
  10460. std::string s;
  10461. auto res =
  10462. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10463. s += std::string(data, len);
  10464. return true;
  10465. });
  10466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10467. EXPECT_EQ(StatusCode::OK_200, res->status);
  10468. EXPECT_EQ("aaabbb", s);
  10469. });
  10470. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10471. // Give GET time to get a few messages.
  10472. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10473. }
  10474. TEST(MountTest, Unmount) {
  10475. Server svr;
  10476. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10477. auto se = detail::scope_exit([&] {
  10478. svr.stop();
  10479. listen_thread.join();
  10480. ASSERT_FALSE(svr.is_running());
  10481. });
  10482. svr.wait_until_ready();
  10483. Client cli("localhost", PORT);
  10484. svr.set_mount_point("/mount2", "./www2");
  10485. auto res = cli.Get("/");
  10486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10487. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10488. res = cli.Get("/mount2/dir/test.html");
  10489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10490. EXPECT_EQ(StatusCode::OK_200, res->status);
  10491. svr.set_mount_point("/", "./www");
  10492. res = cli.Get("/dir/");
  10493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10494. EXPECT_EQ(StatusCode::OK_200, res->status);
  10495. svr.remove_mount_point("/");
  10496. res = cli.Get("/dir/");
  10497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10498. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10499. svr.remove_mount_point("/mount2");
  10500. res = cli.Get("/mount2/dir/test.html");
  10501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10502. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10503. }
  10504. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10505. Server svr;
  10506. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10507. svr.Get("/api/hello", [](const Request &, Response &res) {
  10508. res.set_content("api", "text/plain");
  10509. });
  10510. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10511. auto se = detail::scope_exit([&] {
  10512. svr.stop();
  10513. listen_thread.join();
  10514. ASSERT_FALSE(svr.is_running());
  10515. });
  10516. svr.wait_until_ready();
  10517. Client cli(HOST, PORT);
  10518. auto res = cli.Get("/dir/test.html");
  10519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10520. EXPECT_EQ(StatusCode::OK_200, res->status);
  10521. res = cli.Get("/api/hello");
  10522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10523. EXPECT_EQ(StatusCode::OK_200, res->status);
  10524. EXPECT_EQ("api", res->body);
  10525. }
  10526. TEST(MountTest, PathSegmentBoundary) {
  10527. Server svr;
  10528. svr.set_mount_point("/mount2", "./www2");
  10529. svr.set_mount_point("/", "./www");
  10530. auto port = svr.bind_to_any_port(HOST);
  10531. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10532. auto se = detail::scope_exit([&] {
  10533. svr.stop();
  10534. listen_thread.join();
  10535. ASSERT_FALSE(svr.is_running());
  10536. });
  10537. svr.wait_until_ready();
  10538. Client cli(HOST, port);
  10539. auto res = cli.Get("/mount2/dir/test.html");
  10540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10541. EXPECT_EQ(StatusCode::OK_200, res->status);
  10542. // "/mount2" must not match part-way through a path segment.
  10543. res = cli.Get("/mount2dir/test.html");
  10544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10545. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10546. // A mount point ending in '/' keeps matching every path below it.
  10547. res = cli.Get("/dir/test.html");
  10548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10549. EXPECT_EQ(StatusCode::OK_200, res->status);
  10550. }
  10551. TEST(MountTest, Redicect) {
  10552. Server svr;
  10553. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10554. auto se = detail::scope_exit([&] {
  10555. svr.stop();
  10556. listen_thread.join();
  10557. ASSERT_FALSE(svr.is_running());
  10558. });
  10559. svr.set_mount_point("/", "./www");
  10560. svr.wait_until_ready();
  10561. Client cli("localhost", PORT);
  10562. auto res = cli.Get("/dir/");
  10563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10564. EXPECT_EQ(StatusCode::OK_200, res->status);
  10565. res = cli.Get("/dir");
  10566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10567. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10568. res = cli.Get("/file");
  10569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10570. EXPECT_EQ(StatusCode::OK_200, res->status);
  10571. res = cli.Get("/file/");
  10572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10574. cli.set_follow_location(true);
  10575. res = cli.Get("/dir");
  10576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10577. EXPECT_EQ(StatusCode::OK_200, res->status);
  10578. }
  10579. TEST(MountTest, MultibytesPathName) {
  10580. Server svr;
  10581. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10582. auto se = detail::scope_exit([&] {
  10583. svr.stop();
  10584. listen_thread.join();
  10585. ASSERT_FALSE(svr.is_running());
  10586. });
  10587. svr.set_mount_point("/", "./www");
  10588. svr.wait_until_ready();
  10589. Client cli("localhost", PORT);
  10590. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10592. EXPECT_EQ(StatusCode::OK_200, res->status);
  10593. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10594. }
  10595. #ifdef _WIN32
  10596. // Issue #2435: mmap::open() must succeed even when another handle holds
  10597. // the file open for writing (e.g. an active log file).
  10598. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10599. const char *path = "mmap_concurrent_writer_test.txt";
  10600. const char *content = "hello";
  10601. {
  10602. std::ofstream f(path, std::ios::binary);
  10603. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10604. }
  10605. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10606. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10607. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10608. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10609. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10610. detail::mmap m(path);
  10611. ASSERT_TRUE(m.is_open());
  10612. EXPECT_EQ(strlen(content), m.size());
  10613. char buf[8];
  10614. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10615. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10616. }
  10617. #endif
  10618. #ifndef _WIN32
  10619. // A directory or a device has no size to serve.
  10620. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10621. const char *path = "./mmap_not_regular_test_dir";
  10622. ASSERT_EQ(0, ::mkdir(path, 0755));
  10623. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10624. for (auto p : {path, "/dev/null"}) {
  10625. detail::mmap m(p);
  10626. EXPECT_FALSE(m.is_open()) << p;
  10627. EXPECT_EQ(0U, m.size()) << p;
  10628. }
  10629. Server svr;
  10630. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10631. res.set_file_content("/dev/null");
  10632. });
  10633. auto port = svr.bind_to_any_port(HOST);
  10634. thread t = thread([&] { svr.listen_after_bind(); });
  10635. auto se = detail::scope_exit([&] {
  10636. svr.stop();
  10637. t.join();
  10638. });
  10639. svr.wait_until_ready();
  10640. auto res = Client(HOST, port).Get("/null");
  10641. ASSERT_TRUE(res);
  10642. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10643. }
  10644. #endif
  10645. #ifdef __linux__
  10646. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10647. TEST(MmapTest, FileIsNotMapped) {
  10648. const char *path = "mmap_not_mapped_test.txt";
  10649. {
  10650. std::ofstream f(path, std::ios::binary);
  10651. f << "hello";
  10652. }
  10653. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10654. detail::mmap m(path);
  10655. ASSERT_TRUE(m.is_open());
  10656. std::ifstream maps("/proc/self/maps");
  10657. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10658. std::istreambuf_iterator<char>());
  10659. EXPECT_EQ(std::string::npos, mappings.find(path));
  10660. }
  10661. #endif
  10662. TEST(KeepAliveTest, ReadTimeout) {
  10663. Server svr;
  10664. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10665. std::this_thread::sleep_for(std::chrono::seconds(2));
  10666. res.set_content("a", "text/plain");
  10667. });
  10668. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10669. res.set_content("b", "text/plain");
  10670. });
  10671. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10672. auto se = detail::scope_exit([&] {
  10673. svr.stop();
  10674. listen_thread.join();
  10675. ASSERT_FALSE(svr.is_running());
  10676. });
  10677. svr.wait_until_ready();
  10678. Client cli("localhost", PORT);
  10679. cli.set_keep_alive(true);
  10680. cli.set_read_timeout(std::chrono::seconds(1));
  10681. auto resa = cli.Get("/a");
  10682. ASSERT_FALSE(resa);
  10683. EXPECT_EQ(Error::Read, resa.error());
  10684. auto resb = cli.Get("/b");
  10685. ASSERT_TRUE(resb);
  10686. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10687. EXPECT_EQ("b", resb->body);
  10688. }
  10689. TEST(KeepAliveTest, MaxCount) {
  10690. size_t keep_alive_max_count = 3;
  10691. Server svr;
  10692. svr.set_keep_alive_max_count(keep_alive_max_count);
  10693. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10694. res.set_content("Hello World!", "text/plain");
  10695. });
  10696. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10697. auto se = detail::scope_exit([&] {
  10698. svr.stop();
  10699. listen_thread.join();
  10700. ASSERT_FALSE(svr.is_running());
  10701. });
  10702. svr.wait_until_ready();
  10703. Client cli(HOST, PORT);
  10704. cli.set_keep_alive(true);
  10705. for (size_t i = 0; i < 5; i++) {
  10706. auto result = cli.Get("/hi");
  10707. ASSERT_TRUE(result);
  10708. EXPECT_EQ(StatusCode::OK_200, result->status);
  10709. if (i == keep_alive_max_count - 1) {
  10710. EXPECT_EQ("close", result->get_header_value("Connection"));
  10711. } else {
  10712. EXPECT_FALSE(result->has_header("Connection"));
  10713. }
  10714. }
  10715. }
  10716. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10717. // can pull the next one into the server's buffer. The server must serve it
  10718. // without waiting for the socket to become readable again. The keep-alive
  10719. // timeout outlasts the client's read timeout, so a request left waiting for it
  10720. // shows up as a missing response.
  10721. static void serve_pipelining_routes(Server &svr,
  10722. const std::function<void(int)> &client) {
  10723. svr.set_keep_alive_timeout(5);
  10724. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10725. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10726. });
  10727. svr.Post("/echo", [](const Request &req, Response &res) {
  10728. res.set_content("echo " + req.body, "text/plain");
  10729. });
  10730. auto port = svr.bind_to_any_port(HOST);
  10731. thread t = thread([&] { svr.listen_after_bind(); });
  10732. auto se = detail::scope_exit([&] {
  10733. svr.stop();
  10734. t.join();
  10735. });
  10736. svr.wait_until_ready();
  10737. client(port);
  10738. }
  10739. static std::string
  10740. send_pipelined_requests(const std::vector<std::string> &parts) {
  10741. Server svr;
  10742. std::string res;
  10743. serve_pipelining_routes(svr, [&](int port) {
  10744. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10745. });
  10746. return res;
  10747. }
  10748. static void expect_in_order(const std::string &res,
  10749. const std::vector<std::string> &bodies) {
  10750. size_t pos = 0;
  10751. for (const auto &body : bodies) {
  10752. pos = res.find(body, pos);
  10753. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10754. pos += body.size();
  10755. }
  10756. }
  10757. TEST(KeepAliveTest, PipelinedRequests) {
  10758. auto res = send_pipelined_requests(
  10759. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10760. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10761. "Content-Length: 4\r\n\r\nbody"
  10762. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10763. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10764. }
  10765. // The second request starts in the server's buffer and ends on the socket.
  10766. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10767. auto res =
  10768. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10769. "GET /hi/2 HTTP/1.1\r\nHo",
  10770. "st: localhost\r\nConnection: close\r\n\r\n"});
  10771. expect_in_order(res, {"hi 1", "hi 2"});
  10772. }
  10773. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10774. // CRLF after a body does not turn into a 400 for the next request.
  10775. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10776. auto res = send_pipelined_requests(
  10777. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10778. "Content-Length: 4\r\n\r\nbody\r\n"
  10779. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10780. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10781. expect_in_order(res, {"echo body", "hi 2"});
  10782. }
  10783. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10784. // must not be served as the next request.
  10785. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10786. auto res = send_pipelined_requests(
  10787. {"INVALID REQUEST LINE\r\n\r\n"
  10788. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10789. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10790. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10791. }
  10792. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10793. // Over TLS, the next request is held by the TLS library as already decrypted
  10794. // data rather than on the socket.
  10795. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10796. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10797. std::string res;
  10798. serve_pipelining_routes(svr, [&](int port) {
  10799. // One part, so all three requests arrive in one TLS record
  10800. EXPECT_TRUE(send_ssl_request_in_parts(
  10801. 2,
  10802. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10803. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10804. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10805. &res, port));
  10806. });
  10807. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10808. }
  10809. #endif
  10810. TEST(KeepAliveTest, Issue1041) {
  10811. Server svr;
  10812. svr.set_keep_alive_timeout(3);
  10813. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10814. res.set_content("Hello World!", "text/plain");
  10815. });
  10816. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10817. auto se = detail::scope_exit([&] {
  10818. svr.stop();
  10819. listen_thread.join();
  10820. ASSERT_FALSE(svr.is_running());
  10821. });
  10822. svr.wait_until_ready();
  10823. Client cli(HOST, PORT);
  10824. cli.set_keep_alive(true);
  10825. auto result = cli.Get("/hi");
  10826. ASSERT_TRUE(result);
  10827. EXPECT_EQ(StatusCode::OK_200, result->status);
  10828. std::this_thread::sleep_for(std::chrono::seconds(5));
  10829. result = cli.Get("/hi");
  10830. ASSERT_TRUE(result);
  10831. EXPECT_EQ(StatusCode::OK_200, result->status);
  10832. }
  10833. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10834. Server svr;
  10835. svr.set_keep_alive_max_count(0);
  10836. std::set<int> remote_ports;
  10837. svr.Get("/hi", [&](const Request &req, Response &res) {
  10838. remote_ports.insert(req.remote_port);
  10839. res.set_content("hi", "text/plain");
  10840. });
  10841. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10842. auto se = detail::scope_exit([&] {
  10843. svr.stop();
  10844. listen_thread.join();
  10845. ASSERT_FALSE(svr.is_running());
  10846. });
  10847. svr.wait_until_ready();
  10848. Client cli(HOST, PORT);
  10849. cli.set_keep_alive(true);
  10850. for (int i = 0; i < 3; i++) {
  10851. auto res = cli.Get("/hi");
  10852. ASSERT_TRUE(res);
  10853. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10854. }
  10855. // All three over one connection
  10856. EXPECT_EQ(1u, remote_ports.size());
  10857. }
  10858. TEST(KeepAliveTest, Issue1959) {
  10859. Server svr;
  10860. svr.set_keep_alive_timeout(5);
  10861. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10862. res.set_content("a", "text/plain");
  10863. });
  10864. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10865. auto se = detail::scope_exit([&] {
  10866. if (!svr.is_running()) return;
  10867. svr.stop();
  10868. listen_thread.join();
  10869. ASSERT_FALSE(svr.is_running());
  10870. });
  10871. svr.wait_until_ready();
  10872. Client cli("localhost", PORT);
  10873. cli.set_keep_alive(true);
  10874. using namespace std::chrono;
  10875. auto start = steady_clock::now();
  10876. cli.Get("/a");
  10877. svr.stop();
  10878. listen_thread.join();
  10879. auto end = steady_clock::now();
  10880. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10881. EXPECT_LT(elapsed, 5000);
  10882. }
  10883. #ifdef CPPHTTPLIB_SSL_ENABLED
  10884. TEST(KeepAliveTest, SSLClientReconnection) {
  10885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10886. ASSERT_TRUE(svr.is_valid());
  10887. svr.set_keep_alive_timeout(1);
  10888. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10889. res.set_content("Hello World!", "text/plain");
  10890. });
  10891. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10892. auto se = detail::scope_exit([&] {
  10893. svr.stop();
  10894. listen_thread.join();
  10895. ASSERT_FALSE(svr.is_running());
  10896. });
  10897. svr.wait_until_ready();
  10898. SSLClient cli(HOST, PORT);
  10899. cli.enable_server_certificate_verification(false);
  10900. cli.set_keep_alive(true);
  10901. auto result = cli.Get("/hi");
  10902. ASSERT_TRUE(result);
  10903. EXPECT_EQ(StatusCode::OK_200, result->status);
  10904. result = cli.Get("/hi");
  10905. ASSERT_TRUE(result);
  10906. EXPECT_EQ(StatusCode::OK_200, result->status);
  10907. std::this_thread::sleep_for(std::chrono::seconds(2));
  10908. // Recoonect
  10909. result = cli.Get("/hi");
  10910. ASSERT_TRUE(result);
  10911. EXPECT_EQ(StatusCode::OK_200, result->status);
  10912. result = cli.Get("/hi");
  10913. ASSERT_TRUE(result);
  10914. EXPECT_EQ(StatusCode::OK_200, result->status);
  10915. }
  10916. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10917. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10918. ASSERT_TRUE(svr.is_valid());
  10919. svr.set_keep_alive_timeout(1);
  10920. std::string content = "reconnect";
  10921. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10922. res.set_content("Hello World!", "text/plain");
  10923. });
  10924. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10925. auto se = detail::scope_exit([&] {
  10926. svr.stop();
  10927. listen_thread.join();
  10928. ASSERT_FALSE(svr.is_running());
  10929. });
  10930. svr.wait_until_ready();
  10931. SSLClient cli(HOST, PORT);
  10932. cli.enable_server_certificate_verification(false);
  10933. cli.set_keep_alive(true);
  10934. auto result = cli.Post(
  10935. "/hi", content.size(),
  10936. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10937. sink.write(content.c_str(), content.size());
  10938. return true;
  10939. },
  10940. "text/plain");
  10941. ASSERT_TRUE(result);
  10942. EXPECT_EQ(200, result->status);
  10943. std::this_thread::sleep_for(std::chrono::seconds(2));
  10944. // Recoonect
  10945. result = cli.Post(
  10946. "/hi", content.size(),
  10947. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10948. sink.write(content.c_str(), content.size());
  10949. return true;
  10950. },
  10951. "text/plain");
  10952. ASSERT_TRUE(result);
  10953. EXPECT_EQ(200, result->status);
  10954. result = cli.Post(
  10955. "/hi", content.size(),
  10956. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10957. sink.write(content.c_str(), content.size());
  10958. return true;
  10959. },
  10960. "text/plain");
  10961. ASSERT_TRUE(result);
  10962. EXPECT_EQ(200, result->status);
  10963. }
  10964. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10965. using namespace httplib::tls;
  10966. {
  10967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10968. ASSERT_TRUE(svr.is_valid());
  10969. svr.Get("/sni", [&](const Request &req, Response &res) {
  10970. std::string expected = req.sni();
  10971. EXPECT_EQ(expected, req.get_param_value("expected"));
  10972. res.set_content("ok", "text/plain");
  10973. });
  10974. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10975. auto se = detail::scope_exit([&] {
  10976. svr.stop();
  10977. listen_thread.join();
  10978. ASSERT_FALSE(svr.is_running());
  10979. });
  10980. svr.wait_until_ready();
  10981. {
  10982. SSLClient cli("localhost", PORT);
  10983. cli.enable_server_certificate_verification(false);
  10984. auto res = cli.Get("/sni?expected=localhost");
  10985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10986. }
  10987. {
  10988. SSLClient cli("::1", PORT);
  10989. cli.enable_server_certificate_verification(false);
  10990. auto res = cli.Get("/sni?expected=");
  10991. // NOTE: This may fail if the server is listening on IPv4 only
  10992. // (e.g., when localhost resolves to 127.0.0.1 only)
  10993. if (res) {
  10994. EXPECT_EQ(StatusCode::OK_200, res->status);
  10995. } else {
  10996. EXPECT_EQ(Error::Connection, res.error());
  10997. }
  10998. }
  10999. }
  11000. }
  11001. #endif
  11002. TEST(ClientProblemDetectionTest, ContentProvider) {
  11003. Server svr;
  11004. size_t content_length = 1024 * 1024;
  11005. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11006. res.set_content_provider(
  11007. content_length, "text/plain",
  11008. [&](size_t offset, size_t length, DataSink &sink) {
  11009. auto out_len = std::min(length, static_cast<size_t>(1024));
  11010. std::string out(out_len, '@');
  11011. sink.write(out.data(), out_len);
  11012. return offset < 4096;
  11013. },
  11014. [](bool success) { ASSERT_FALSE(success); });
  11015. });
  11016. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11017. res.set_content_provider(
  11018. 0, "text/plain",
  11019. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11020. EXPECT_TRUE(false);
  11021. return true;
  11022. },
  11023. [](bool success) { ASSERT_FALSE(success); });
  11024. });
  11025. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11026. auto se = detail::scope_exit([&] {
  11027. svr.stop();
  11028. listen_thread.join();
  11029. ASSERT_FALSE(svr.is_running());
  11030. });
  11031. svr.wait_until_ready();
  11032. Client cli("localhost", PORT);
  11033. {
  11034. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11035. size_t /*data_length*/) { return false; });
  11036. ASSERT_FALSE(res);
  11037. }
  11038. {
  11039. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11040. size_t /*data_length*/) { return false; });
  11041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11042. }
  11043. }
  11044. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11045. // A provider that reports success without writing anything and without
  11046. // calling done() used to be handed the same offset and length again on every
  11047. // pass, so it spun for as long as the peer stayed connected.
  11048. Server svr;
  11049. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11050. res.set_content("ok", "text/plain");
  11051. });
  11052. auto port = svr.bind_to_any_port(HOST);
  11053. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11054. auto se = detail::scope_exit([&] {
  11055. svr.stop();
  11056. listen_thread.join();
  11057. ASSERT_FALSE(svr.is_running());
  11058. });
  11059. svr.wait_until_ready();
  11060. std::atomic<int> call_count{0};
  11061. Client cli(HOST, port);
  11062. auto res = cli.Post(
  11063. "/", 1024,
  11064. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11065. // Give up after enough passes to show the spin, so that losing the
  11066. // check below fails this test instead of hanging it.
  11067. return ++call_count < 100;
  11068. },
  11069. "text/plain");
  11070. ASSERT_FALSE(res);
  11071. EXPECT_EQ(Error::Write, res.error());
  11072. EXPECT_EQ(1, call_count.load());
  11073. }
  11074. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11075. // A writer only has to assign `write`. The other three used to be left as
  11076. // empty std::functions, so a provider calling one threw
  11077. // std::bad_function_call out of the thread running it and took the whole
  11078. // process down.
  11079. DataSink sink;
  11080. std::string written;
  11081. sink.write = [&](const char *data, size_t data_len) {
  11082. written.append(data, data_len);
  11083. return true;
  11084. };
  11085. EXPECT_TRUE(sink.is_writable());
  11086. sink.done();
  11087. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11088. EXPECT_TRUE(written.empty());
  11089. }
  11090. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11091. // A sink that cannot carry trailers still has to finish.
  11092. DataSink sink;
  11093. auto done_count = 0;
  11094. sink.done = [&]() { done_count++; };
  11095. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11096. EXPECT_EQ(1, done_count);
  11097. }
  11098. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11099. Server svr;
  11100. const std::string body(4096, 'x');
  11101. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11102. res.set_content_provider(body.size(), "text/plain",
  11103. [&](size_t offset, size_t length, DataSink &sink) {
  11104. sink.write(body.data() + offset, length);
  11105. sink.done();
  11106. return true;
  11107. });
  11108. });
  11109. auto port = svr.bind_to_any_port(HOST);
  11110. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11111. auto se = detail::scope_exit([&] {
  11112. svr.stop();
  11113. listen_thread.join();
  11114. ASSERT_FALSE(svr.is_running());
  11115. });
  11116. svr.wait_until_ready();
  11117. Client cli(HOST, port);
  11118. auto res = cli.Get("/");
  11119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11120. EXPECT_EQ(StatusCode::OK_200, res->status);
  11121. EXPECT_EQ(body, res->body);
  11122. }
  11123. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11124. Server svr;
  11125. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11126. res.set_content_provider(
  11127. 1024, "text/plain",
  11128. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11129. sink.write("hello", 5);
  11130. sink.done(); // short of the 1024 bytes the response promised
  11131. return true;
  11132. });
  11133. });
  11134. auto port = svr.bind_to_any_port(HOST);
  11135. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11136. auto se = detail::scope_exit([&] {
  11137. svr.stop();
  11138. listen_thread.join();
  11139. ASSERT_FALSE(svr.is_running());
  11140. });
  11141. svr.wait_until_ready();
  11142. Client cli(HOST, port);
  11143. cli.set_read_timeout(5, 0);
  11144. // The response is short of its Content-Length, so the client cannot read a
  11145. // complete body. What matters is that this returns at all: a no-op done()
  11146. // would leave the writer looping over a provider that never makes progress.
  11147. auto res = cli.Get("/");
  11148. EXPECT_FALSE(res);
  11149. }
  11150. // Read as the next response by a peer that sees it after a framed body.
  11151. static const std::string smuggled_response =
  11152. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11153. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11154. Server svr;
  11155. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11156. res.set_content_provider(
  11157. 5, "text/plain",
  11158. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11159. auto data = "AAAAA" + smuggled_response;
  11160. sink.write(data.data(), data.size());
  11161. return true;
  11162. });
  11163. });
  11164. thread t = thread([&] { svr.listen(HOST, PORT); });
  11165. auto se = detail::scope_exit([&] {
  11166. svr.stop();
  11167. t.join();
  11168. ASSERT_FALSE(svr.is_running());
  11169. });
  11170. svr.wait_until_ready();
  11171. std::string resp;
  11172. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11173. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11174. resp.clear();
  11175. ASSERT_TRUE(send_request(
  11176. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11177. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11178. }
  11179. TEST(NoContentTest, BodyIsNotSent) {
  11180. Server svr;
  11181. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11182. res.status = StatusCode::NoContent_204;
  11183. res.set_content(smuggled_response, "text/plain");
  11184. });
  11185. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11186. res.status = StatusCode::NotModified_304;
  11187. res.set_chunked_content_provider(
  11188. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11189. sink.write(smuggled_response.data(), smuggled_response.size());
  11190. sink.done();
  11191. return true;
  11192. });
  11193. });
  11194. thread t = thread([&] { svr.listen(HOST, PORT); });
  11195. auto se = detail::scope_exit([&] {
  11196. svr.stop();
  11197. t.join();
  11198. ASSERT_FALSE(svr.is_running());
  11199. });
  11200. svr.wait_until_ready();
  11201. for (auto path : {"/204", "/304"}) {
  11202. std::string resp;
  11203. ASSERT_TRUE(send_request(
  11204. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11205. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11206. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11207. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11208. }
  11209. }
  11210. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11211. Server svr;
  11212. std::atomic<bool> smuggled(false);
  11213. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11214. res.set_content("ok", "text/plain");
  11215. });
  11216. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11217. smuggled = true;
  11218. });
  11219. auto port = svr.bind_to_any_port(HOST);
  11220. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11221. auto se = detail::scope_exit([&] {
  11222. svr.stop();
  11223. listen_thread.join();
  11224. ASSERT_FALSE(svr.is_running());
  11225. });
  11226. svr.wait_until_ready();
  11227. // What follows the body would be read as the next request.
  11228. Client cli(HOST, port);
  11229. auto res = cli.Post(
  11230. "/", 5,
  11231. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11232. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11233. sink.write(data.data(), data.size());
  11234. return true;
  11235. },
  11236. "text/plain");
  11237. ASSERT_FALSE(res);
  11238. EXPECT_EQ(Error::Write, res.error());
  11239. EXPECT_FALSE(smuggled);
  11240. }
  11241. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11242. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11243. // The compressed path builds the whole body before connecting, so this
  11244. // fails client-side and never reaches a server.
  11245. Client cli(HOST, PORT);
  11246. cli.set_compress(true);
  11247. auto res = cli.Post(
  11248. "/", 1024,
  11249. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11250. sink.write("hello", 5);
  11251. sink.done(); // short of the 1024 bytes the request announced
  11252. return true;
  11253. },
  11254. "text/plain");
  11255. ASSERT_FALSE(res);
  11256. EXPECT_EQ(Error::Write, res.error());
  11257. }
  11258. #endif
  11259. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11260. Server svr;
  11261. svr.set_error_handler([](Request const &, Response &res) -> void {
  11262. res.set_chunked_content_provider(
  11263. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11264. sink.os << "hello";
  11265. sink.os << "world";
  11266. sink.done();
  11267. return true;
  11268. });
  11269. });
  11270. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11271. auto se = detail::scope_exit([&] {
  11272. svr.stop();
  11273. listen_thread.join();
  11274. ASSERT_FALSE(svr.is_running());
  11275. });
  11276. svr.wait_until_ready();
  11277. Client cli("localhost", PORT);
  11278. auto res = cli.Get("/");
  11279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11280. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11281. EXPECT_EQ("helloworld", res->body);
  11282. }
  11283. // A body set after a content provider must replace it, not be sent through it.
  11284. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11285. Server svr;
  11286. svr.set_mount_point("/", "./www");
  11287. svr.set_file_request_handler([](const Request &req, Response &res) {
  11288. if (req.path == "/dir/test.html") {
  11289. res.status = StatusCode::Forbidden_403;
  11290. res.set_content(std::string(5000, 'D'), "text/plain");
  11291. } else if (req.path == "/file") {
  11292. res.status = StatusCode::Forbidden_403;
  11293. res.body = "Denied";
  11294. }
  11295. });
  11296. auto port = svr.bind_to_any_port(HOST);
  11297. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11298. auto se = detail::scope_exit([&] {
  11299. svr.stop();
  11300. t.join();
  11301. ASSERT_FALSE(svr.is_running());
  11302. });
  11303. svr.wait_until_ready();
  11304. Client cli(HOST, port);
  11305. {
  11306. auto res = cli.Get("/dir/test.html");
  11307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11308. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11309. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11310. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11311. }
  11312. {
  11313. auto res = cli.Get("/file");
  11314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11315. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11316. EXPECT_EQ("Denied", res->body);
  11317. }
  11318. {
  11319. auto res = cli.Get("/dir/index.html");
  11320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11321. EXPECT_EQ(StatusCode::OK_200, res->status);
  11322. EXPECT_EQ(0U, res->body.find("<html>"));
  11323. }
  11324. }
  11325. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11326. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11327. Server svr;
  11328. std::vector<bool> released;
  11329. std::mutex released_mutex;
  11330. auto releaser = [&](bool success) {
  11331. std::lock_guard<std::mutex> guard(released_mutex);
  11332. released.push_back(success);
  11333. };
  11334. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11335. return sink.write(&"hello"[offset], length);
  11336. };
  11337. svr.Get("/sized", [&](const Request &, Response &res) {
  11338. res.status = StatusCode::NotFound_404;
  11339. res.set_content_provider(5, "text/plain", provider, releaser);
  11340. });
  11341. svr.Get("/chunked", [&](const Request &, Response &res) {
  11342. res.status = StatusCode::ServiceUnavailable_503;
  11343. res.set_chunked_content_provider(
  11344. "text/plain",
  11345. [](size_t, DataSink &sink) {
  11346. sink.os << "chunk";
  11347. sink.done();
  11348. return true;
  11349. },
  11350. releaser);
  11351. });
  11352. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11353. res.set_content_provider(5, "text/plain", provider, releaser);
  11354. throw std::runtime_error("after the provider");
  11355. });
  11356. svr.set_error_handler([](const Request &req, Response &res) {
  11357. // Leave the exception handler's content to it.
  11358. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11359. res.set_content(std::string(1000, 'E'), "text/html");
  11360. return Server::HandlerResponse::Handled;
  11361. });
  11362. svr.set_exception_handler(
  11363. [](const Request &, Response &res, std::exception_ptr) {
  11364. res.status = StatusCode::InternalServerError_500;
  11365. res.set_content(std::string(1000, 'X'), "text/html");
  11366. });
  11367. auto port = svr.bind_to_any_port(HOST);
  11368. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11369. auto se = detail::scope_exit([&] {
  11370. svr.stop();
  11371. t.join();
  11372. ASSERT_FALSE(svr.is_running());
  11373. });
  11374. svr.wait_until_ready();
  11375. Client cli(HOST, port);
  11376. {
  11377. auto res = cli.Get("/sized");
  11378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11379. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11380. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11381. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11382. }
  11383. {
  11384. auto res = cli.Get("/chunked");
  11385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11386. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11387. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11388. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11389. }
  11390. {
  11391. auto res = cli.Get("/throw");
  11392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11393. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11394. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11395. }
  11396. std::lock_guard<std::mutex> guard(released_mutex);
  11397. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11398. }
  11399. #endif
  11400. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11401. Server svr;
  11402. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11403. return sink.write(&"abc"[offset], length);
  11404. };
  11405. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11406. res.set_file_content("./www/dir/test.html");
  11407. res.set_content("body", "text/plain");
  11408. });
  11409. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11410. res.set_content(std::string(100, 'B'), "text/plain");
  11411. res.set_file_content("./www/dir/test.html");
  11412. });
  11413. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11414. res.set_content(std::string(100, 'B'), "text/plain");
  11415. res.set_content_provider(3, "text/x-provider", abc);
  11416. });
  11417. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11418. res.set_content_provider(3, "text/x-provider", abc);
  11419. res.set_content(std::string(100, 'B'), "text/plain");
  11420. });
  11421. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11422. res.set_content_provider(3, "text/x-provider", abc);
  11423. res.set_file_content("./www/dir/test.html", "text/x-file");
  11424. });
  11425. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11426. res.set_file_content("./www/dir/test.html");
  11427. res.set_header("Content-Type", "text/x-handler");
  11428. });
  11429. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11430. res.set_content_provider(3, "text/plain", abc);
  11431. res.body = "direct";
  11432. });
  11433. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11434. res.set_file_content("./www/dir/test.html");
  11435. res.body = "direct";
  11436. });
  11437. auto port = svr.bind_to_any_port(HOST);
  11438. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11439. auto se = detail::scope_exit([&] {
  11440. svr.stop();
  11441. t.join();
  11442. ASSERT_FALSE(svr.is_running());
  11443. });
  11444. svr.wait_until_ready();
  11445. Client cli(HOST, port);
  11446. auto expect_body = [&](const char *path, const std::string &body,
  11447. const std::string &type) {
  11448. // Uncompressed, so Content-Length can be compared with the body.
  11449. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11450. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11451. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11452. EXPECT_EQ(body, res->body) << path;
  11453. EXPECT_EQ(std::to_string(body.size()),
  11454. res->get_header_value("Content-Length"))
  11455. << path;
  11456. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11457. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11458. };
  11459. expect_body("/file-then-body", "body", "text/plain");
  11460. expect_body("/body-then-file", "test.html", "text/html");
  11461. expect_body("/body-then-provider", "abc", "text/x-provider");
  11462. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11463. expect_body("/provider-then-file", "test.html", "text/x-file");
  11464. expect_body("/file-then-header", "test.html", "text/x-handler");
  11465. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11466. expect_body("/file-then-direct-body", "direct", "text/plain");
  11467. // Ranges are checked against the body, not the dropped provider.
  11468. {
  11469. auto res = cli.Get("/provider-then-direct-body",
  11470. Headers{{make_range_header({{1, 2}})}});
  11471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11472. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11473. EXPECT_EQ("ir", res->body);
  11474. }
  11475. {
  11476. auto res = cli.Get("/file-then-direct-body",
  11477. Headers{{make_range_header({{7, 8}})}});
  11478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11479. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11480. }
  11481. }
  11482. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11483. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11484. const char *path = "./truncated_while_served.txt";
  11485. const size_t size = 32 * 1024 * 1024;
  11486. {
  11487. std::ofstream f(path, std::ios::binary);
  11488. f << std::string(size, 'x');
  11489. }
  11490. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11491. // Over TLS, where the bytes are encrypted in this process rather than
  11492. // copied by send().
  11493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11494. svr.Get("/file", [&](const Request &, Response &res) {
  11495. res.set_file_content(path, "text/plain");
  11496. });
  11497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11498. auto se = detail::scope_exit([&] {
  11499. svr.stop();
  11500. thread.join();
  11501. ASSERT_FALSE(svr.is_running());
  11502. });
  11503. svr.wait_until_ready();
  11504. // The file shrinks once the first bytes are in, as a rewrite in place
  11505. // would, and reading the mapping past its new end used to raise SIGBUS.
  11506. SSLClient cli(HOST, PORT);
  11507. cli.enable_server_certificate_verification(false);
  11508. size_t received = 0;
  11509. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11510. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11511. received += len;
  11512. return true;
  11513. });
  11514. EXPECT_FALSE(res);
  11515. EXPECT_LT(received, size);
  11516. }
  11517. #endif
  11518. // Forward declaration (see the base64_encode note).
  11519. namespace httplib {
  11520. namespace detail {
  11521. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11522. const std::string &content_type,
  11523. EncodingType encoding);
  11524. } // namespace detail
  11525. } // namespace httplib
  11526. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11527. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11528. ASSERT_TRUE(mm->is_open());
  11529. Response res;
  11530. detail::set_file_content_provider(res, mm, "text/html",
  11531. detail::EncodingType::None);
  11532. std::string out;
  11533. DataSink sink;
  11534. sink.write = [&](const char *d, size_t l) {
  11535. out.append(d, l);
  11536. return true;
  11537. };
  11538. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11539. EXPECT_EQ("test.html", out);
  11540. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11541. EXPECT_EQ("test.html", out);
  11542. }
  11543. TEST(LongPollingTest, ClientCloseDetection) {
  11544. Server svr;
  11545. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11546. res.set_chunked_content_provider(
  11547. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11548. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11549. sink.os << "hello";
  11550. auto count = 10;
  11551. while (count > 0 && sink.is_writable()) {
  11552. this_thread::sleep_for(chrono::milliseconds(10));
  11553. count--;
  11554. }
  11555. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11556. return true;
  11557. });
  11558. });
  11559. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11560. auto se = detail::scope_exit([&] {
  11561. svr.stop();
  11562. listen_thread.join();
  11563. ASSERT_FALSE(svr.is_running());
  11564. });
  11565. svr.wait_until_ready();
  11566. Client cli("localhost", PORT);
  11567. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11568. EXPECT_EQ("hello", string(data, data_length));
  11569. return false; // close the socket immediately.
  11570. });
  11571. ASSERT_FALSE(res);
  11572. }
  11573. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11574. Server svr;
  11575. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11576. res.set_chunked_content_provider(
  11577. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11578. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11579. sink.os << "hello";
  11580. EXPECT_TRUE(sink.os.good());
  11581. // Wait for the client to close the connection
  11582. auto count = 10;
  11583. while (count > 0 && sink.is_writable()) {
  11584. this_thread::sleep_for(chrono::milliseconds(10));
  11585. count--;
  11586. }
  11587. // After client disconnect, write repeatedly until the socket
  11588. // write actually fails (small writes may be absorbed by the
  11589. // kernel buffer)
  11590. std::string chunk(1024, 'x');
  11591. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11592. sink.os << chunk;
  11593. }
  11594. EXPECT_TRUE(sink.os.fail());
  11595. return true;
  11596. });
  11597. });
  11598. auto port = svr.bind_to_any_port("localhost");
  11599. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11600. auto se = detail::scope_exit([&] {
  11601. svr.stop();
  11602. listen_thread.join();
  11603. ASSERT_FALSE(svr.is_running());
  11604. });
  11605. svr.wait_until_ready();
  11606. Client cli("localhost", port);
  11607. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11608. EXPECT_EQ("hello", string(data, data_length));
  11609. return false; // close the socket immediately.
  11610. });
  11611. ASSERT_FALSE(res);
  11612. }
  11613. TEST(GetWithParametersTest, GetWithParameters) {
  11614. Server svr;
  11615. svr.Get("/", [&](const Request &req, Response &) {
  11616. EXPECT_EQ("world", req.get_param_value("hello"));
  11617. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11618. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11619. });
  11620. svr.Get("/params", [&](const Request &req, Response &) {
  11621. EXPECT_EQ("world", req.get_param_value("hello"));
  11622. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11623. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11624. });
  11625. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11626. EXPECT_EQ("resource-id", req.matches[1]);
  11627. EXPECT_EQ("foo", req.get_param_value("param1"));
  11628. EXPECT_EQ("bar", req.get_param_value("param2"));
  11629. });
  11630. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11631. EXPECT_EQ("user-id", req.path_params.at("id"));
  11632. EXPECT_EQ("foo", req.get_param_value("param1"));
  11633. EXPECT_EQ("bar", req.get_param_value("param2"));
  11634. });
  11635. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11636. auto se = detail::scope_exit([&] {
  11637. svr.stop();
  11638. listen_thread.join();
  11639. ASSERT_FALSE(svr.is_running());
  11640. });
  11641. svr.wait_until_ready();
  11642. {
  11643. Client cli(HOST, PORT);
  11644. Params params;
  11645. params.emplace("hello", "world");
  11646. params.emplace("hello2", "world2");
  11647. params.emplace("hello3", "world3");
  11648. auto res = cli.Get("/", params, Headers{});
  11649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11650. EXPECT_EQ(StatusCode::OK_200, res->status);
  11651. }
  11652. {
  11653. Client cli(HOST, PORT);
  11654. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11656. EXPECT_EQ(StatusCode::OK_200, res->status);
  11657. }
  11658. {
  11659. Client cli(HOST, PORT);
  11660. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11662. EXPECT_EQ(StatusCode::OK_200, res->status);
  11663. }
  11664. {
  11665. Client cli(HOST, PORT);
  11666. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11668. EXPECT_EQ(StatusCode::OK_200, res->status);
  11669. }
  11670. }
  11671. TEST(GetWithParametersTest, GetWithParameters2) {
  11672. Server svr;
  11673. svr.Get("/", [&](const Request &req, Response &res) {
  11674. auto text = req.get_param_value("hello");
  11675. res.set_content(text, "text/plain");
  11676. });
  11677. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11678. auto se = detail::scope_exit([&] {
  11679. svr.stop();
  11680. listen_thread.join();
  11681. ASSERT_FALSE(svr.is_running());
  11682. });
  11683. svr.wait_until_ready();
  11684. Client cli("localhost", PORT);
  11685. Params params;
  11686. params.emplace("hello", "world");
  11687. std::string body;
  11688. auto res = cli.Get("/", params, Headers{},
  11689. [&](const char *data, size_t data_length) {
  11690. body.append(data, data_length);
  11691. return true;
  11692. });
  11693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11694. EXPECT_EQ(StatusCode::OK_200, res->status);
  11695. EXPECT_EQ("world", body);
  11696. }
  11697. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11698. Server svr;
  11699. svr.Get("/search", [&](const Request &req, Response &res) {
  11700. auto q = req.get_param_value("q");
  11701. res.set_content(q, "text/plain");
  11702. });
  11703. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11704. auto se = detail::scope_exit([&] {
  11705. svr.stop();
  11706. listen_thread.join();
  11707. ASSERT_FALSE(svr.is_running());
  11708. });
  11709. svr.wait_until_ready();
  11710. Client cli("localhost", PORT);
  11711. // Verify that Get(path, params) works without requiring Headers argument
  11712. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11714. EXPECT_EQ(StatusCode::OK_200, res->status);
  11715. EXPECT_EQ("cpp-httplib", res->body);
  11716. }
  11717. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11718. auto host = "httpbingo.org";
  11719. auto path = std::string{"/range/32"};
  11720. #ifdef CPPHTTPLIB_SSL_ENABLED
  11721. SSLClient cli(host);
  11722. #else
  11723. Client cli(host);
  11724. #endif
  11725. cli.set_default_headers({make_range_header({{1, 10}})});
  11726. cli.set_connection_timeout(5);
  11727. {
  11728. auto res = cli.Get(path);
  11729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11730. EXPECT_EQ("bcdefghijk", res->body);
  11731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11732. }
  11733. {
  11734. auto res = cli.Get(path);
  11735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11736. EXPECT_EQ("bcdefghijk", res->body);
  11737. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11738. }
  11739. }
  11740. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11741. Server svr;
  11742. svr.set_default_headers({{"Hello", "World"}});
  11743. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11744. res.set_content("ok", "text/plain");
  11745. });
  11746. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11747. auto se = detail::scope_exit([&] {
  11748. svr.stop();
  11749. listen_thread.join();
  11750. ASSERT_FALSE(svr.is_running());
  11751. });
  11752. svr.wait_until_ready();
  11753. Client cli("localhost", PORT);
  11754. auto res = cli.Get("/");
  11755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11756. EXPECT_EQ(StatusCode::OK_200, res->status);
  11757. EXPECT_EQ("ok", res->body);
  11758. EXPECT_EQ("World", res->get_header_value("Hello"));
  11759. }
  11760. #ifdef CPPHTTPLIB_SSL_ENABLED
  11761. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11762. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11763. ASSERT_TRUE(svr.is_valid());
  11764. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11765. std::this_thread::sleep_for(std::chrono::seconds(2));
  11766. res.set_content("a", "text/plain");
  11767. });
  11768. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11769. res.set_content("b", "text/plain");
  11770. });
  11771. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11772. auto se = detail::scope_exit([&] {
  11773. svr.stop();
  11774. listen_thread.join();
  11775. ASSERT_FALSE(svr.is_running());
  11776. });
  11777. svr.wait_until_ready();
  11778. SSLClient cli("localhost", PORT);
  11779. cli.enable_server_certificate_verification(false);
  11780. cli.set_keep_alive(true);
  11781. cli.set_read_timeout(std::chrono::seconds(1));
  11782. auto resa = cli.Get("/a");
  11783. ASSERT_TRUE(!resa);
  11784. EXPECT_EQ(Error::Read, resa.error());
  11785. auto resb = cli.Get("/b");
  11786. ASSERT_TRUE(resb);
  11787. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11788. EXPECT_EQ("b", resb->body);
  11789. }
  11790. // Closing an idle keep-alive connection sends close_notify and returns. The
  11791. // server must not wait for the client's close_notify: an idle client never
  11792. // sends one, so the worker would be held until the read timeout expires, and
  11793. // stop() would wait for it.
  11794. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11795. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11796. ASSERT_TRUE(svr.is_valid());
  11797. svr.set_keep_alive_timeout(1);
  11798. svr.set_read_timeout(10, 0);
  11799. svr.Get("/", [](const Request &, Response &res) {
  11800. res.set_content("ok", "text/plain");
  11801. });
  11802. auto port = svr.bind_to_any_port(HOST);
  11803. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11804. auto se = detail::scope_exit([&] {
  11805. if (listen_thread.joinable()) {
  11806. svr.stop();
  11807. listen_thread.join();
  11808. }
  11809. });
  11810. svr.wait_until_ready();
  11811. SSLClient cli(HOST, port);
  11812. cli.enable_server_certificate_verification(false);
  11813. cli.set_keep_alive(true);
  11814. auto res = cli.Get("/");
  11815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11816. EXPECT_EQ(StatusCode::OK_200, res->status);
  11817. // Stay idle past the keep-alive timeout so the server closes the connection.
  11818. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11819. auto start = std::chrono::steady_clock::now();
  11820. svr.stop();
  11821. listen_thread.join();
  11822. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11823. std::chrono::steady_clock::now() - start)
  11824. .count();
  11825. EXPECT_LT(elapsed, 3000);
  11826. }
  11827. #endif
  11828. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11829. protected:
  11830. ServerTestWithAI_PASSIVE()
  11831. : cli_(HOST, PORT)
  11832. #ifdef CPPHTTPLIB_SSL_ENABLED
  11833. ,
  11834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11835. #endif
  11836. {
  11837. #ifdef CPPHTTPLIB_SSL_ENABLED
  11838. cli_.enable_server_certificate_verification(false);
  11839. #endif
  11840. }
  11841. virtual void SetUp() {
  11842. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11843. res.set_content("Hello World!", "text/plain");
  11844. });
  11845. t_ = thread(
  11846. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11847. svr_.wait_until_ready();
  11848. }
  11849. virtual void TearDown() {
  11850. svr_.stop();
  11851. t_.join();
  11852. }
  11853. #ifdef CPPHTTPLIB_SSL_ENABLED
  11854. SSLClient cli_;
  11855. SSLServer svr_;
  11856. #else
  11857. Client cli_;
  11858. Server svr_;
  11859. #endif
  11860. thread t_;
  11861. };
  11862. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11863. auto res = cli_.Get("/hi");
  11864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11865. EXPECT_EQ(StatusCode::OK_200, res->status);
  11866. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11867. EXPECT_EQ("Hello World!", res->body);
  11868. }
  11869. class ServerUpDownTest : public ::testing::Test {
  11870. protected:
  11871. ServerUpDownTest() : cli_(HOST, PORT) {}
  11872. virtual void SetUp() {
  11873. t_ = thread([&]() {
  11874. svr_.bind_to_any_port(HOST);
  11875. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11876. ASSERT_TRUE(svr_.listen_after_bind());
  11877. });
  11878. svr_.wait_until_ready();
  11879. }
  11880. virtual void TearDown() {
  11881. svr_.stop();
  11882. t_.join();
  11883. }
  11884. Client cli_;
  11885. Server svr_;
  11886. thread t_;
  11887. };
  11888. TEST_F(ServerUpDownTest, QuickStartStop) {
  11889. // Should not crash, especially when run with
  11890. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11891. }
  11892. class PayloadMaxLengthTest : public ::testing::Test {
  11893. protected:
  11894. PayloadMaxLengthTest()
  11895. : cli_(HOST, PORT)
  11896. #ifdef CPPHTTPLIB_SSL_ENABLED
  11897. ,
  11898. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11899. #endif
  11900. {
  11901. #ifdef CPPHTTPLIB_SSL_ENABLED
  11902. cli_.enable_server_certificate_verification(false);
  11903. #endif
  11904. }
  11905. virtual void SetUp() {
  11906. svr_.set_payload_max_length(8);
  11907. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11908. res.set_content("test", "text/plain");
  11909. });
  11910. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11911. svr_.wait_until_ready();
  11912. }
  11913. virtual void TearDown() {
  11914. svr_.stop();
  11915. t_.join();
  11916. }
  11917. #ifdef CPPHTTPLIB_SSL_ENABLED
  11918. SSLClient cli_;
  11919. SSLServer svr_;
  11920. #else
  11921. Client cli_;
  11922. Server svr_;
  11923. #endif
  11924. thread t_;
  11925. };
  11926. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11927. auto res = cli_.Post("/test", "123456789", "text/plain");
  11928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11929. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11930. res = cli_.Post("/test", "12345678", "text/plain");
  11931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11932. EXPECT_EQ(StatusCode::OK_200, res->status);
  11933. }
  11934. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11935. // Test chunked encoding with payload exceeding the 8-byte limit
  11936. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11937. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11939. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11940. }
  11941. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11942. // Test chunked encoding with payload within the 8-byte limit
  11943. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11944. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11946. EXPECT_EQ(StatusCode::OK_200, res->status);
  11947. }
  11948. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11949. // Test using send_request to send chunked data exceeding payload limit
  11950. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11951. "Host: " +
  11952. std::string(HOST) + ":" + std::to_string(PORT) +
  11953. "\r\n"
  11954. "Transfer-Encoding: chunked\r\n"
  11955. "Connection: close\r\n"
  11956. "\r\n"
  11957. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11958. "0123456789\r\n"
  11959. "0\r\n" // End chunk
  11960. "\r\n";
  11961. std::string response;
  11962. bool result = send_request(1, chunked_request, &response);
  11963. if (!result) {
  11964. // If send_request fails, it might be because the server closed the
  11965. // connection due to payload limit enforcement, which is acceptable
  11966. SUCCEED()
  11967. << "Server rejected oversized chunked request (connection closed)";
  11968. } else {
  11969. // If we got a response, check if it's an error response or connection was
  11970. // closed early Short response length indicates connection was closed due to
  11971. // payload limit
  11972. if (response.length() <= 10) {
  11973. SUCCEED() << "Server closed connection for oversized chunked request";
  11974. } else {
  11975. // Check for error status codes
  11976. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11977. response.find("Payload Too Large") != std::string::npos ||
  11978. response.find("400") != std::string::npos);
  11979. }
  11980. }
  11981. }
  11982. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11983. // Test request without Content-Length header exceeding payload limit
  11984. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11985. "Host: " +
  11986. std::string(HOST) + ":" +
  11987. std::to_string(PORT) +
  11988. "\r\n"
  11989. "Connection: close\r\n"
  11990. "\r\n";
  11991. // Add payload exceeding the 8-byte limit
  11992. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11993. request_without_content_length += large_payload;
  11994. std::string response;
  11995. bool result = send_request(1, request_without_content_length, &response);
  11996. if (!result) {
  11997. // If send_request fails, server likely closed connection due to payload
  11998. // limit
  11999. SUCCEED() << "Server rejected oversized request without Content-Length "
  12000. "(connection closed)";
  12001. } else {
  12002. // Check if server responded with error or closed connection early
  12003. if (response.length() <= 10) {
  12004. SUCCEED() << "Server closed connection for oversized request without "
  12005. "Content-Length";
  12006. } else {
  12007. // Check for error status codes
  12008. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12009. response.find("Payload Too Large") != std::string::npos ||
  12010. response.find("400") != std::string::npos);
  12011. }
  12012. }
  12013. }
  12014. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  12015. // Test request without Content-Length header within payload limit
  12016. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12017. "Host: " +
  12018. std::string(HOST) + ":" +
  12019. std::to_string(PORT) +
  12020. "\r\n"
  12021. "Connection: close\r\n"
  12022. "\r\n";
  12023. // Add payload within the 8-byte limit
  12024. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12025. request_without_content_length += small_payload;
  12026. std::string response;
  12027. bool result = send_request(1, request_without_content_length, &response);
  12028. // For requests without Content-Length, the server may have different behavior
  12029. // The key is that it should not reject due to payload limit for small
  12030. // payloads
  12031. if (result) {
  12032. // Check for any HTTP response (success or error, but not connection closed)
  12033. if (response.length() > 10) {
  12034. SUCCEED()
  12035. << "Server processed request without Content-Length within limit";
  12036. } else {
  12037. // Short response might indicate connection closed, which is acceptable
  12038. SUCCEED() << "Server closed connection for request without "
  12039. "Content-Length (acceptable behavior)";
  12040. }
  12041. } else {
  12042. // Connection failure might be due to protocol requirements
  12043. SUCCEED() << "Connection issue with request without Content-Length "
  12044. "(environment-specific)";
  12045. }
  12046. }
  12047. class LargePayloadMaxLengthTest : public ::testing::Test {
  12048. protected:
  12049. LargePayloadMaxLengthTest()
  12050. : cli_(HOST, PORT)
  12051. #ifdef CPPHTTPLIB_SSL_ENABLED
  12052. ,
  12053. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12054. #endif
  12055. {
  12056. #ifdef CPPHTTPLIB_SSL_ENABLED
  12057. cli_.enable_server_certificate_verification(false);
  12058. #endif
  12059. }
  12060. virtual void SetUp() {
  12061. // Set 10MB payload limit
  12062. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12063. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12064. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12065. res.set_content("Large payload test", "text/plain");
  12066. });
  12067. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12068. svr_.wait_until_ready();
  12069. }
  12070. virtual void TearDown() {
  12071. svr_.stop();
  12072. t_.join();
  12073. }
  12074. #ifdef CPPHTTPLIB_SSL_ENABLED
  12075. SSLClient cli_;
  12076. SSLServer svr_;
  12077. #else
  12078. Client cli_;
  12079. Server svr_;
  12080. #endif
  12081. thread t_;
  12082. };
  12083. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12084. // Test chunked encoding with payload within 10MB limit
  12085. std::string medium_payload(5 * 1024 * 1024,
  12086. 'A'); // 5MB payload, within 10MB limit
  12087. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12089. EXPECT_EQ(StatusCode::OK_200, res->status);
  12090. }
  12091. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12092. // Test chunked encoding with payload exceeding 10MB limit
  12093. std::string large_payload(12 * 1024 * 1024,
  12094. 'B'); // 12MB payload, exceeds 10MB limit
  12095. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12096. // Server may either return 413 or close the connection
  12097. if (res) {
  12098. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12099. } else {
  12100. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12101. }
  12102. }
  12103. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12104. // Test request without Content-Length header within 10MB limit
  12105. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12106. "Host: " +
  12107. std::string(HOST) + ":" +
  12108. std::to_string(PORT) +
  12109. "\r\n"
  12110. "Connection: close\r\n"
  12111. "\r\n";
  12112. // Add 1MB payload (within 10MB limit)
  12113. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12114. request_without_content_length += medium_payload;
  12115. std::string response;
  12116. bool result = send_request(5, request_without_content_length, &response);
  12117. if (result) {
  12118. // Should get a proper HTTP response for payloads within limit
  12119. if (response.length() > 10) {
  12120. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12121. "10MB limit";
  12122. } else {
  12123. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12124. "Content-Length)";
  12125. }
  12126. } else {
  12127. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12128. }
  12129. }
  12130. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12131. // Test request without Content-Length header exceeding 10MB limit
  12132. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12133. "Host: " +
  12134. std::string(HOST) + ":" +
  12135. std::to_string(PORT) +
  12136. "\r\n"
  12137. "Connection: close\r\n"
  12138. "\r\n";
  12139. // Add 12MB payload (exceeds 10MB limit)
  12140. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12141. request_without_content_length += large_payload;
  12142. std::string response;
  12143. bool result = send_request(10, request_without_content_length, &response);
  12144. if (!result) {
  12145. // Server should close connection due to payload limit
  12146. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12147. "(connection closed)";
  12148. } else {
  12149. // Check for error response
  12150. if (response.length() <= 10) {
  12151. SUCCEED()
  12152. << "Server closed connection for 12MB request exceeding 10MB limit";
  12153. } else {
  12154. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12155. response.find("Payload Too Large") != std::string::npos ||
  12156. response.find("400") != std::string::npos);
  12157. }
  12158. }
  12159. }
  12160. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12161. Server svr;
  12162. svr.Get("/", [](const Request &, Response &res) {
  12163. // Claims far more than it sends, then drops the connection.
  12164. res.set_content_provider(size_t(1) << 41, "text/plain",
  12165. [](size_t, size_t, DataSink &sink) {
  12166. sink.write("abc", 3);
  12167. return false;
  12168. });
  12169. });
  12170. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12171. auto se = detail::scope_exit([&] {
  12172. svr.stop();
  12173. thread.join();
  12174. ASSERT_FALSE(svr.is_running());
  12175. });
  12176. svr.wait_until_ready();
  12177. Client cli(HOST, PORT);
  12178. cli.set_payload_max_length(0);
  12179. EXPECT_FALSE(cli.Get("/"));
  12180. }
  12181. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12182. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12183. // path.
  12184. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12185. Server svr;
  12186. const size_t LIMIT = 64 * 1024; // 64KB
  12187. svr.set_payload_max_length(LIMIT);
  12188. size_t total = 0;
  12189. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12190. const ContentReader &content_reader) {
  12191. content_reader([&](const char * /*data*/, size_t len) {
  12192. total += len;
  12193. return true;
  12194. });
  12195. res.status = 200;
  12196. res.set_content("stream_ok", "text/plain");
  12197. });
  12198. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12199. auto se = detail::scope_exit([&] {
  12200. svr.stop();
  12201. thread.join();
  12202. ASSERT_FALSE(svr.is_running());
  12203. });
  12204. svr.wait_until_ready();
  12205. // Prepare 256KB raw data and gzip-compress it
  12206. std::string raw(256 * 1024, 'A');
  12207. std::string gz;
  12208. {
  12209. z_stream zs{};
  12210. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12211. Z_DEFAULT_STRATEGY);
  12212. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12213. zs.avail_in = static_cast<uInt>(raw.size());
  12214. char outbuf[4096];
  12215. int ret;
  12216. do {
  12217. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12218. zs.avail_out = sizeof(outbuf);
  12219. ret = deflate(&zs, Z_FINISH);
  12220. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12221. } while (ret != Z_STREAM_END);
  12222. deflateEnd(&zs);
  12223. }
  12224. Client cli(HOST, PORT);
  12225. cli.set_connection_timeout(std::chrono::seconds(5));
  12226. Headers headers = {{"Content-Encoding", "gzip"}};
  12227. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12228. "application/octet-stream");
  12229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12230. // Server must reject oversized decompressed payloads with 413.
  12231. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12232. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12233. EXPECT_LE(total, LIMIT);
  12234. }
  12235. #ifndef CPPHTTPLIB_SSL_ENABLED
  12236. // For a request with neither Content-Length nor Transfer-Encoding, the
  12237. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12238. // compressed wire bytes straight to the ContentReader without ever routing
  12239. // them through the decompressor, so payload_max_length_ only bounded the
  12240. // compressed size on the wire, not the decompressed size.
  12241. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12242. Server svr;
  12243. const size_t LIMIT = 64 * 1024; // 64KB
  12244. svr.set_payload_max_length(LIMIT);
  12245. size_t total = 0;
  12246. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12247. const ContentReader &content_reader) {
  12248. content_reader([&](const char * /*data*/, size_t len) {
  12249. total += len;
  12250. return true;
  12251. });
  12252. res.status = 200;
  12253. res.set_content("stream_ok", "text/plain");
  12254. });
  12255. auto port = svr.bind_to_any_port(HOST);
  12256. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12257. auto se = detail::scope_exit([&] {
  12258. svr.stop();
  12259. thread.join();
  12260. ASSERT_FALSE(svr.is_running());
  12261. });
  12262. svr.wait_until_ready();
  12263. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12264. // StreamingGzipDecompression test above.
  12265. std::string raw(256 * 1024, 'A');
  12266. std::string gz;
  12267. {
  12268. httplib::detail::gzip_compressor compressor;
  12269. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12270. [&](const char *chunk, size_t len) {
  12271. gz.append(chunk, len);
  12272. return true;
  12273. });
  12274. ASSERT_TRUE(result);
  12275. }
  12276. // Send the gzip body over raw TCP with neither Content-Length nor
  12277. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12278. // kicks in.
  12279. std::string req = "POST /stream HTTP/1.1\r\n"
  12280. "Host: " +
  12281. std::string(HOST) + ":" + std::to_string(port) +
  12282. "\r\n"
  12283. "Content-Encoding: gzip\r\n"
  12284. "Connection: close\r\n"
  12285. "\r\n" +
  12286. gz;
  12287. std::string response;
  12288. ASSERT_TRUE(send_request(5, req, &response, port));
  12289. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12290. EXPECT_LE(total, LIMIT);
  12291. }
  12292. #endif
  12293. #endif
  12294. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12295. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12296. // the payload must be passed through untouched instead of being rejected.
  12297. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12298. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12299. Server svr;
  12300. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12301. res.set_content(body, "image/jpeg");
  12302. res.set_header("Content-Encoding", "UTF-8");
  12303. });
  12304. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12305. res.set_content(body, "image/jpeg");
  12306. res.set_header("Content-Encoding", "identity");
  12307. });
  12308. svr.Post("/echo", [](const Request &req, Response &res) {
  12309. res.set_content(req.body, "image/jpeg");
  12310. });
  12311. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12312. auto se = detail::scope_exit([&] {
  12313. svr.stop();
  12314. t.join();
  12315. ASSERT_FALSE(svr.is_running());
  12316. });
  12317. svr.wait_until_ready();
  12318. Client cli(HOST, PORT);
  12319. {
  12320. auto res = cli.Get("/image");
  12321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12322. EXPECT_EQ(StatusCode::OK_200, res->status);
  12323. EXPECT_EQ(body, res->body);
  12324. }
  12325. {
  12326. auto res = cli.Get("/identity");
  12327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12328. EXPECT_EQ(StatusCode::OK_200, res->status);
  12329. EXPECT_EQ(body, res->body);
  12330. }
  12331. {
  12332. // The same applies to a request body reaching the server.
  12333. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12334. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12336. EXPECT_EQ(StatusCode::OK_200, res->status);
  12337. EXPECT_EQ(body, res->body);
  12338. }
  12339. }
  12340. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12341. // gzip-encoded response even when the build has no zlib support.
  12342. static const char GZIPPED_HELLO_WORLD[] = {
  12343. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12344. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12345. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12346. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12347. // A content coding is a whole token, not something the field value merely
  12348. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12349. // as "fibre" look like Brotli, and turned a multi-coding value like
  12350. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12351. // it was never meant to see.
  12352. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12353. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12354. Server svr;
  12355. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12356. res.set_content(body, "image/jpeg");
  12357. res.set_header("Content-Encoding", "fibre");
  12358. });
  12359. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12360. res.set_content(body, "image/jpeg");
  12361. res.set_header("Content-Encoding", "gzip, br");
  12362. });
  12363. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12364. res.set_content(body, "image/jpeg");
  12365. res.set_header("Content-Encoding", "x-zstd-ish");
  12366. });
  12367. auto port = svr.bind_to_any_port(HOST);
  12368. thread t = thread([&]() { svr.listen_after_bind(); });
  12369. auto se = detail::scope_exit([&] {
  12370. svr.stop();
  12371. t.join();
  12372. ASSERT_FALSE(svr.is_running());
  12373. });
  12374. svr.wait_until_ready();
  12375. Client cli(HOST, port);
  12376. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12377. auto res = cli.Get(path);
  12378. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12379. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12380. // Not a coding we recognize, so the payload comes back untouched
  12381. EXPECT_EQ(body, res->body) << path;
  12382. }
  12383. }
  12384. // A content coding cpp-httplib recognizes but was not built with must be
  12385. // reported as such. Handing the still-compressed payload back to the caller
  12386. // would silently corrupt it.
  12387. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12388. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12389. Server svr;
  12390. // "image/jpeg" keeps the server from applying a content coding of its own,
  12391. // so the hand-crafted Content-Encoding below survives.
  12392. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12393. res.set_content(gzipped, "image/jpeg");
  12394. res.set_header("Content-Encoding", "gzip");
  12395. });
  12396. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12397. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12398. res.set_content(gzipped, "image/jpeg");
  12399. res.set_header("Content-Encoding", "GZIP");
  12400. });
  12401. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12402. auto se = detail::scope_exit([&] {
  12403. svr.stop();
  12404. t.join();
  12405. ASSERT_FALSE(svr.is_running());
  12406. });
  12407. svr.wait_until_ready();
  12408. Client cli(HOST, PORT);
  12409. {
  12410. auto res = cli.Get("/gzipped");
  12411. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12413. EXPECT_EQ("Hello World!", res->body);
  12414. #else
  12415. ASSERT_FALSE(res);
  12416. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12417. #endif
  12418. }
  12419. {
  12420. // open_stream() must behave the same way.
  12421. auto handle = cli.open_stream("GET", "/gzipped");
  12422. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12423. ASSERT_TRUE(handle.is_valid());
  12424. std::string received;
  12425. char buf[256];
  12426. ssize_t n;
  12427. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12428. received.append(buf, static_cast<size_t>(n));
  12429. }
  12430. EXPECT_EQ("Hello World!", received);
  12431. #else
  12432. EXPECT_FALSE(handle.is_valid());
  12433. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12434. #endif
  12435. }
  12436. {
  12437. // A differently-cased coding must not be mistaken for an unknown one, or
  12438. // the body would be handed back still compressed.
  12439. auto res = cli.Get("/gzipped-uppercase");
  12440. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12442. EXPECT_EQ("Hello World!", res->body);
  12443. #else
  12444. ASSERT_FALSE(res);
  12445. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12446. #endif
  12447. }
  12448. }
  12449. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12450. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12451. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12452. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12453. // body a second time and appending a second Content-Encoding field line, so
  12454. // clients that decode one coding per listed value handed back raw gzip bytes.
  12455. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12456. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12457. Server svr;
  12458. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12459. // keeps the server from applying a coding of its own.
  12460. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12461. res.set_content(gzipped, "text/plain");
  12462. res.set_header("Content-Encoding", "gzip");
  12463. });
  12464. auto port = svr.bind_to_any_port(HOST);
  12465. thread t = thread([&]() { svr.listen_after_bind(); });
  12466. auto se = detail::scope_exit([&] {
  12467. svr.stop();
  12468. t.join();
  12469. ASSERT_FALSE(svr.is_running());
  12470. });
  12471. svr.wait_until_ready();
  12472. Client cli(HOST, port);
  12473. Headers headers = {{"Accept-Encoding", "gzip"}};
  12474. auto res = cli.Get("/pre-gzipped", headers);
  12475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12476. EXPECT_EQ(StatusCode::OK_200, res->status);
  12477. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12478. EXPECT_EQ("Hello World!", res->body);
  12479. }
  12480. // A chunked provider settles its coding where the headers are written and
  12481. // reuses it at write time. Both ends of that have to hold: a handler's own
  12482. // Content-Encoding suppresses the coding, and a response without one is still
  12483. // compressed as it always was.
  12484. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12485. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12486. const std::string plain = "Hello World! Hello World! Hello World!";
  12487. Server svr;
  12488. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12489. res.set_header("Content-Encoding", "gzip");
  12490. res.set_chunked_content_provider(
  12491. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12492. sink.write(gzipped.data(), gzipped.size());
  12493. sink.done();
  12494. return true;
  12495. });
  12496. });
  12497. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12498. res.set_chunked_content_provider(
  12499. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12500. sink.write(plain.data(), plain.size());
  12501. sink.done();
  12502. return true;
  12503. });
  12504. });
  12505. auto port = svr.bind_to_any_port(HOST);
  12506. thread t = thread([&]() { svr.listen_after_bind(); });
  12507. auto se = detail::scope_exit([&] {
  12508. svr.stop();
  12509. t.join();
  12510. ASSERT_FALSE(svr.is_running());
  12511. });
  12512. svr.wait_until_ready();
  12513. Client cli(HOST, port);
  12514. Headers headers = {{"Accept-Encoding", "gzip"}};
  12515. {
  12516. auto res = cli.Get("/pre-gzipped", headers);
  12517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12518. EXPECT_EQ(StatusCode::OK_200, res->status);
  12519. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12520. EXPECT_EQ("Hello World!", res->body);
  12521. }
  12522. {
  12523. auto res = cli.Get("/negotiated", headers);
  12524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12525. EXPECT_EQ(StatusCode::OK_200, res->status);
  12526. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12527. EXPECT_EQ(plain, res->body);
  12528. }
  12529. }
  12530. #endif
  12531. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12532. // the same message as the comma-joined one, so both have to be read the same
  12533. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12534. // single gzip coding, and a body the sender says was encoded twice was handed
  12535. // back after one pass, still compressed but presented as decoded.
  12536. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12537. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12538. Server svr;
  12539. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12540. res.set_content(body, "image/jpeg");
  12541. res.headers.emplace("Content-Encoding", "gzip");
  12542. res.headers.emplace("Content-Encoding", "gzip");
  12543. });
  12544. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12545. res.set_content(body, "image/jpeg");
  12546. res.set_header("Content-Encoding", "gzip, gzip");
  12547. });
  12548. auto port = svr.bind_to_any_port(HOST);
  12549. thread t = thread([&]() { svr.listen_after_bind(); });
  12550. auto se = detail::scope_exit([&] {
  12551. svr.stop();
  12552. t.join();
  12553. ASSERT_FALSE(svr.is_running());
  12554. });
  12555. svr.wait_until_ready();
  12556. Client cli(HOST, port);
  12557. // Two codings is not something cpp-httplib decodes, so both representations
  12558. // take the pass-through path rather than one of them being gunzipped once.
  12559. for (const char *path : {"/split", "/joined"}) {
  12560. auto res = cli.Get(path);
  12561. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12562. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12563. EXPECT_EQ(body, res->body) << path;
  12564. }
  12565. }
  12566. // Regression test for DoS vulnerability: a malicious server sending a response
  12567. // without Content-Length header must not cause unbounded memory consumption on
  12568. // the client side. The client should stop reading after a reasonable limit,
  12569. // similar to the server-side set_payload_max_length protection.
  12570. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12571. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12572. #ifndef _WIN32
  12573. signal(SIGPIPE, SIG_IGN);
  12574. #endif
  12575. auto server_thread = std::thread([] {
  12576. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12577. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12578. default_socket_options(srv);
  12579. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12580. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12581. sockaddr_in addr{};
  12582. addr.sin_family = AF_INET;
  12583. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12584. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12585. int opt = 1;
  12586. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12587. #ifdef _WIN32
  12588. reinterpret_cast<const char *>(&opt),
  12589. #else
  12590. &opt,
  12591. #endif
  12592. sizeof(opt));
  12593. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12594. ::listen(srv, 1);
  12595. sockaddr_in cli_addr{};
  12596. socklen_t cli_len = sizeof(cli_addr);
  12597. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12598. if (cli != INVALID_SOCKET) {
  12599. char buf[4096];
  12600. ::recv(cli, buf, sizeof(buf), 0);
  12601. // Malicious response: no Content-Length, no chunked encoding
  12602. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12603. "Connection: close\r\n"
  12604. "\r\n";
  12605. ::send(cli,
  12606. #ifdef _WIN32
  12607. static_cast<const char *>(response_header.c_str()),
  12608. static_cast<int>(response_header.size()),
  12609. #else
  12610. response_header.c_str(), response_header.size(),
  12611. #endif
  12612. 0);
  12613. // Send 10MB of data
  12614. std::string chunk(64 * 1024, 'A');
  12615. size_t total_sent = 0;
  12616. while (total_sent < MALICIOUS_DATA_SIZE) {
  12617. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12618. auto sent = ::send(cli,
  12619. #ifdef _WIN32
  12620. static_cast<const char *>(chunk.c_str()),
  12621. static_cast<int>(to_send),
  12622. #else
  12623. chunk.c_str(), to_send,
  12624. #endif
  12625. 0);
  12626. if (sent <= 0) break;
  12627. total_sent += static_cast<size_t>(sent);
  12628. }
  12629. detail::close_socket(cli);
  12630. }
  12631. detail::close_socket(srv);
  12632. });
  12633. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12634. size_t total_read = 0;
  12635. {
  12636. Client cli("127.0.0.1", PORT + 2);
  12637. cli.set_read_timeout(5, 0);
  12638. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12639. auto stream = cli.open_stream("GET", "/malicious");
  12640. ASSERT_TRUE(stream.is_valid());
  12641. char buffer[64 * 1024];
  12642. ssize_t n;
  12643. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12644. total_read += static_cast<size_t>(n);
  12645. }
  12646. } // StreamHandle and Client destroyed here, closing the socket
  12647. server_thread.join();
  12648. // With set_payload_max_length, the client must stop reading before consuming
  12649. // all 10MB. The read loop should be cut off at or near the configured limit.
  12650. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12651. << "Client read " << total_read << " bytes, exceeding the configured "
  12652. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12653. }
  12654. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12655. // the entire response body without truncation.
  12656. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12657. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12658. #ifndef _WIN32
  12659. signal(SIGPIPE, SIG_IGN);
  12660. #endif
  12661. auto server_thread = std::thread([] {
  12662. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12663. default_socket_options(srv);
  12664. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12665. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12666. sockaddr_in addr{};
  12667. addr.sin_family = AF_INET;
  12668. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12669. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12670. int opt = 1;
  12671. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12672. #ifdef _WIN32
  12673. reinterpret_cast<const char *>(&opt),
  12674. #else
  12675. &opt,
  12676. #endif
  12677. sizeof(opt));
  12678. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12679. ::listen(srv, 1);
  12680. sockaddr_in cli_addr{};
  12681. socklen_t cli_len = sizeof(cli_addr);
  12682. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12683. if (cli != INVALID_SOCKET) {
  12684. char buf[4096];
  12685. ::recv(cli, buf, sizeof(buf), 0);
  12686. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12687. "Connection: close\r\n"
  12688. "\r\n";
  12689. ::send(cli,
  12690. #ifdef _WIN32
  12691. static_cast<const char *>(response_header.c_str()),
  12692. static_cast<int>(response_header.size()),
  12693. #else
  12694. response_header.c_str(), response_header.size(),
  12695. #endif
  12696. 0);
  12697. std::string chunk(64 * 1024, 'A');
  12698. size_t total_sent = 0;
  12699. while (total_sent < DATA_SIZE) {
  12700. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12701. auto sent = ::send(cli,
  12702. #ifdef _WIN32
  12703. static_cast<const char *>(chunk.c_str()),
  12704. static_cast<int>(to_send),
  12705. #else
  12706. chunk.c_str(), to_send,
  12707. #endif
  12708. 0);
  12709. if (sent <= 0) break;
  12710. total_sent += static_cast<size_t>(sent);
  12711. }
  12712. #ifdef _WIN32
  12713. ::shutdown(cli, SD_SEND);
  12714. #else
  12715. ::shutdown(cli, SHUT_WR);
  12716. #endif
  12717. // Drain until the client closes its end, ensuring all data is delivered
  12718. char drain[1024];
  12719. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12720. detail::close_socket(cli);
  12721. }
  12722. detail::close_socket(srv);
  12723. });
  12724. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12725. size_t total_read = 0;
  12726. {
  12727. Client cli("127.0.0.1", PORT + 2);
  12728. cli.set_read_timeout(5, 0);
  12729. cli.set_payload_max_length(0); // 0 means no limit
  12730. auto stream = cli.open_stream("GET", "/data");
  12731. ASSERT_TRUE(stream.is_valid());
  12732. char buffer[64 * 1024];
  12733. ssize_t n;
  12734. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12735. total_read += static_cast<size_t>(n);
  12736. }
  12737. }
  12738. server_thread.join();
  12739. EXPECT_EQ(total_read, DATA_SIZE)
  12740. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12741. << " bytes without truncation, but only read " << total_read << " bytes.";
  12742. }
  12743. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12744. // enormous Content-Length must not cause the client to pre-allocate a huge
  12745. // response body buffer. The reservation is capped at payload_max_length_, and
  12746. // the read itself fails when the body exceeds the limit.
  12747. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12748. #ifndef _WIN32
  12749. signal(SIGPIPE, SIG_IGN);
  12750. #endif
  12751. auto server_thread = std::thread([] {
  12752. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12753. default_socket_options(srv);
  12754. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12755. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12756. sockaddr_in addr{};
  12757. addr.sin_family = AF_INET;
  12758. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12759. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12760. int opt = 1;
  12761. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12762. #ifdef _WIN32
  12763. reinterpret_cast<const char *>(&opt),
  12764. #else
  12765. &opt,
  12766. #endif
  12767. sizeof(opt));
  12768. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12769. ::listen(srv, 1);
  12770. sockaddr_in cli_addr{};
  12771. socklen_t cli_len = sizeof(cli_addr);
  12772. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12773. if (cli != INVALID_SOCKET) {
  12774. char buf[4096];
  12775. ::recv(cli, buf, sizeof(buf), 0);
  12776. // Malicious response: claim a 20GB body but send only a tiny payload.
  12777. std::string response = "HTTP/1.1 200 OK\r\n"
  12778. "Content-Length: 20000000000\r\n"
  12779. "\r\n"
  12780. "abc";
  12781. ::send(cli,
  12782. #ifdef _WIN32
  12783. static_cast<const char *>(response.c_str()),
  12784. static_cast<int>(response.size()),
  12785. #else
  12786. response.c_str(), response.size(),
  12787. #endif
  12788. 0);
  12789. detail::close_socket(cli);
  12790. }
  12791. detail::close_socket(srv);
  12792. });
  12793. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12794. {
  12795. Client cli("127.0.0.1", PORT + 2);
  12796. cli.set_read_timeout(5, 0);
  12797. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12798. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12799. // (server claims more bytes than payload_max_length permits), but it must
  12800. // not exhaust memory before getting there.
  12801. auto res = cli.Get("/malicious");
  12802. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12803. }
  12804. server_thread.join();
  12805. }
  12806. // Verify that content_receiver bypasses the default payload_max_length,
  12807. // allowing streaming downloads larger than 100MB without requiring an explicit
  12808. // set_payload_max_length call.
  12809. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12810. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12811. #ifndef _WIN32
  12812. signal(SIGPIPE, SIG_IGN);
  12813. #endif
  12814. auto server_thread = std::thread([] {
  12815. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12816. default_socket_options(srv);
  12817. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12818. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12819. sockaddr_in addr{};
  12820. addr.sin_family = AF_INET;
  12821. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12822. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12823. int opt = 1;
  12824. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12825. #ifdef _WIN32
  12826. reinterpret_cast<const char *>(&opt),
  12827. #else
  12828. &opt,
  12829. #endif
  12830. sizeof(opt));
  12831. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12832. ::listen(srv, 1);
  12833. sockaddr_in cli_addr{};
  12834. socklen_t cli_len = sizeof(cli_addr);
  12835. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12836. if (cli != INVALID_SOCKET) {
  12837. char buf[4096];
  12838. ::recv(cli, buf, sizeof(buf), 0);
  12839. // Response with Content-Length larger than default 100MB limit
  12840. auto content_length = std::to_string(DATA_SIZE);
  12841. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12842. "Content-Length: " +
  12843. content_length +
  12844. "\r\n"
  12845. "Connection: close\r\n"
  12846. "\r\n";
  12847. ::send(cli,
  12848. #ifdef _WIN32
  12849. static_cast<const char *>(response_header.c_str()),
  12850. static_cast<int>(response_header.size()),
  12851. #else
  12852. response_header.c_str(), response_header.size(),
  12853. #endif
  12854. 0);
  12855. std::string chunk(64 * 1024, 'A');
  12856. size_t total_sent = 0;
  12857. while (total_sent < DATA_SIZE) {
  12858. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12859. auto sent = ::send(cli,
  12860. #ifdef _WIN32
  12861. static_cast<const char *>(chunk.c_str()),
  12862. static_cast<int>(to_send),
  12863. #else
  12864. chunk.c_str(), to_send,
  12865. #endif
  12866. 0);
  12867. if (sent <= 0) break;
  12868. total_sent += static_cast<size_t>(sent);
  12869. }
  12870. detail::close_socket(cli);
  12871. }
  12872. detail::close_socket(srv);
  12873. });
  12874. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12875. size_t total_received = 0;
  12876. {
  12877. Client cli("127.0.0.1", PORT + 2);
  12878. cli.set_read_timeout(10, 0);
  12879. // Do NOT call set_payload_max_length — use the default 100MB limit
  12880. auto res =
  12881. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12882. total_received += data_length;
  12883. return true;
  12884. });
  12885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12886. EXPECT_EQ(StatusCode::OK_200, res->status);
  12887. }
  12888. server_thread.join();
  12889. EXPECT_EQ(total_received, DATA_SIZE)
  12890. << "With content_receiver, the client should read all " << DATA_SIZE
  12891. << " bytes despite the default 100MB payload_max_length, but only read "
  12892. << total_received << " bytes.";
  12893. }
  12894. // Verify that an explicit set_payload_max_length smaller than the response is
  12895. // enforced even when a content_receiver is used.
  12896. TEST(ClientVulnerabilityTest,
  12897. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12898. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12899. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12900. #ifndef _WIN32
  12901. signal(SIGPIPE, SIG_IGN);
  12902. #endif
  12903. auto server_thread = std::thread([] {
  12904. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12905. default_socket_options(srv);
  12906. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12907. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12908. sockaddr_in addr{};
  12909. addr.sin_family = AF_INET;
  12910. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12911. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12912. int opt = 1;
  12913. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12914. #ifdef _WIN32
  12915. reinterpret_cast<const char *>(&opt),
  12916. #else
  12917. &opt,
  12918. #endif
  12919. sizeof(opt));
  12920. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12921. ::listen(srv, 1);
  12922. sockaddr_in cli_addr{};
  12923. socklen_t cli_len = sizeof(cli_addr);
  12924. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12925. if (cli != INVALID_SOCKET) {
  12926. char buf[4096];
  12927. ::recv(cli, buf, sizeof(buf), 0);
  12928. auto content_length = std::to_string(DATA_SIZE);
  12929. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12930. "Content-Length: " +
  12931. content_length +
  12932. "\r\n"
  12933. "Connection: close\r\n"
  12934. "\r\n";
  12935. ::send(cli,
  12936. #ifdef _WIN32
  12937. static_cast<const char *>(response_header.c_str()),
  12938. static_cast<int>(response_header.size()),
  12939. #else
  12940. response_header.c_str(), response_header.size(),
  12941. #endif
  12942. 0);
  12943. std::string chunk(64 * 1024, 'A');
  12944. size_t total_sent = 0;
  12945. while (total_sent < DATA_SIZE) {
  12946. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12947. auto sent = ::send(cli,
  12948. #ifdef _WIN32
  12949. static_cast<const char *>(chunk.c_str()),
  12950. static_cast<int>(to_send),
  12951. #else
  12952. chunk.c_str(), to_send,
  12953. #endif
  12954. 0);
  12955. if (sent <= 0) break;
  12956. total_sent += static_cast<size_t>(sent);
  12957. }
  12958. detail::close_socket(cli);
  12959. }
  12960. detail::close_socket(srv);
  12961. });
  12962. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12963. size_t total_received = 0;
  12964. {
  12965. Client cli("127.0.0.1", PORT + 2);
  12966. cli.set_read_timeout(10, 0);
  12967. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12968. auto res =
  12969. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12970. total_received += data_length;
  12971. return true;
  12972. });
  12973. // Should fail because 200MB exceeds the explicit 150MB limit
  12974. EXPECT_FALSE(res);
  12975. }
  12976. server_thread.join();
  12977. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12978. << "Client with content_receiver should respect the explicit "
  12979. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12980. << total_received << " bytes.";
  12981. }
  12982. // Verify that an explicit set_payload_max_length larger than the response
  12983. // allows the content_receiver to read all data successfully.
  12984. TEST(ClientVulnerabilityTest,
  12985. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12986. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12987. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12988. #ifndef _WIN32
  12989. signal(SIGPIPE, SIG_IGN);
  12990. #endif
  12991. auto server_thread = std::thread([] {
  12992. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12993. default_socket_options(srv);
  12994. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12995. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12996. sockaddr_in addr{};
  12997. addr.sin_family = AF_INET;
  12998. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12999. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13000. int opt = 1;
  13001. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13002. #ifdef _WIN32
  13003. reinterpret_cast<const char *>(&opt),
  13004. #else
  13005. &opt,
  13006. #endif
  13007. sizeof(opt));
  13008. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13009. ::listen(srv, 1);
  13010. sockaddr_in cli_addr{};
  13011. socklen_t cli_len = sizeof(cli_addr);
  13012. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13013. if (cli != INVALID_SOCKET) {
  13014. char buf[4096];
  13015. ::recv(cli, buf, sizeof(buf), 0);
  13016. auto content_length = std::to_string(DATA_SIZE);
  13017. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13018. "Content-Length: " +
  13019. content_length +
  13020. "\r\n"
  13021. "Connection: close\r\n"
  13022. "\r\n";
  13023. ::send(cli,
  13024. #ifdef _WIN32
  13025. static_cast<const char *>(response_header.c_str()),
  13026. static_cast<int>(response_header.size()),
  13027. #else
  13028. response_header.c_str(), response_header.size(),
  13029. #endif
  13030. 0);
  13031. std::string chunk(64 * 1024, 'A');
  13032. size_t total_sent = 0;
  13033. while (total_sent < DATA_SIZE) {
  13034. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13035. auto sent = ::send(cli,
  13036. #ifdef _WIN32
  13037. static_cast<const char *>(chunk.c_str()),
  13038. static_cast<int>(to_send),
  13039. #else
  13040. chunk.c_str(), to_send,
  13041. #endif
  13042. 0);
  13043. if (sent <= 0) break;
  13044. total_sent += static_cast<size_t>(sent);
  13045. }
  13046. #ifdef _WIN32
  13047. ::shutdown(cli, SD_SEND);
  13048. #else
  13049. ::shutdown(cli, SHUT_WR);
  13050. #endif
  13051. char drain[1024];
  13052. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13053. detail::close_socket(cli);
  13054. }
  13055. detail::close_socket(srv);
  13056. });
  13057. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13058. size_t total_received = 0;
  13059. {
  13060. Client cli("127.0.0.1", PORT + 2);
  13061. cli.set_read_timeout(10, 0);
  13062. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13063. auto res =
  13064. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13065. total_received += data_length;
  13066. return true;
  13067. });
  13068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13069. EXPECT_EQ(StatusCode::OK_200, res->status);
  13070. }
  13071. server_thread.join();
  13072. EXPECT_EQ(total_received, DATA_SIZE)
  13073. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13074. << " bytes (larger than " << DATA_SIZE
  13075. << " bytes response), content_receiver should read all data, but only "
  13076. "read "
  13077. << total_received << " bytes.";
  13078. }
  13079. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13080. // Regression test for "zip bomb" attack on the client side: a malicious server
  13081. // sends a small gzip-compressed response that decompresses to a huge payload.
  13082. // The client must enforce payload_max_length on the decompressed size.
  13083. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13084. constexpr size_t DECOMPRESSED_SIZE =
  13085. 10 * 1024 * 1024; // 10MB after decompression
  13086. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13087. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13088. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13089. std::string compressed;
  13090. {
  13091. httplib::detail::gzip_compressor compressor;
  13092. bool ok =
  13093. compressor.compress(uncompressed.data(), uncompressed.size(),
  13094. /*last=*/true, [&](const char *buf, size_t len) {
  13095. compressed.append(buf, len);
  13096. return true;
  13097. });
  13098. ASSERT_TRUE(ok);
  13099. }
  13100. // Sanity: compressed data should be much smaller than the decompressed size
  13101. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13102. #ifndef _WIN32
  13103. signal(SIGPIPE, SIG_IGN);
  13104. #endif
  13105. // Set up the listening socket in the main thread so the server is guaranteed
  13106. // to be ready before the client connects (eliminates race condition).
  13107. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13108. default_socket_options(srv);
  13109. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13110. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13111. sockaddr_in addr{};
  13112. addr.sin_family = AF_INET;
  13113. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13114. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13115. int opt = 1;
  13116. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13117. #ifdef _WIN32
  13118. reinterpret_cast<const char *>(&opt),
  13119. #else
  13120. &opt,
  13121. #endif
  13122. sizeof(opt));
  13123. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13124. ASSERT_EQ(0, ::listen(srv, 1));
  13125. auto server_thread = std::thread([&compressed, srv] {
  13126. sockaddr_in cli_addr{};
  13127. socklen_t cli_len = sizeof(cli_addr);
  13128. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13129. if (cli != INVALID_SOCKET) {
  13130. // Read the full HTTP request (until \r\n\r\n)
  13131. char buf[4096];
  13132. size_t total = 0;
  13133. while (total < sizeof(buf)) {
  13134. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13135. if (n <= 0) break;
  13136. total += static_cast<size_t>(n);
  13137. // Check for end of headers
  13138. if (total >= 4) {
  13139. std::string req(buf, total);
  13140. if (req.find("\r\n\r\n") != std::string::npos) break;
  13141. }
  13142. }
  13143. // Malicious response: gzip-compressed body, no Content-Length
  13144. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13145. "Content-Encoding: gzip\r\n"
  13146. "Connection: close\r\n"
  13147. "\r\n";
  13148. ::send(cli,
  13149. #ifdef _WIN32
  13150. static_cast<const char *>(response_header.c_str()),
  13151. static_cast<int>(response_header.size()),
  13152. #else
  13153. response_header.c_str(), response_header.size(),
  13154. #endif
  13155. 0);
  13156. // Send the compressed payload (small on the wire, huge when decompressed)
  13157. size_t total_sent = 0;
  13158. while (total_sent < compressed.size()) {
  13159. auto to_send = std::min(compressed.size() - total_sent,
  13160. static_cast<size_t>(64 * 1024));
  13161. auto sent =
  13162. ::send(cli,
  13163. #ifdef _WIN32
  13164. static_cast<const char *>(compressed.c_str() + total_sent),
  13165. static_cast<int>(to_send),
  13166. #else
  13167. compressed.c_str() + total_sent, to_send,
  13168. #endif
  13169. 0);
  13170. if (sent <= 0) break;
  13171. total_sent += static_cast<size_t>(sent);
  13172. }
  13173. detail::close_socket(cli);
  13174. }
  13175. });
  13176. auto se = detail::scope_exit([&] {
  13177. detail::close_socket(srv);
  13178. server_thread.join();
  13179. });
  13180. size_t total_decompressed = 0;
  13181. {
  13182. Client cli("127.0.0.1", PORT + 3);
  13183. cli.set_read_timeout(5, 0);
  13184. cli.set_decompress(true);
  13185. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13186. auto stream = cli.open_stream("GET", "/zipbomb");
  13187. ASSERT_TRUE(stream.is_valid());
  13188. char buffer[64 * 1024];
  13189. ssize_t n;
  13190. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13191. total_decompressed += static_cast<size_t>(n);
  13192. }
  13193. }
  13194. // The decompressed size must be capped by payload_max_length. Without
  13195. // protection, the client would decompress the full 10MB from a tiny
  13196. // compressed payload, enabling a zip bomb DoS attack.
  13197. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13198. << "Client decompressed " << total_decompressed
  13199. << " bytes from a gzip response. The decompressed size should be "
  13200. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13201. }
  13202. #endif
  13203. TEST(HostAndPortPropertiesTest, NoSSL) {
  13204. httplib::Client cli("www.google.com", 1234);
  13205. ASSERT_EQ("www.google.com", cli.host());
  13206. ASSERT_EQ(1234, cli.port());
  13207. }
  13208. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13209. httplib::Client cli("www.google.com:1234");
  13210. ASSERT_EQ("www.google.com", cli.host());
  13211. ASSERT_EQ(1234, cli.port());
  13212. }
  13213. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13214. // Port number that overflows int — should not crash, client becomes invalid
  13215. httplib::Client cli("http://www.google.com:99999999999999999999");
  13216. ASSERT_FALSE(cli.is_valid());
  13217. }
  13218. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13219. // Port 99999 exceeds valid range (1-65535) — should not crash
  13220. httplib::Client cli("http://www.google.com:99999");
  13221. ASSERT_FALSE(cli.is_valid());
  13222. auto res = cli.Get("/");
  13223. EXPECT_FALSE(res);
  13224. EXPECT_EQ(Error::Connection, res.error());
  13225. }
  13226. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13227. httplib::Client cli("http://user:pass@localhost:1234");
  13228. ASSERT_FALSE(cli.is_valid());
  13229. EXPECT_FALSE(cli.Get("/"));
  13230. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13231. }
  13232. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13233. httplib::Client cli("http://www.google.com:80abc");
  13234. ASSERT_FALSE(cli.is_valid());
  13235. }
  13236. #ifdef CPPHTTPLIB_SSL_ENABLED
  13237. TEST(HostAndPortPropertiesTest, SSL) {
  13238. httplib::SSLClient cli("www.google.com");
  13239. ASSERT_EQ("www.google.com", cli.host());
  13240. ASSERT_EQ(443, cli.port());
  13241. }
  13242. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13243. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13244. std::string cert;
  13245. read_file(CA_CERT_FILE, cert);
  13246. httplib::SSLClient httplib_client("www.google.com");
  13247. // Load CA store first time
  13248. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13249. // Load CA store second time (update)
  13250. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13251. // Verify client is still valid and can make connections
  13252. httplib_client.enable_server_certificate_verification(true);
  13253. auto res = httplib_client.Get("/");
  13254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13255. // Google may return 200 or 301 depending on various factors
  13256. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13257. res->status == StatusCode::MovedPermanently_301);
  13258. }
  13259. TEST(SSLClientTest, ServerNameIndication_Online) {
  13260. auto host = "httpbingo.org";
  13261. auto path = std::string{"/get"};
  13262. SSLClient cli(host, 443);
  13263. auto res = cli.Get(path);
  13264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13265. ASSERT_EQ(StatusCode::OK_200, res->status);
  13266. }
  13267. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13268. // Use a site that will cause SSL verification failure due to self-signed cert
  13269. SSLClient cli("self-signed.badssl.com", 443);
  13270. cli.enable_server_certificate_verification(true);
  13271. auto res = cli.Get("/");
  13272. ASSERT_TRUE(!res);
  13273. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13274. // Verify backend error is captured for SSLServerVerification
  13275. // This occurs when certificate verification fails
  13276. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13277. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13278. EXPECT_NE(0UL, res.ssl_backend_error());
  13279. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13280. // For OpenSSL, ssl_error is 0 for verification errors
  13281. EXPECT_EQ(0, res.ssl_error());
  13282. #if !defined(_WIN32) || \
  13283. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13284. // On non-Windows or when Windows Schannel is disabled, the error comes
  13285. // from OpenSSL's verification
  13286. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13287. res.ssl_backend_error());
  13288. #endif
  13289. #endif
  13290. }
  13291. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13292. // Use a site where hostname doesn't match the certificate
  13293. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13294. SSLClient cli("wrong.host.badssl.com", 443);
  13295. cli.enable_server_certificate_verification(true);
  13296. cli.enable_server_hostname_verification(true);
  13297. auto res = cli.Get("/");
  13298. ASSERT_TRUE(!res);
  13299. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13300. // Verify backend error is captured for hostname verification failure
  13301. EXPECT_NE(0UL, res.ssl_backend_error());
  13302. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13303. // For OpenSSL, ssl_error is 0 for verification errors
  13304. EXPECT_EQ(0, res.ssl_error());
  13305. #if !defined(_WIN32) || \
  13306. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13307. // On non-Windows or when Windows Schannel is disabled, the error comes
  13308. // from OpenSSL's hostname verification
  13309. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13310. res.ssl_backend_error());
  13311. #endif
  13312. #endif
  13313. }
  13314. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13315. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13316. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13317. SSLClient cli("www.google.com", 443);
  13318. cli.enable_server_certificate_verification(true);
  13319. auto res = cli.Get("/");
  13320. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13321. }
  13322. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13323. SSLClient cli("www.google.com", 443);
  13324. cli.enable_server_certificate_verification(true);
  13325. cli.enable_windows_certificate_verification(false);
  13326. auto res = cli.Get("/");
  13327. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13328. }
  13329. // The server sends an intermediate cross-signed by a root Windows trusts,
  13330. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13331. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13332. SSLClient cli("accounts.spotify.com", 443);
  13333. auto res = cli.Get("/");
  13334. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13335. << " ssl_backend_error=" << res.ssl_backend_error();
  13336. }
  13337. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13338. // policy status, which no backend reports for a self-signed certificate.
  13339. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13340. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13341. ASSERT_TRUE(svr.is_valid());
  13342. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13343. auto se = detail::scope_exit([&] {
  13344. svr.stop();
  13345. t.join();
  13346. ASSERT_FALSE(svr.is_running());
  13347. });
  13348. svr.wait_until_ready();
  13349. SSLClient cli("127.0.0.1", PORT);
  13350. cli.set_connection_timeout(30);
  13351. auto res = cli.Get("/");
  13352. ASSERT_FALSE(res);
  13353. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13354. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13355. }
  13356. #endif
  13357. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13358. Client cli("https://google.com");
  13359. auto res = cli.Get("/");
  13360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13361. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13362. }
  13363. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13364. SSLClient cli("google.com");
  13365. cli.set_ca_cert_path(CA_CERT_FILE);
  13366. auto res = cli.Get("/");
  13367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13368. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13369. }
  13370. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13371. SSLClient cli("google.com");
  13372. cli.enable_server_certificate_verification(true);
  13373. cli.set_ca_cert_path("hello");
  13374. auto res = cli.Get("/");
  13375. ASSERT_TRUE(!res);
  13376. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13377. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13378. // should be set
  13379. EXPECT_EQ(0, res.ssl_error());
  13380. // Verify backend error is captured for SSLLoadingCerts
  13381. // This error occurs when loading CA certificates fails
  13382. EXPECT_NE(0UL, res.ssl_backend_error());
  13383. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13384. // OpenSSL specific error codes:
  13385. // > openssl errstr 0x80000002
  13386. // error:80000002:system library::No such file or directory
  13387. // > openssl errstr 0xA000126
  13388. // error:0A000126:SSL routines::unexpected eof while reading
  13389. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13390. res.ssl_backend_error() == 0xA000126);
  13391. #endif
  13392. }
  13393. TEST(SSLClientTest, ServerCertificateVerification4) {
  13394. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13395. ASSERT_TRUE(svr.is_valid());
  13396. svr.Get("/test", [&](const Request &, Response &res) {
  13397. res.set_content("test", "text/plain");
  13398. svr.stop();
  13399. ASSERT_TRUE(true);
  13400. });
  13401. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13402. auto se = detail::scope_exit([&] {
  13403. t.join();
  13404. ASSERT_FALSE(svr.is_running());
  13405. });
  13406. svr.wait_until_ready();
  13407. SSLClient cli("127.0.0.1", PORT);
  13408. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13409. cli.enable_server_certificate_verification(true);
  13410. cli.set_connection_timeout(30);
  13411. auto res = cli.Get("/test");
  13412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13413. ASSERT_EQ(StatusCode::OK_200, res->status);
  13414. }
  13415. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13416. std::string cert;
  13417. read_file(CA_CERT_FILE, cert);
  13418. SSLClient cli("google.com");
  13419. cli.load_ca_cert_store(cert.data(), cert.size());
  13420. const auto res = cli.Get("/");
  13421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13422. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13423. }
  13424. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13425. // clang-format off
  13426. static constexpr char cert[] =
  13427. "GlobalSign Root CA\n"
  13428. "==================\n"
  13429. "-----BEGIN CERTIFICATE-----\n"
  13430. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13431. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13432. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13433. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13434. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13435. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13436. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13437. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13438. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13439. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13440. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13441. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13442. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13443. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13444. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13445. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13446. "-----END CERTIFICATE-----\n";
  13447. // clang-format on
  13448. SSLClient cli("google.com");
  13449. cli.load_ca_cert_store(cert, sizeof(cert));
  13450. const auto res = cli.Get("/");
  13451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13452. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13453. }
  13454. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13455. SSLClient cli("www.youtube.com");
  13456. cli.set_ca_cert_path(CA_CERT_FILE);
  13457. cli.enable_server_certificate_verification(true);
  13458. cli.set_follow_location(true);
  13459. auto res = cli.Get("/");
  13460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13461. ASSERT_EQ(StatusCode::OK_200, res->status);
  13462. }
  13463. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13464. SSLClient cli("wWw.YouTube.Com");
  13465. cli.set_ca_cert_path(CA_CERT_FILE);
  13466. cli.enable_server_certificate_verification(true);
  13467. cli.enable_server_hostname_verification(true);
  13468. cli.set_follow_location(true);
  13469. auto res = cli.Get("/");
  13470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13471. ASSERT_EQ(StatusCode::OK_200, res->status);
  13472. }
  13473. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13474. SSLClient cli("gOoGlE.COm");
  13475. cli.enable_server_certificate_verification(true);
  13476. cli.enable_server_hostname_verification(true);
  13477. cli.set_follow_location(true);
  13478. auto res = cli.Get("/");
  13479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13480. ASSERT_EQ(StatusCode::OK_200, res->status);
  13481. }
  13482. TEST(SSLClientTest, Issue2004_Online) {
  13483. Client client("https://google.com");
  13484. client.set_follow_location(true);
  13485. auto res = client.Get("/");
  13486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13487. ASSERT_EQ(StatusCode::OK_200, res->status);
  13488. auto body = res->body;
  13489. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13490. }
  13491. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13492. // Create SSLClient with invalid cert/key to make is_valid() return false
  13493. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13494. "nonexistent_key.pem");
  13495. // is_valid() should be false due to cert loading failure
  13496. ASSERT_FALSE(cli.is_valid());
  13497. auto res = cli.Get("/");
  13498. ASSERT_FALSE(res);
  13499. EXPECT_EQ(Error::SSLConnection, res.error());
  13500. }
  13501. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13502. // Test for Issue #2251: SSL error not properly reported when client cert
  13503. // and key paths are swapped or mismatched
  13504. // This simulates the scenario where user accidentally swaps the cert and key
  13505. // files
  13506. // Using client cert file as private key and vice versa (completely wrong)
  13507. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13508. // Should fail validation due to cert/key mismatch
  13509. ASSERT_FALSE(cli.is_valid());
  13510. // Attempt to make a request should fail with proper error
  13511. auto res = cli.Get("/");
  13512. ASSERT_FALSE(res);
  13513. EXPECT_EQ(Error::SSLConnection, res.error());
  13514. // SSL error should be recorded in the Result object (this is the key fix for
  13515. // Issue #2251)
  13516. auto backend_error = res.ssl_backend_error();
  13517. EXPECT_NE(0u, backend_error);
  13518. }
  13519. // Tests cert/key mismatch detection at the TLS context level
  13520. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13521. // Test that using mismatched cert/key causes connection failure.
  13522. // We verify this at the SSLClient level rather than through internal
  13523. // TLS API functions.
  13524. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13525. cli.enable_server_certificate_verification(false);
  13526. cli.set_connection_timeout(2);
  13527. // The mismatch should cause a connection or handshake error
  13528. auto res = cli.Get("/test");
  13529. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13530. // Either way, the request should fail
  13531. EXPECT_FALSE(res);
  13532. }
  13533. #endif
  13534. #if 0
  13535. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13536. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13537. ASSERT_TRUE(cli != nullptr);
  13538. cli->set_address_family(AF_INET6);
  13539. cli->set_interface("en0");
  13540. auto res = cli->Get("/get");
  13541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13542. ASSERT_EQ(StatusCode::OK_200, res->status);
  13543. }
  13544. #endif
  13545. // Client certificate tests - work with all TLS backends
  13546. #ifdef CPPHTTPLIB_SSL_ENABLED
  13547. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13548. void ClientCertPresent(
  13549. const std::string &client_cert_file,
  13550. const std::string &client_private_key_file,
  13551. const std::string &client_encrypted_private_key_pass = std::string(),
  13552. const ClientCertServerSetup &setup = nullptr) {
  13553. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13554. CLIENT_CA_CERT_DIR);
  13555. ASSERT_TRUE(svr.is_valid());
  13556. if (setup) { setup(svr); }
  13557. svr.Get("/test", [&](const Request &req, Response &res) {
  13558. res.set_content("test", "text/plain");
  13559. auto cert = req.peer_cert();
  13560. ASSERT_TRUE(static_cast<bool>(cert));
  13561. std::string common_name = cert.subject_cn();
  13562. EXPECT_EQ("Common Name", common_name);
  13563. });
  13564. auto port = svr.bind_to_any_port(HOST);
  13565. ASSERT_LT(0, port);
  13566. thread t = thread([&]() { svr.listen_after_bind(); });
  13567. auto se = detail::scope_exit([&] {
  13568. svr.stop();
  13569. t.join();
  13570. ASSERT_FALSE(svr.is_running());
  13571. });
  13572. svr.wait_until_ready();
  13573. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13574. client_encrypted_private_key_pass);
  13575. cli.enable_server_certificate_verification(false);
  13576. cli.set_connection_timeout(30);
  13577. auto res = cli.Get("/test");
  13578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13579. ASSERT_EQ(StatusCode::OK_200, res->status);
  13580. }
  13581. TEST(SSLClientServerTest, ClientCertPresent) {
  13582. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13583. }
  13584. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13585. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13586. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13587. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13588. }
  13589. // Expects svr, which must require client certificates, to reject a client
  13590. // that has none
  13591. void RejectsClientWithoutCert(SSLServer &svr) {
  13592. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13593. auto port = svr.bind_to_any_port(HOST);
  13594. ASSERT_LT(0, port);
  13595. thread t = thread([&]() { svr.listen_after_bind(); });
  13596. auto se = detail::scope_exit([&] {
  13597. svr.stop();
  13598. t.join();
  13599. ASSERT_FALSE(svr.is_running());
  13600. });
  13601. svr.wait_until_ready();
  13602. SSLClient cli(HOST, port);
  13603. cli.set_connection_timeout(30);
  13604. // Skip the server certificate check, so that the request fails because the
  13605. // client certificate is missing rather than because cert.pem is not trusted
  13606. cli.enable_server_certificate_verification(false);
  13607. auto res = cli.Get("/test");
  13608. ASSERT_FALSE(res);
  13609. // The server rejects the client during the handshake, or on TLS 1.3 right
  13610. // after it, which the client notices on its first write or read
  13611. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13612. res.error() == Error::Write || res.error() == Error::Read)
  13613. << to_string(res.error());
  13614. if (res.error() == Error::SSLConnection) {
  13615. EXPECT_NE(0UL, res.ssl_backend_error());
  13616. }
  13617. // A rejection noticed on the write keeps the TLS error the write hit
  13618. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13619. }
  13620. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13622. CLIENT_CA_CERT_DIR);
  13623. ASSERT_TRUE(svr.is_valid());
  13624. if (setup) { setup(svr); }
  13625. RejectsClientWithoutCert(svr);
  13626. }
  13627. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13628. // A server that requires client certificates must keep requiring them after a
  13629. // verify callback is set on its context, or set and then cleared again.
  13630. void ClientCertStillRequired(bool clear_callback) {
  13631. auto setup = [clear_callback](SSLServer &svr) {
  13632. ASSERT_TRUE(tls::set_verify_callback(
  13633. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13634. if (clear_callback) {
  13635. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13636. }
  13637. };
  13638. ClientCertMissing(setup);
  13639. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13640. setup);
  13641. }
  13642. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13643. ClientCertStillRequired(false);
  13644. }
  13645. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13646. ClientCertStillRequired(true);
  13647. }
  13648. // Replacing the certificates must not stop the server requiring client ones
  13649. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13650. ClientCertMissing([](SSLServer &svr) {
  13651. std::string cert_pem, key_pem, ca_pem;
  13652. read_file(SERVER_CERT_FILE, cert_pem);
  13653. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13654. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13655. ASSERT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  13656. ca_pem.c_str()));
  13657. });
  13658. }
  13659. // A TLS error from one request must not show up in a later request's Result
  13660. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13661. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13662. ASSERT_TRUE(svr.is_valid());
  13663. svr.Get("/test", [](const Request &, Response &res) {
  13664. res.set_content("test", "text/plain");
  13665. });
  13666. auto port = svr.bind_to_any_port(HOST);
  13667. ASSERT_LT(0, port);
  13668. thread t = thread([&]() { svr.listen_after_bind(); });
  13669. auto se = detail::scope_exit([&] {
  13670. svr.stop();
  13671. t.join();
  13672. ASSERT_FALSE(svr.is_running());
  13673. });
  13674. svr.wait_until_ready();
  13675. SSLClient cli(HOST, port);
  13676. cli.set_connection_timeout(30);
  13677. cli.enable_server_hostname_verification(false);
  13678. // cert.pem is not trusted, so the handshake fails
  13679. ASSERT_FALSE(cli.Get("/test"));
  13680. cli.enable_server_certificate_verification(false);
  13681. auto res = cli.Get("/test");
  13682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13683. EXPECT_EQ(0, res.ssl_error());
  13684. EXPECT_EQ(0UL, res.ssl_backend_error());
  13685. }
  13686. // PEM memory-based constructor tests (works with all TLS backends)
  13687. void PemMemoryClientCertPresent(
  13688. const std::string &client_cert_file,
  13689. const std::string &client_private_key_file,
  13690. const std::string &client_encrypted_private_key_pass = std::string()) {
  13691. // Read PEM files into memory
  13692. std::string server_cert_pem, server_key_pem;
  13693. std::string client_ca_pem;
  13694. std::string client_cert_pem, client_key_pem;
  13695. read_file(SERVER_CERT_FILE, server_cert_pem);
  13696. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13697. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13698. read_file(client_cert_file, client_cert_pem);
  13699. read_file(client_private_key_file, client_key_pem);
  13700. // Create server with PEM memory
  13701. SSLServer::PemMemory server_pem = {
  13702. server_cert_pem.c_str(),
  13703. server_cert_pem.size(),
  13704. server_key_pem.c_str(),
  13705. server_key_pem.size(),
  13706. client_ca_pem.c_str(),
  13707. client_ca_pem.size(),
  13708. nullptr // no password for server key
  13709. };
  13710. SSLServer svr(server_pem);
  13711. ASSERT_TRUE(svr.is_valid());
  13712. svr.Get("/test", [&](const Request &, Response &res) {
  13713. res.set_content("test", "text/plain");
  13714. });
  13715. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13716. auto se = detail::scope_exit([&] {
  13717. svr.stop();
  13718. t.join();
  13719. ASSERT_FALSE(svr.is_running());
  13720. });
  13721. svr.wait_until_ready();
  13722. // Create client with PEM memory
  13723. const char *password = client_encrypted_private_key_pass.empty()
  13724. ? nullptr
  13725. : client_encrypted_private_key_pass.c_str();
  13726. SSLClient::PemMemory client_pem = {
  13727. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13728. client_key_pem.size(), password};
  13729. SSLClient cli(HOST, PORT, client_pem);
  13730. cli.enable_server_certificate_verification(false);
  13731. cli.set_connection_timeout(30);
  13732. auto res = cli.Get("/test");
  13733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13734. ASSERT_EQ(StatusCode::OK_200, res->status);
  13735. }
  13736. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13737. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13738. }
  13739. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13740. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13741. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13742. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13743. }
  13744. // A server built from PEM memory with a client CA requires client certificates
  13745. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13746. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13747. read_file(SERVER_CERT_FILE, server_cert_pem);
  13748. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13749. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13750. SSLServer::PemMemory server_pem = {
  13751. server_cert_pem.c_str(),
  13752. server_cert_pem.size(),
  13753. server_key_pem.c_str(),
  13754. server_key_pem.size(),
  13755. client_ca_pem.c_str(),
  13756. client_ca_pem.size(),
  13757. nullptr // no password for server key
  13758. };
  13759. SSLServer svr(server_pem);
  13760. ASSERT_TRUE(svr.is_valid());
  13761. RejectsClientWithoutCert(svr);
  13762. }
  13763. TEST(SSLClientServerTest, TrustDirOptional) {
  13764. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13765. ASSERT_TRUE(svr.is_valid());
  13766. svr.Get("/test", [&](const Request &, Response &res) {
  13767. res.set_content("test", "text/plain");
  13768. });
  13769. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13770. auto se = detail::scope_exit([&] {
  13771. svr.stop();
  13772. t.join();
  13773. ASSERT_FALSE(svr.is_running());
  13774. });
  13775. svr.wait_until_ready();
  13776. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13777. cli.enable_server_certificate_verification(false);
  13778. cli.set_connection_timeout(30);
  13779. auto res = cli.Get("/test");
  13780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13781. ASSERT_EQ(StatusCode::OK_200, res->status);
  13782. }
  13783. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13784. class NoListenSSLServer : public SSLServer {
  13785. public:
  13786. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13787. const char *client_ca_cert_file_path,
  13788. const char *client_ca_cert_dir_path = nullptr)
  13789. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13790. client_ca_cert_dir_path),
  13791. stop_(false) {}
  13792. std::atomic_bool stop_;
  13793. private:
  13794. bool process_and_close_socket(socket_t /*sock*/) override {
  13795. // Don't create SSL context
  13796. while (!stop_.load()) {
  13797. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13798. }
  13799. return true;
  13800. }
  13801. };
  13802. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13803. CLIENT_CA_CERT_FILE);
  13804. ASSERT_TRUE(svr.is_valid());
  13805. svr.Get("/test", [&](const Request &, Response &res) {
  13806. res.set_content("test", "text/plain");
  13807. });
  13808. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13809. auto se = detail::scope_exit([&] {
  13810. svr.stop_ = true;
  13811. svr.stop();
  13812. t.join();
  13813. ASSERT_FALSE(svr.is_running());
  13814. });
  13815. svr.wait_until_ready();
  13816. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13817. cli.enable_server_certificate_verification(false);
  13818. cli.set_connection_timeout(1);
  13819. auto res = cli.Get("/test");
  13820. ASSERT_TRUE(!res);
  13821. EXPECT_EQ(Error::SSLConnection, res.error());
  13822. // Timeout results in WantRead error code (maps to backend-specific value)
  13823. EXPECT_NE(0, res.ssl_error());
  13824. }
  13825. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13826. // Test SSLServer with client certificate verification using the standard
  13827. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13828. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13829. CLIENT_CA_CERT_DIR);
  13830. ASSERT_TRUE(svr.is_valid());
  13831. svr.Get("/test", [&](const Request &req, Response &res) {
  13832. res.set_content("test", "text/plain");
  13833. auto cert = req.peer_cert();
  13834. ASSERT_TRUE(static_cast<bool>(cert));
  13835. auto common_name = cert.subject_cn();
  13836. EXPECT_EQ("Common Name", common_name);
  13837. });
  13838. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13839. auto se = detail::scope_exit([&] {
  13840. svr.stop();
  13841. t.join();
  13842. ASSERT_FALSE(svr.is_running());
  13843. });
  13844. svr.wait_until_ready();
  13845. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13846. cli.enable_server_certificate_verification(false);
  13847. cli.set_connection_timeout(30);
  13848. auto res = cli.Get("/test");
  13849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13850. ASSERT_EQ(StatusCode::OK_200, res->status);
  13851. }
  13852. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13853. // Verifies that wildcard matching and exact matching work consistently
  13854. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13855. using namespace httplib::tls;
  13856. // We need a running server to test against
  13857. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13858. ASSERT_TRUE(svr.is_valid());
  13859. svr.Get("/test", [](const Request &, Response &res) {
  13860. res.set_content("ok", "text/plain");
  13861. });
  13862. thread t([&]() { svr.listen(HOST, PORT); });
  13863. auto se = detail::scope_exit([&] {
  13864. svr.stop();
  13865. t.join();
  13866. });
  13867. svr.wait_until_ready();
  13868. bool verify_callback_called = false;
  13869. bool verify_result_wrong = false;
  13870. SSLClient cli(HOST, PORT);
  13871. cli.enable_server_certificate_verification(true);
  13872. cli.set_ca_cert_path(CA_CERT_FILE);
  13873. cli.set_connection_timeout(5);
  13874. // Note: Test certificate has CN="Common Name", not "localhost"
  13875. bool verify_result_cn = false;
  13876. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13877. verify_callback_called = true;
  13878. if (!ctx.cert) return false;
  13879. // Test 1: "Common Name" should match (our test server cert CN)
  13880. verify_result_cn = ctx.check_hostname("Common Name");
  13881. // Test 2: wrong hostname should not match
  13882. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13883. return true; // Accept for the purpose of this test
  13884. });
  13885. auto res = cli.Get("/test");
  13886. // The request may succeed or fail depending on cert configuration
  13887. // but the callback should have been called
  13888. ASSERT_TRUE(verify_callback_called)
  13889. << "Verify callback should have been called";
  13890. // CN="Common Name" should match our test certificate
  13891. //
  13892. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13893. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13894. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13895. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13896. // <openssl/base.h>, which is included transitively when
  13897. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13898. #if defined(OPENSSL_IS_BORINGSSL)
  13899. EXPECT_FALSE(verify_result_cn)
  13900. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13901. #else
  13902. EXPECT_TRUE(verify_result_cn)
  13903. << "verify_hostname should match 'Common Name' (certificate CN)";
  13904. #endif
  13905. // Wrong hostname should not match
  13906. EXPECT_FALSE(verify_result_wrong)
  13907. << "verify_hostname should not match 'wronghost.example.com'";
  13908. }
  13909. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13910. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13911. // X509_check_ip behavior and must hold for every backend.
  13912. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13913. using namespace httplib::tls;
  13914. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13915. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13916. ASSERT_TRUE(svr.is_valid());
  13917. svr.Get("/test", [](const Request &, Response &res) {
  13918. res.set_content("ok", "text/plain");
  13919. });
  13920. thread t([&]() { svr.listen(HOST, PORT); });
  13921. auto se = detail::scope_exit([&] {
  13922. svr.stop();
  13923. t.join();
  13924. });
  13925. svr.wait_until_ready();
  13926. bool verify_callback_called = false;
  13927. bool ip_matched_via_cn = true;
  13928. SSLClient cli(HOST, PORT);
  13929. cli.enable_server_certificate_verification(true);
  13930. cli.set_ca_cert_path(CA_CERT_FILE);
  13931. cli.set_connection_timeout(5);
  13932. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13933. verify_callback_called = true;
  13934. if (!ctx.cert) return false;
  13935. // The IP appears only in the CN, so it must NOT be accepted.
  13936. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13937. return true; // Accept for the purpose of this test
  13938. });
  13939. cli.Get("/test");
  13940. ASSERT_TRUE(verify_callback_called)
  13941. << "Verify callback should have been called";
  13942. EXPECT_FALSE(ip_matched_via_cn)
  13943. << "An IP host must not be authenticated via the certificate CN";
  13944. }
  13945. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13946. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13947. using namespace httplib::tls;
  13948. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13949. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13950. ASSERT_TRUE(svr.is_valid());
  13951. svr.Get("/test", [](const Request &, Response &res) {
  13952. res.set_content("ok", "text/plain");
  13953. });
  13954. thread t([&]() { svr.listen(HOST, PORT); });
  13955. auto se = detail::scope_exit([&] {
  13956. svr.stop();
  13957. t.join();
  13958. });
  13959. svr.wait_until_ready();
  13960. bool verify_callback_called = false;
  13961. bool san_matched = false;
  13962. bool wrong_ipv6_matched = true;
  13963. bool cn_ipv6_matched = true;
  13964. SSLClient cli(HOST, PORT);
  13965. cli.enable_server_certificate_verification(true);
  13966. cli.set_ca_cert_path(CA_CERT_FILE);
  13967. cli.set_connection_timeout(5);
  13968. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13969. verify_callback_called = true;
  13970. if (!ctx.cert) return false;
  13971. // Matches the IPv6 iPAddress SAN.
  13972. san_matched = ctx.check_hostname("2001:db8::1");
  13973. // A different IPv6 address must not match.
  13974. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13975. // "::1" lives only in the CN, so it must not be accepted.
  13976. cn_ipv6_matched = ctx.check_hostname("::1");
  13977. return true; // Accept for the purpose of this test
  13978. });
  13979. cli.Get("/test");
  13980. ASSERT_TRUE(verify_callback_called)
  13981. << "Verify callback should have been called";
  13982. EXPECT_TRUE(san_matched)
  13983. << "verify_hostname should match an IPv6 iPAddress SAN";
  13984. EXPECT_FALSE(wrong_ipv6_matched)
  13985. << "verify_hostname should not match a non-matching IPv6 address";
  13986. EXPECT_FALSE(cn_ipv6_matched)
  13987. << "An IPv6 host must not be authenticated via the certificate CN";
  13988. }
  13989. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13990. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13991. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13992. using namespace httplib::tls;
  13993. // SANs: DNS:a.zz, IP:42.46.122.122
  13994. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13995. ASSERT_TRUE(svr.is_valid());
  13996. svr.Get("/test", [](const Request &, Response &res) {
  13997. res.set_content("ok", "text/plain");
  13998. });
  13999. auto port = svr.bind_to_any_port(HOST);
  14000. thread t([&]() { svr.listen_after_bind(); });
  14001. auto se = detail::scope_exit([&] {
  14002. svr.stop();
  14003. t.join();
  14004. });
  14005. svr.wait_until_ready();
  14006. bool verify_callback_called = false;
  14007. bool dns_san_matched = false;
  14008. bool ip_san_matched = false;
  14009. bool ip_matched_via_dns_san = true;
  14010. bool dns_matched_via_ip_san = true;
  14011. bool cn_matched_next_to_dns_san = true;
  14012. SSLClient cli(HOST, port);
  14013. cli.enable_server_certificate_verification(true);
  14014. cli.set_ca_cert_path(CA_CERT_FILE);
  14015. cli.set_connection_timeout(5);
  14016. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14017. verify_callback_called = true;
  14018. if (!ctx.cert) return false;
  14019. dns_san_matched = ctx.check_hostname("a.zz");
  14020. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14021. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14022. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14023. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14024. return true; // Accept for the purpose of this test
  14025. });
  14026. cli.Get("/test");
  14027. ASSERT_TRUE(verify_callback_called)
  14028. << "Verify callback should have been called";
  14029. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14030. EXPECT_TRUE(ip_san_matched)
  14031. << "verify_hostname should match an iPAddress SAN";
  14032. EXPECT_FALSE(ip_matched_via_dns_san)
  14033. << "An IP host must not be authenticated via a dNSName SAN";
  14034. EXPECT_FALSE(dns_matched_via_ip_san)
  14035. << "A DNS host must not be authenticated via an iPAddress SAN";
  14036. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14037. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14038. }
  14039. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14040. // "www.*.example.test" names one host and not every host under example.test.
  14041. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14042. using namespace httplib::tls;
  14043. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14044. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14045. ASSERT_TRUE(svr.is_valid());
  14046. svr.Get("/test", [](const Request &, Response &res) {
  14047. res.set_content("ok", "text/plain");
  14048. });
  14049. auto port = svr.bind_to_any_port(HOST);
  14050. thread t([&]() { svr.listen_after_bind(); });
  14051. auto se = detail::scope_exit([&] {
  14052. svr.stop();
  14053. t.join();
  14054. });
  14055. svr.wait_until_ready();
  14056. bool verify_callback_called = false;
  14057. bool leftmost_wildcard_matched = false;
  14058. bool wildcard_spanned_labels = true;
  14059. bool inner_wildcard_matched = true;
  14060. SSLClient cli(HOST, port);
  14061. cli.enable_server_certificate_verification(true);
  14062. cli.set_ca_cert_path(CA_CERT_FILE);
  14063. cli.set_connection_timeout(5);
  14064. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14065. verify_callback_called = true;
  14066. if (!ctx.cert) return false;
  14067. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14068. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14069. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14070. return true; // Accept for the purpose of this test
  14071. });
  14072. cli.Get("/test");
  14073. ASSERT_TRUE(verify_callback_called)
  14074. << "Verify callback should have been called";
  14075. EXPECT_TRUE(leftmost_wildcard_matched)
  14076. << "A leftmost wildcard should match a single label";
  14077. EXPECT_FALSE(wildcard_spanned_labels)
  14078. << "A wildcard label must not match more than one label";
  14079. EXPECT_FALSE(inner_wildcard_matched)
  14080. << "A wildcard outside the leftmost label must not be honoured";
  14081. }
  14082. // sans() must report each SAN entry under its own type.
  14083. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14084. using namespace httplib::tls;
  14085. // SANs: DNS:a.zz, IP:42.46.122.122
  14086. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14087. ASSERT_TRUE(svr.is_valid());
  14088. svr.Get("/test", [](const Request &, Response &res) {
  14089. res.set_content("ok", "text/plain");
  14090. });
  14091. auto port = svr.bind_to_any_port(HOST);
  14092. thread t([&]() { svr.listen_after_bind(); });
  14093. auto se = detail::scope_exit([&] {
  14094. svr.stop();
  14095. t.join();
  14096. });
  14097. svr.wait_until_ready();
  14098. bool verify_callback_called = false;
  14099. std::vector<SanEntry> sans;
  14100. SSLClient cli(HOST, port);
  14101. cli.enable_server_certificate_verification(true);
  14102. cli.set_ca_cert_path(CA_CERT_FILE);
  14103. cli.set_connection_timeout(5);
  14104. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14105. verify_callback_called = true;
  14106. if (!ctx.cert) return false;
  14107. sans = ctx.sans();
  14108. return true; // Accept for the purpose of this test
  14109. });
  14110. cli.Get("/test");
  14111. ASSERT_TRUE(verify_callback_called)
  14112. << "Verify callback should have been called";
  14113. auto has_san = [&](SanType type, const std::string &value) {
  14114. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14115. return san.type == type && san.value == value;
  14116. });
  14117. };
  14118. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14119. << "sans() should report the dNSName SAN";
  14120. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14121. << "sans() should report the iPAddress SAN";
  14122. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14123. << "sans() must not report the dNSName SAN as an address";
  14124. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14125. << "sans() must not report the iPAddress SAN as a DNS name";
  14126. }
  14127. #endif
  14128. // mbedTLS-specific callback constructor test
  14129. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14130. #ifdef CPPHTTPLIB_SSL_ENABLED
  14131. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14132. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14133. ASSERT_TRUE(svr.is_valid());
  14134. // Set up a handler to verify client certificate is present
  14135. bool client_cert_verified = false;
  14136. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14137. // Verify that client certificate was provided
  14138. client_cert_verified = true;
  14139. res.set_content("success", "text/plain");
  14140. });
  14141. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14142. auto se = detail::scope_exit([&] {
  14143. svr.stop();
  14144. t.join();
  14145. ASSERT_FALSE(svr.is_running());
  14146. });
  14147. svr.wait_until_ready();
  14148. // Client with certificate
  14149. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14150. cli.enable_server_certificate_verification(false);
  14151. cli.set_connection_timeout(30);
  14152. auto res = cli.Get("/test");
  14153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14154. ASSERT_EQ(StatusCode::OK_200, res->status);
  14155. ASSERT_TRUE(client_cert_verified);
  14156. EXPECT_EQ("success", res->body);
  14157. }
  14158. #endif
  14159. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14160. // backends
  14161. #ifdef CPPHTTPLIB_SSL_ENABLED
  14162. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14163. using namespace httplib::tls;
  14164. // Test that when client CA cert file is provided,
  14165. // the server properly requests and validates client certificates
  14166. // Create a server with client authentication
  14167. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14168. ASSERT_TRUE(svr.is_valid());
  14169. bool handler_called = false;
  14170. svr.Get("/test", [&](const Request &req, Response &res) {
  14171. handler_called = true;
  14172. // Verify that a client certificate was provided
  14173. auto cert = req.peer_cert();
  14174. ASSERT_TRUE(static_cast<bool>(cert));
  14175. // Get the issuer name
  14176. std::string issuer_str = cert.issuer_name();
  14177. ASSERT_FALSE(issuer_str.empty());
  14178. // The client certificate should be issued by our test CA
  14179. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14180. res.set_content("authenticated", "text/plain");
  14181. });
  14182. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14183. auto se = detail::scope_exit([&] {
  14184. svr.stop();
  14185. t.join();
  14186. ASSERT_FALSE(svr.is_running());
  14187. });
  14188. svr.wait_until_ready();
  14189. // Connect with a client certificate issued by the CA
  14190. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14191. cli.enable_server_certificate_verification(false);
  14192. cli.set_connection_timeout(30);
  14193. auto res = cli.Get("/test");
  14194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14195. ASSERT_EQ(StatusCode::OK_200, res->status);
  14196. ASSERT_TRUE(handler_called);
  14197. EXPECT_EQ("authenticated", res->body);
  14198. }
  14199. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14200. using namespace httplib::tls;
  14201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14202. ASSERT_TRUE(svr.is_valid());
  14203. svr.Get("/test", [](const Request &, Response &res) {
  14204. res.set_content("ok", "text/plain");
  14205. });
  14206. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14207. auto se = detail::scope_exit([&] {
  14208. svr.stop();
  14209. t.join();
  14210. });
  14211. svr.wait_until_ready();
  14212. SSLClient cli(HOST, PORT);
  14213. cli.enable_server_certificate_verification(false);
  14214. cli.set_connection_timeout(30);
  14215. bool cert_checked = false;
  14216. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14217. if (ctx.cert) {
  14218. auto sans = ctx.sans();
  14219. // Test certificate may or may not have SANs - just verify the API
  14220. // works If SANs exist, verify the types are valid
  14221. for (const auto &san : sans) {
  14222. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14223. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14224. san.type == SanType::OTHER);
  14225. EXPECT_FALSE(san.value.empty());
  14226. }
  14227. cert_checked = true;
  14228. }
  14229. return true;
  14230. });
  14231. auto res = cli.Get("/test");
  14232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14233. EXPECT_TRUE(cert_checked);
  14234. }
  14235. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14236. using namespace httplib::tls;
  14237. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14238. ASSERT_TRUE(svr.is_valid());
  14239. svr.Get("/test", [](const Request &, Response &res) {
  14240. res.set_content("ok", "text/plain");
  14241. });
  14242. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14243. auto se = detail::scope_exit([&] {
  14244. svr.stop();
  14245. t.join();
  14246. });
  14247. svr.wait_until_ready();
  14248. SSLClient cli(HOST, PORT);
  14249. cli.enable_server_certificate_verification(false);
  14250. cli.set_connection_timeout(30);
  14251. bool validity_checked = false;
  14252. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14253. if (ctx.cert) {
  14254. time_t not_before = 0, not_after = 0;
  14255. bool result = ctx.validity(not_before, not_after);
  14256. EXPECT_TRUE(result);
  14257. // Verify that not_before < now < not_after for a valid cert
  14258. time_t now = time(nullptr);
  14259. EXPECT_LT(not_before, now);
  14260. EXPECT_GT(not_after, now);
  14261. validity_checked = true;
  14262. }
  14263. return true;
  14264. });
  14265. auto res = cli.Get("/test");
  14266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14267. EXPECT_TRUE(validity_checked);
  14268. }
  14269. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14270. using namespace httplib::tls;
  14271. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14272. ASSERT_TRUE(svr.is_valid());
  14273. svr.Get("/test", [](const Request &, Response &res) {
  14274. res.set_content("ok", "text/plain");
  14275. });
  14276. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14277. auto se = detail::scope_exit([&] {
  14278. svr.stop();
  14279. t.join();
  14280. });
  14281. svr.wait_until_ready();
  14282. SSLClient cli(HOST, PORT);
  14283. cli.enable_server_certificate_verification(false);
  14284. cli.set_connection_timeout(30);
  14285. bool serial_checked = false;
  14286. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14287. if (ctx.cert) {
  14288. std::string serial = ctx.serial();
  14289. EXPECT_FALSE(serial.empty());
  14290. // Serial should be a hex string
  14291. for (char c : serial) {
  14292. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14293. (c >= 'a' && c <= 'f'));
  14294. }
  14295. serial_checked = true;
  14296. }
  14297. return true;
  14298. });
  14299. auto res = cli.Get("/test");
  14300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14301. EXPECT_TRUE(serial_checked);
  14302. }
  14303. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14304. // Test 1: Valid CA file - no error should be recorded
  14305. {
  14306. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14307. CLIENT_CA_CERT_FILE);
  14308. ASSERT_TRUE(svr.is_valid());
  14309. // With valid setup, last_ssl_error should be 0
  14310. EXPECT_EQ(0, svr.ssl_last_error());
  14311. }
  14312. // Test 2: Invalid CA file content
  14313. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14314. {
  14315. // Create a temporary file with completely invalid content
  14316. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14317. {
  14318. std::ofstream ofs(temp_invalid_ca);
  14319. ofs << "This is not a certificate file at all\n";
  14320. ofs << "Just plain text content\n";
  14321. }
  14322. // Create server with invalid CA file
  14323. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14324. // Clean up temporary file
  14325. std::remove(temp_invalid_ca);
  14326. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14327. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14328. // Note: SSL_CTX_load_verify_locations typically fails first,
  14329. // but our error handling code path is still exercised
  14330. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14331. }
  14332. }
  14333. TEST(VerifyCallbackTest, VerifyContextFields) {
  14334. using namespace httplib::tls;
  14335. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14336. ASSERT_TRUE(svr.is_valid());
  14337. svr.Get("/test", [](const Request &, Response &res) {
  14338. res.set_content("ok", "text/plain");
  14339. });
  14340. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14341. auto se = detail::scope_exit([&] {
  14342. svr.stop();
  14343. t.join();
  14344. });
  14345. svr.wait_until_ready();
  14346. SSLClient cli(HOST, PORT);
  14347. cli.enable_server_certificate_verification(false);
  14348. cli.set_connection_timeout(30);
  14349. int callback_count = 0;
  14350. bool saw_leaf_cert = false;
  14351. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14352. if (ctx.cert) {
  14353. callback_count++;
  14354. // We should see at least one certificate (the leaf)
  14355. std::string cn = ctx.subject_cn();
  14356. if (!cn.empty()) { saw_leaf_cert = true; }
  14357. // Verify context fields are populated
  14358. EXPECT_NE(ctx.session, nullptr);
  14359. EXPECT_GE(ctx.depth, 0);
  14360. }
  14361. return true;
  14362. });
  14363. auto res = cli.Get("/test");
  14364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14365. EXPECT_GT(callback_count, 0);
  14366. EXPECT_TRUE(saw_leaf_cert);
  14367. }
  14368. // A verifier belongs to the client that set it, not to the thread that set it.
  14369. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14370. using namespace httplib::tls;
  14371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14372. ASSERT_TRUE(svr.is_valid());
  14373. svr.Get("/test", [](const Request &, Response &res) {
  14374. res.set_content("ok", "text/plain");
  14375. });
  14376. auto port = svr.bind_to_any_port(HOST);
  14377. thread t([&]() { svr.listen_after_bind(); });
  14378. auto se = detail::scope_exit([&] {
  14379. svr.stop();
  14380. t.join();
  14381. });
  14382. svr.wait_until_ready();
  14383. auto rejecting_calls = 0;
  14384. SSLClient rejecting(HOST, port);
  14385. rejecting.enable_server_certificate_verification(false);
  14386. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14387. rejecting_calls++;
  14388. return false;
  14389. });
  14390. auto accepting_calls = 0;
  14391. SSLClient accepting(HOST, port);
  14392. accepting.enable_server_certificate_verification(false);
  14393. // Set on another thread than the requests below.
  14394. thread([&]() {
  14395. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14396. accepting_calls++;
  14397. return true;
  14398. });
  14399. }).join();
  14400. // Requested on another thread than the verifier was set on.
  14401. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14402. EXPECT_GT(rejecting_calls, 0);
  14403. auto res = accepting.Get("/test");
  14404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14405. EXPECT_GT(accepting_calls, 0);
  14406. }
  14407. // A verifier replaced while a handshake runs it lives until it returns.
  14408. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14409. using namespace httplib::tls;
  14410. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14411. ASSERT_TRUE(svr.is_valid());
  14412. svr.Get("/test", [](const Request &, Response &res) {
  14413. res.set_content("ok", "text/plain");
  14414. });
  14415. auto port = svr.bind_to_any_port(HOST);
  14416. thread t([&]() { svr.listen_after_bind(); });
  14417. auto se = detail::scope_exit([&] {
  14418. svr.stop();
  14419. t.join();
  14420. });
  14421. svr.wait_until_ready();
  14422. SSLClient cli(HOST, port);
  14423. cli.enable_server_certificate_verification(false);
  14424. std::promise<void> entered;
  14425. std::promise<void> replaced;
  14426. auto replaced_future = replaced.get_future();
  14427. auto first_call = true;
  14428. // Long enough to live on the heap
  14429. std::string expected(64, 'v');
  14430. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14431. if (first_call) {
  14432. first_call = false;
  14433. entered.set_value();
  14434. replaced_future.wait();
  14435. }
  14436. return expected == std::string(64, 'v');
  14437. });
  14438. thread request([&]() {
  14439. auto res = cli.Get("/test");
  14440. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14441. });
  14442. entered.get_future().wait();
  14443. cli.set_server_certificate_verifier(
  14444. [](const VerifyContext &) { return true; });
  14445. replaced.set_value();
  14446. request.join();
  14447. }
  14448. // VerifyContext::session is the same handle the other tls:: functions take.
  14449. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14450. using namespace httplib::tls;
  14451. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14452. ASSERT_TRUE(svr.is_valid());
  14453. svr.Get("/test", [](const Request &, Response &res) {
  14454. res.set_content("ok", "text/plain");
  14455. });
  14456. auto port = svr.bind_to_any_port(HOST);
  14457. thread t([&]() { svr.listen_after_bind(); });
  14458. auto se = detail::scope_exit([&] {
  14459. svr.stop();
  14460. t.join();
  14461. });
  14462. svr.wait_until_ready();
  14463. SSLClient cli(HOST, port);
  14464. cli.enable_server_certificate_verification(false);
  14465. session_t verifier_session = nullptr;
  14466. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14467. verifier_session = ctx.session;
  14468. return true;
  14469. });
  14470. session_t session_verifier_session = nullptr;
  14471. cli.set_session_verifier([&](session_t session) {
  14472. session_verifier_session = session;
  14473. return SSLVerifierResponse::NoDecisionMade;
  14474. });
  14475. auto res = cli.Get("/test");
  14476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14477. EXPECT_NE(nullptr, verifier_session);
  14478. EXPECT_EQ(session_verifier_session, verifier_session);
  14479. }
  14480. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14481. using httplib::tls::TlsError;
  14482. // Test that verify_error_to_string returns empty for success
  14483. std::string success_str = TlsError::verify_error_to_string(0);
  14484. EXPECT_TRUE(success_str.empty());
  14485. // Test that verify_error_to_string returns non-empty for error codes
  14486. // Using a common error code (certificate expired)
  14487. std::string error_str =
  14488. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14489. EXPECT_FALSE(error_str.empty());
  14490. }
  14491. TEST(SessionVerifierTest, CertificateAccepted) {
  14492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14493. ASSERT_TRUE(svr.is_valid());
  14494. svr.Get("/test", [](const Request &, Response &res) {
  14495. res.set_content("ok", "text/plain");
  14496. });
  14497. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14498. auto se = detail::scope_exit([&] {
  14499. svr.stop();
  14500. t.join();
  14501. });
  14502. svr.wait_until_ready();
  14503. SSLClient cli(HOST, PORT);
  14504. cli.enable_server_certificate_verification(false);
  14505. cli.set_connection_timeout(30);
  14506. bool callback_called = false;
  14507. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14508. EXPECT_NE(session, nullptr);
  14509. callback_called = true;
  14510. return SSLVerifierResponse::CertificateAccepted;
  14511. });
  14512. auto res = cli.Get("/test");
  14513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14514. EXPECT_EQ(200, res->status);
  14515. EXPECT_TRUE(callback_called);
  14516. }
  14517. TEST(SessionVerifierTest, CertificateRejected) {
  14518. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14519. ASSERT_TRUE(svr.is_valid());
  14520. svr.Get("/test", [](const Request &, Response &res) {
  14521. res.set_content("ok", "text/plain");
  14522. });
  14523. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14524. auto se = detail::scope_exit([&] {
  14525. svr.stop();
  14526. t.join();
  14527. });
  14528. svr.wait_until_ready();
  14529. SSLClient cli(HOST, PORT);
  14530. cli.enable_server_certificate_verification(false);
  14531. cli.set_connection_timeout(30);
  14532. bool callback_called = false;
  14533. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14534. EXPECT_NE(session, nullptr);
  14535. callback_called = true;
  14536. return SSLVerifierResponse::CertificateRejected;
  14537. });
  14538. auto res = cli.Get("/test");
  14539. EXPECT_FALSE(res);
  14540. EXPECT_TRUE(callback_called);
  14541. }
  14542. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14543. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14544. ASSERT_TRUE(svr.is_valid());
  14545. svr.Get("/test", [](const Request &, Response &res) {
  14546. res.set_content("ok", "text/plain");
  14547. });
  14548. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14549. auto se = detail::scope_exit([&] {
  14550. svr.stop();
  14551. t.join();
  14552. });
  14553. svr.wait_until_ready();
  14554. // NoDecisionMade with verification disabled should succeed (no default check)
  14555. SSLClient cli(HOST, PORT);
  14556. cli.enable_server_certificate_verification(false);
  14557. cli.set_connection_timeout(30);
  14558. bool callback_called = false;
  14559. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14560. EXPECT_NE(session, nullptr);
  14561. callback_called = true;
  14562. return SSLVerifierResponse::NoDecisionMade;
  14563. });
  14564. auto res = cli.Get("/test");
  14565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14566. EXPECT_EQ(200, res->status);
  14567. EXPECT_TRUE(callback_called);
  14568. }
  14569. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14570. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14571. ASSERT_TRUE(svr.is_valid());
  14572. svr.Get("/test", [](const Request &, Response &res) {
  14573. res.set_content("ok", "text/plain");
  14574. });
  14575. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14576. auto se = detail::scope_exit([&] {
  14577. svr.stop();
  14578. t.join();
  14579. });
  14580. svr.wait_until_ready();
  14581. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14582. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14583. // so we only check that the request fails, not whether the callback was
  14584. // called.
  14585. SSLClient cli(HOST, PORT);
  14586. cli.enable_server_certificate_verification(true);
  14587. cli.set_connection_timeout(30);
  14588. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14589. EXPECT_NE(session, nullptr);
  14590. return SSLVerifierResponse::NoDecisionMade;
  14591. });
  14592. auto res = cli.Get("/test");
  14593. EXPECT_FALSE(res);
  14594. }
  14595. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14596. // Test SSL server using PemMemory constructor with client CA certificates
  14597. // Read PEM files
  14598. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14599. read_file(SERVER_CERT_FILE, server_cert_pem);
  14600. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14601. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14602. // Create SSLServer with PemMemory constructor including client CA
  14603. SSLServer::PemMemory server_pem = {
  14604. server_cert_pem.c_str(),
  14605. server_cert_pem.size(),
  14606. server_key_pem.c_str(),
  14607. server_key_pem.size(),
  14608. client_ca_pem.c_str(),
  14609. client_ca_pem.size(),
  14610. nullptr // no password for server key
  14611. };
  14612. SSLServer svr(server_pem);
  14613. ASSERT_TRUE(svr.is_valid());
  14614. // No SSL error should be recorded for valid setup
  14615. EXPECT_EQ(0, svr.ssl_last_error());
  14616. // Set up server endpoints
  14617. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14618. res.set_content("ok", "text/plain");
  14619. });
  14620. // Start server in a thread
  14621. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14622. svr.wait_until_ready();
  14623. // Connect with client certificate (using constructor with paths)
  14624. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14625. cli.enable_server_certificate_verification(false);
  14626. auto res = cli.Get("/test-pem-ca");
  14627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14628. EXPECT_EQ(200, res->status);
  14629. EXPECT_EQ("ok", res->body);
  14630. svr.stop();
  14631. server_thread.join();
  14632. }
  14633. #endif
  14634. #ifdef _WIN32
  14635. TEST(CleanupTest, WSACleanup) {
  14636. int ret = WSACleanup();
  14637. ASSERT_EQ(0, ret);
  14638. }
  14639. #endif
  14640. #ifndef CPPHTTPLIB_SSL_ENABLED
  14641. TEST(NoSSLSupport, SimpleInterface) {
  14642. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14643. }
  14644. #endif
  14645. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14646. TEST(InvalidScheme, SimpleInterface) {
  14647. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14648. }
  14649. #endif
  14650. TEST(NoScheme, SimpleInterface) {
  14651. Client cli("yahoo.com:80");
  14652. ASSERT_TRUE(cli.is_valid());
  14653. }
  14654. TEST(SendAPI, SimpleInterface_Online) {
  14655. Client cli("http://yahoo.com");
  14656. Request req;
  14657. req.method = "GET";
  14658. req.path = "/";
  14659. auto res = cli.send(req);
  14660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14661. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14662. }
  14663. TEST(SendAPI, WithParamsInRequest) {
  14664. Server svr;
  14665. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14666. EXPECT_TRUE(req.has_param("test"));
  14667. EXPECT_EQ("test_value", req.get_param_value("test"));
  14668. });
  14669. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14670. auto se = detail::scope_exit([&] {
  14671. svr.stop();
  14672. t.join();
  14673. ASSERT_FALSE(svr.is_running());
  14674. });
  14675. svr.wait_until_ready();
  14676. Client cli(HOST, PORT);
  14677. {
  14678. Request req;
  14679. req.method = "GET";
  14680. req.path = "/";
  14681. req.params.emplace("test", "test_value");
  14682. auto res = cli.send(req);
  14683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14684. }
  14685. {
  14686. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14688. }
  14689. }
  14690. TEST(ClientImplMethods, GetSocketTest) {
  14691. httplib::Server svr;
  14692. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14693. res.status = StatusCode::OK_200;
  14694. });
  14695. auto port = svr.bind_to_any_port("127.0.0.1");
  14696. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14697. auto se = detail::scope_exit([&] {
  14698. svr.stop();
  14699. thread.join();
  14700. ASSERT_FALSE(svr.is_running());
  14701. });
  14702. svr.wait_until_ready();
  14703. {
  14704. httplib::Client cli("127.0.0.1", port);
  14705. cli.set_keep_alive(true);
  14706. // Use the behavior of cpp-httplib of opening the connection
  14707. // only when the first request happens. If that changes,
  14708. // this test would be obsolete.
  14709. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14710. // This also implicitly tests the server. But other tests would fail much
  14711. // earlier than this one to be considered.
  14712. auto res = cli.Get("/");
  14713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14714. EXPECT_EQ(StatusCode::OK_200, res->status);
  14715. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14716. }
  14717. }
  14718. #ifdef CPPHTTPLIB_SSL_ENABLED
  14719. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14720. Client cli("http://yahoo.com");
  14721. auto res = cli.Get("/");
  14722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14723. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14724. cli.set_follow_location(true);
  14725. res = cli.Get("/");
  14726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14727. EXPECT_EQ(StatusCode::OK_200, res->status);
  14728. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14729. }
  14730. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14731. Client cli("https://yahoo.com");
  14732. auto res = cli.Get("/");
  14733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14734. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14735. cli.set_follow_location(true);
  14736. res = cli.Get("/");
  14737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14738. EXPECT_EQ(StatusCode::OK_200, res->status);
  14739. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14740. }
  14741. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14742. Client cli("https://yahoo.com");
  14743. auto res = cli.Get("/");
  14744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14745. ASSERT_FALSE(!res);
  14746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14747. ASSERT_FALSE(res == nullptr);
  14748. ASSERT_TRUE(res != nullptr);
  14749. EXPECT_EQ(Error::Success, res.error());
  14750. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14751. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14752. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14753. cli.set_follow_location(true);
  14754. res = cli.Get("/");
  14755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14756. EXPECT_EQ(Error::Success, res.error());
  14757. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14758. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14759. EXPECT_EQ(StatusCode::OK_200, res->status);
  14760. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14761. }
  14762. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14763. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14764. Client cli("https://cdnjs.cloudflare.com");
  14765. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14766. Headers{{"Accept-Encoding", "br"}});
  14767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14768. EXPECT_EQ(StatusCode::OK_200, res->status);
  14769. EXPECT_EQ(287630U, res->body.size());
  14770. EXPECT_EQ("application/javascript; charset=utf-8",
  14771. res->get_header_value("Content-Type"));
  14772. }
  14773. #endif
  14774. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14775. #undef REDIR_HOST // Silence compiler warning
  14776. #define REDIR_HOST "https://httpbingo.org"
  14777. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14778. Client cli(REDIR_HOST);
  14779. cli.set_follow_location(true);
  14780. auto res =
  14781. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14783. EXPECT_EQ(StatusCode::OK_200, res->status);
  14784. }
  14785. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14786. Client cli(REDIR_HOST);
  14787. cli.set_follow_location(true);
  14788. Params params;
  14789. params.emplace("url", "http://example.com");
  14790. params.emplace("status_code", "302");
  14791. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14793. EXPECT_EQ(StatusCode::OK_200, res->status);
  14794. }
  14795. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14796. Client cli(REDIR_HOST);
  14797. cli.set_follow_location(true);
  14798. Params params;
  14799. params.emplace("url", "http://example.com");
  14800. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14802. EXPECT_EQ(StatusCode::OK_200, res->status);
  14803. }
  14804. TEST(HttpToHttpsRedirectTest, CertFile) {
  14805. auto ssl_port = PORT + 1;
  14806. Server svr;
  14807. ASSERT_TRUE(svr.is_valid());
  14808. svr.Get("/index", [&](const Request &, Response &res) {
  14809. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14810. "/index");
  14811. svr.stop();
  14812. });
  14813. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14814. ASSERT_TRUE(ssl_svr.is_valid());
  14815. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14816. res.set_content("test", "text/plain");
  14817. ssl_svr.stop();
  14818. });
  14819. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14820. thread t2 =
  14821. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14822. auto se = detail::scope_exit([&] {
  14823. t2.join();
  14824. t.join();
  14825. ASSERT_FALSE(svr.is_running());
  14826. });
  14827. svr.wait_until_ready();
  14828. ssl_svr.wait_until_ready();
  14829. Client cli("127.0.0.1", PORT);
  14830. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14831. cli.enable_server_certificate_verification(true);
  14832. cli.set_follow_location(true);
  14833. cli.set_connection_timeout(30);
  14834. auto res = cli.Get("/index");
  14835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14836. ASSERT_EQ(StatusCode::OK_200, res->status);
  14837. }
  14838. TEST(SSLClientRedirectTest, CertFile) {
  14839. auto ssl_port = PORT + 1;
  14840. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14841. ASSERT_TRUE(ssl_svr1.is_valid());
  14842. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14843. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14844. "/index");
  14845. ssl_svr1.stop();
  14846. });
  14847. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14848. ASSERT_TRUE(ssl_svr2.is_valid());
  14849. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14850. res.set_content("test", "text/plain");
  14851. ssl_svr2.stop();
  14852. });
  14853. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14854. thread t2 =
  14855. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14856. auto se = detail::scope_exit([&] {
  14857. t2.join();
  14858. t.join();
  14859. ASSERT_FALSE(ssl_svr1.is_running());
  14860. });
  14861. ssl_svr1.wait_until_ready();
  14862. ssl_svr2.wait_until_ready();
  14863. SSLClient cli("127.0.0.1", PORT);
  14864. std::string cert;
  14865. read_file(SERVER_CERT2_FILE, cert);
  14866. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14867. cli.enable_server_certificate_verification(true);
  14868. cli.set_follow_location(true);
  14869. cli.set_connection_timeout(30);
  14870. auto res = cli.Get("/index");
  14871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14872. ASSERT_EQ(StatusCode::OK_200, res->status);
  14873. }
  14874. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14875. // another port, so the client follows it with a new client.
  14876. static Result GetThroughTlsRedirectToDifferentPort(
  14877. const std::function<void(SSLClient &)> &setup,
  14878. const char *target_cert = SERVER_CERT2_FILE,
  14879. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14880. auto ssl_port = PORT + 1;
  14881. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14882. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14883. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14884. "/index");
  14885. });
  14886. SSLServer ssl_svr2(target_cert, target_key);
  14887. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14888. res.set_content("test", "text/plain");
  14889. });
  14890. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14891. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14892. auto se = detail::scope_exit([&] {
  14893. ssl_svr2.stop();
  14894. ssl_svr1.stop();
  14895. t2.join();
  14896. t.join();
  14897. });
  14898. ssl_svr1.wait_until_ready();
  14899. ssl_svr2.wait_until_ready();
  14900. SSLClient cli("127.0.0.1", PORT);
  14901. cli.set_follow_location(true);
  14902. cli.set_connection_timeout(30);
  14903. setup(cli);
  14904. return cli.Get("/index");
  14905. }
  14906. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14907. auto calls = 0;
  14908. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14909. cli.enable_server_certificate_verification(false);
  14910. // Accept the first server only.
  14911. cli.set_session_verifier([&](tls::session_t) {
  14912. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14913. : SSLVerifierResponse::CertificateRejected;
  14914. });
  14915. });
  14916. ASSERT_FALSE(res);
  14917. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14918. EXPECT_EQ(2, calls);
  14919. }
  14920. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14921. std::string pinned;
  14922. auto res = GetThroughTlsRedirectToDifferentPort(
  14923. [&](SSLClient &cli) {
  14924. cli.enable_server_certificate_verification(false);
  14925. // Pin the first certificate seen.
  14926. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14927. if (pinned.empty()) { pinned = ctx.serial(); }
  14928. return ctx.serial() == pinned;
  14929. });
  14930. },
  14931. // A certificate other than the first server's.
  14932. SERVER_CERT_FILE);
  14933. EXPECT_FALSE(res);
  14934. EXPECT_FALSE(pinned.empty());
  14935. }
  14936. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14937. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14938. std::string cert;
  14939. read_file(SERVER_CERT2_FILE, cert);
  14940. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14941. });
  14942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14943. EXPECT_EQ(StatusCode::OK_200, res->status);
  14944. }
  14945. // The target's certificate is signed by the root CA, which the first server's
  14946. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  14947. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  14948. auto res = GetThroughTlsRedirectToDifferentPort(
  14949. [](SSLClient &cli) {
  14950. std::string root_ca, cert;
  14951. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14952. read_file(SERVER_CERT2_FILE, cert);
  14953. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14954. cli.load_ca_cert_store(cert.data(), cert.size());
  14955. cli.enable_server_hostname_verification(false);
  14956. },
  14957. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14959. EXPECT_EQ(StatusCode::OK_200, res->status);
  14960. }
  14961. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  14962. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  14963. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  14964. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  14965. auto res = GetThroughTlsRedirectToDifferentPort(
  14966. [](SSLClient &cli) {
  14967. std::string root_ca, cert;
  14968. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14969. read_file(SERVER_CERT2_FILE, cert);
  14970. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14971. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14972. cli.enable_server_hostname_verification(false);
  14973. },
  14974. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14975. ASSERT_FALSE(res);
  14976. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14977. }
  14978. #endif
  14979. #endif
  14980. #ifdef CPPHTTPLIB_SSL_ENABLED
  14981. // Test that set_ca_cert_store() skips system certs (consistent with
  14982. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14983. // should be trusted - system certs should NOT be loaded.
  14984. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14985. // Load a specific cert that is NOT a system CA cert
  14986. std::string cert;
  14987. read_file(SERVER_CERT2_FILE, cert);
  14988. SSLClient cli("google.com");
  14989. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14990. cli.enable_server_certificate_verification(true);
  14991. // This should FAIL because:
  14992. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14993. // 2. System certs should NOT be loaded when custom store is set
  14994. // If system certs WERE loaded, this would succeed
  14995. auto res = cli.Get("/");
  14996. ASSERT_FALSE(res);
  14997. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14998. }
  14999. // Same as above, but through the native store handle path. Regression test:
  15000. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15001. // merged system certs into the user-provided store.
  15002. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15003. std::string cert;
  15004. read_file(SERVER_CERT2_FILE, cert);
  15005. SSLClient cli("google.com");
  15006. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15007. cli.enable_server_certificate_verification(true);
  15008. auto res = cli.Get("/");
  15009. ASSERT_FALSE(res);
  15010. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15011. }
  15012. // A custom store set via the native handle must still verify a server whose
  15013. // cert it does contain.
  15014. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15015. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15016. ASSERT_TRUE(svr.is_valid());
  15017. svr.Get("/test", [&](const Request &, Response &res) {
  15018. res.set_content("test", "text/plain");
  15019. });
  15020. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15021. auto se = detail::scope_exit([&] {
  15022. svr.stop();
  15023. t.join();
  15024. ASSERT_FALSE(svr.is_running());
  15025. });
  15026. svr.wait_until_ready();
  15027. SSLClient cli("127.0.0.1", PORT);
  15028. std::string cert;
  15029. read_file(SERVER_CERT2_FILE, cert);
  15030. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15031. cli.enable_server_certificate_verification(true);
  15032. cli.set_connection_timeout(30);
  15033. auto res = cli.Get("/test");
  15034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15035. ASSERT_EQ(StatusCode::OK_200, res->status);
  15036. }
  15037. // CA certs loaded through the universal Client must be transferred to the
  15038. // client created internally for following an HTTPS redirect. Regression test:
  15039. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15040. // the CA data for redirect transfer.
  15041. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15042. auto ssl_port = PORT + 1;
  15043. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15044. ASSERT_TRUE(ssl_svr1.is_valid());
  15045. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15046. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15047. "/index");
  15048. });
  15049. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15050. ASSERT_TRUE(ssl_svr2.is_valid());
  15051. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15052. res.set_content("test", "text/plain");
  15053. });
  15054. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15055. thread t2 =
  15056. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15057. auto se = detail::scope_exit([&] {
  15058. ssl_svr2.stop();
  15059. ssl_svr1.stop();
  15060. t2.join();
  15061. t.join();
  15062. ASSERT_FALSE(ssl_svr1.is_running());
  15063. });
  15064. ssl_svr1.wait_until_ready();
  15065. ssl_svr2.wait_until_ready();
  15066. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15067. std::string cert;
  15068. read_file(SERVER_CERT2_FILE, cert);
  15069. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15070. cli.enable_server_certificate_verification(true);
  15071. cli.set_follow_location(true);
  15072. cli.set_connection_timeout(30);
  15073. auto res = cli.Get("/index");
  15074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15075. ASSERT_EQ(StatusCode::OK_200, res->status);
  15076. }
  15077. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15078. // so a host signed by a system CA verifies even though a custom CA is set
  15079. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15080. std::string cert;
  15081. read_file(SERVER_CERT2_FILE, cert);
  15082. SSLClient cli("google.com");
  15083. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15084. cli.enable_system_ca(true);
  15085. cli.enable_server_certificate_verification(true);
  15086. auto res = cli.Get("/");
  15087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15088. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15089. }
  15090. // The custom CA remains effective when combined with the system CA
  15091. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15092. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15093. ASSERT_TRUE(svr.is_valid());
  15094. svr.Get("/test", [&](const Request &, Response &res) {
  15095. res.set_content("test", "text/plain");
  15096. });
  15097. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15098. auto se = detail::scope_exit([&] {
  15099. svr.stop();
  15100. t.join();
  15101. ASSERT_FALSE(svr.is_running());
  15102. });
  15103. svr.wait_until_ready();
  15104. SSLClient cli("127.0.0.1", PORT);
  15105. std::string cert;
  15106. read_file(SERVER_CERT2_FILE, cert);
  15107. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15108. cli.enable_system_ca(true);
  15109. cli.enable_server_certificate_verification(true);
  15110. cli.set_connection_timeout(30);
  15111. auto res = cli.Get("/test");
  15112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15113. ASSERT_EQ(StatusCode::OK_200, res->status);
  15114. }
  15115. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15116. // skip chain verification entirely (only the certificate identity was
  15117. // checked), so a server presenting an untrusted certificate with a matching
  15118. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15119. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15120. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15121. ASSERT_TRUE(svr.is_valid());
  15122. svr.Get("/test", [&](const Request &, Response &res) {
  15123. res.set_content("test", "text/plain");
  15124. });
  15125. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15126. auto se = detail::scope_exit([&] {
  15127. svr.stop();
  15128. t.join();
  15129. ASSERT_FALSE(svr.is_running());
  15130. });
  15131. svr.wait_until_ready();
  15132. SSLClient cli("127.0.0.1", PORT);
  15133. std::string cert;
  15134. // A trusted CA that did not sign the server certificate. The server cert
  15135. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15136. // this connection.
  15137. read_file(CLIENT_CA_CERT_FILE, cert);
  15138. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15139. cli.enable_server_certificate_verification(true);
  15140. cli.set_connection_timeout(30);
  15141. auto res = cli.Get("/test");
  15142. ASSERT_FALSE(res);
  15143. }
  15144. // enable_system_ca(false) prevents system CA loading entirely
  15145. TEST(SSLClientTest, DisableSystemCa_Online) {
  15146. SSLClient cli("google.com");
  15147. cli.enable_system_ca(false);
  15148. cli.enable_server_certificate_verification(true);
  15149. auto res = cli.Get("/");
  15150. ASSERT_FALSE(res);
  15151. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15152. // itself when the CA chain is empty
  15153. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15154. res.error() == Error::SSLConnection);
  15155. }
  15156. // The universal Client forwards enable_system_ca()
  15157. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15158. std::string cert;
  15159. read_file(SERVER_CERT2_FILE, cert);
  15160. Client cli("https://google.com");
  15161. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15162. cli.enable_system_ca(true);
  15163. cli.enable_server_certificate_verification(true);
  15164. auto res = cli.Get("/");
  15165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15166. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15167. }
  15168. // The system CA policy must carry over to the client created internally for
  15169. // following a cross-host HTTPS redirect
  15170. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15171. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15172. ASSERT_TRUE(svr.is_valid());
  15173. svr.Get("/index", [&](const Request &, Response &res) {
  15174. res.set_redirect("https://www.google.com/");
  15175. });
  15176. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15177. auto se = detail::scope_exit([&] {
  15178. svr.stop();
  15179. t.join();
  15180. ASSERT_FALSE(svr.is_running());
  15181. });
  15182. svr.wait_until_ready();
  15183. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15184. std::string cert;
  15185. read_file(SERVER_CERT2_FILE, cert);
  15186. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15187. cli.enable_system_ca(true);
  15188. cli.enable_server_certificate_verification(true);
  15189. cli.set_follow_location(true);
  15190. cli.set_connection_timeout(30);
  15191. // Receiving any response proves the redirect client completed the TLS
  15192. // handshake with a system-CA-signed host
  15193. auto res = cli.Get("/index");
  15194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15195. }
  15196. TEST(MultipartFormDataTest, LargeData) {
  15197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15198. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15199. const ContentReader &content_reader) {
  15200. if (req.is_multipart_form_data()) {
  15201. std::vector<FormData> items;
  15202. content_reader(
  15203. [&](const FormData &file) {
  15204. items.push_back(file);
  15205. return true;
  15206. },
  15207. [&](const char *data, size_t data_length) {
  15208. items.back().content.append(data, data_length);
  15209. return true;
  15210. });
  15211. EXPECT_TRUE(std::string(items[0].name) == "document");
  15212. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15213. EXPECT_TRUE(items[0].filename == "2MB_data");
  15214. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15215. EXPECT_TRUE(items[1].name == "hello");
  15216. EXPECT_TRUE(items[1].content == "world");
  15217. EXPECT_TRUE(items[1].filename == "");
  15218. EXPECT_TRUE(items[1].content_type == "");
  15219. } else {
  15220. std::string body;
  15221. content_reader([&](const char *data, size_t data_length) {
  15222. body.append(data, data_length);
  15223. return true;
  15224. });
  15225. }
  15226. });
  15227. auto port = svr.bind_to_any_port(HOST);
  15228. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15229. auto se = detail::scope_exit([&] {
  15230. svr.stop();
  15231. t.join();
  15232. ASSERT_FALSE(svr.is_running());
  15233. });
  15234. svr.wait_until_ready();
  15235. {
  15236. std::string data(1024 * 1024 * 2, '.');
  15237. std::stringstream buffer;
  15238. buffer << data;
  15239. SSLClient cli(HOST, port);
  15240. cli.enable_server_certificate_verification(false);
  15241. UploadFormDataItems items{
  15242. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15243. {"hello", "world", "", ""},
  15244. };
  15245. auto res = cli.Post("/post", items);
  15246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15247. ASSERT_EQ(StatusCode::OK_200, res->status);
  15248. }
  15249. }
  15250. TEST(MultipartFormDataTest, DataProviderItems) {
  15251. std::random_device seed_gen;
  15252. std::mt19937 random(seed_gen());
  15253. std::string rand1;
  15254. rand1.resize(1000);
  15255. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15256. std::string rand2;
  15257. rand2.resize(3000);
  15258. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15259. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15260. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15261. const ContentReader &content_reader) {
  15262. ASSERT_FALSE(req.is_multipart_form_data());
  15263. std::string body;
  15264. content_reader([&](const char *data, size_t data_length) {
  15265. body.append(data, data_length);
  15266. return true;
  15267. });
  15268. EXPECT_EQ(body, "");
  15269. });
  15270. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15271. const ContentReader &content_reader) {
  15272. ASSERT_TRUE(req.is_multipart_form_data());
  15273. std::vector<FormData> items;
  15274. content_reader(
  15275. [&](const FormData &file) {
  15276. items.push_back(file);
  15277. return true;
  15278. },
  15279. [&](const char *data, size_t data_length) {
  15280. items.back().content.append(data, data_length);
  15281. return true;
  15282. });
  15283. ASSERT_TRUE(items.size() == 2);
  15284. EXPECT_EQ(std::string(items[0].name), "name1");
  15285. EXPECT_EQ(items[0].content, "Testing123");
  15286. EXPECT_EQ(items[0].filename, "filename1");
  15287. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15288. EXPECT_EQ(items[1].name, "name2");
  15289. EXPECT_EQ(items[1].content, "Testing456");
  15290. EXPECT_EQ(items[1].filename, "");
  15291. EXPECT_EQ(items[1].content_type, "");
  15292. });
  15293. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15294. const ContentReader &content_reader) {
  15295. ASSERT_TRUE(req.is_multipart_form_data());
  15296. std::vector<FormData> items;
  15297. content_reader(
  15298. [&](const FormData &file) {
  15299. items.push_back(file);
  15300. return true;
  15301. },
  15302. [&](const char *data, size_t data_length) {
  15303. items.back().content.append(data, data_length);
  15304. return true;
  15305. });
  15306. ASSERT_TRUE(items.size() == 2);
  15307. EXPECT_EQ(items[0].name, "name3");
  15308. EXPECT_EQ(items[0].content, rand1);
  15309. EXPECT_EQ(items[0].filename, "filename3");
  15310. EXPECT_EQ(items[0].content_type, "");
  15311. EXPECT_EQ(items[1].name, "name4");
  15312. EXPECT_EQ(items[1].content, rand2);
  15313. EXPECT_EQ(items[1].filename, "filename4");
  15314. EXPECT_EQ(items[1].content_type, "");
  15315. });
  15316. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15317. const ContentReader &content_reader) {
  15318. ASSERT_TRUE(req.is_multipart_form_data());
  15319. std::vector<FormData> items;
  15320. content_reader(
  15321. [&](const FormData &file) {
  15322. items.push_back(file);
  15323. return true;
  15324. },
  15325. [&](const char *data, size_t data_length) {
  15326. items.back().content.append(data, data_length);
  15327. return true;
  15328. });
  15329. ASSERT_TRUE(items.size() == 4);
  15330. EXPECT_EQ(std::string(items[0].name), "name1");
  15331. EXPECT_EQ(items[0].content, "Testing123");
  15332. EXPECT_EQ(items[0].filename, "filename1");
  15333. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15334. EXPECT_EQ(items[1].name, "name2");
  15335. EXPECT_EQ(items[1].content, "Testing456");
  15336. EXPECT_EQ(items[1].filename, "");
  15337. EXPECT_EQ(items[1].content_type, "");
  15338. EXPECT_EQ(items[2].name, "name3");
  15339. EXPECT_EQ(items[2].content, rand1);
  15340. EXPECT_EQ(items[2].filename, "filename3");
  15341. EXPECT_EQ(items[2].content_type, "");
  15342. EXPECT_EQ(items[3].name, "name4");
  15343. EXPECT_EQ(items[3].content, rand2);
  15344. EXPECT_EQ(items[3].filename, "filename4");
  15345. EXPECT_EQ(items[3].content_type, "");
  15346. });
  15347. auto port = svr.bind_to_any_port("localhost");
  15348. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15349. auto se = detail::scope_exit([&] {
  15350. svr.stop();
  15351. t.join();
  15352. ASSERT_FALSE(svr.is_running());
  15353. });
  15354. svr.wait_until_ready();
  15355. {
  15356. SSLClient cli("localhost", port);
  15357. cli.enable_server_certificate_verification(false);
  15358. UploadFormDataItems items{
  15359. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15360. {"name2", "Testing456", "", ""}, // not a file
  15361. };
  15362. {
  15363. auto res = cli.Post("/post-none", {}, {}, {});
  15364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15365. ASSERT_EQ(StatusCode::OK_200, res->status);
  15366. }
  15367. FormDataProviderItems providers;
  15368. {
  15369. auto res =
  15370. cli.Post("/post-items", {}, items, providers); // empty providers
  15371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15372. ASSERT_EQ(StatusCode::OK_200, res->status);
  15373. }
  15374. providers.push_back({"name3",
  15375. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15376. // test the offset is given correctly at each step
  15377. if (!offset)
  15378. sink.os.write(rand1.data(), 30);
  15379. else if (offset == 30)
  15380. sink.os.write(rand1.data() + 30, 300);
  15381. else if (offset == 330)
  15382. sink.os.write(rand1.data() + 330, 670);
  15383. else if (offset == rand1.size())
  15384. sink.done();
  15385. return true;
  15386. },
  15387. "filename3",
  15388. {}});
  15389. providers.push_back({"name4",
  15390. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15391. // test the offset is given correctly at each step
  15392. if (!offset)
  15393. sink.os.write(rand2.data(), 2000);
  15394. else if (offset == 2000)
  15395. sink.os.write(rand2.data() + 2000, 1);
  15396. else if (offset == 2001)
  15397. sink.os.write(rand2.data() + 2001, 999);
  15398. else if (offset == rand2.size())
  15399. sink.done();
  15400. return true;
  15401. },
  15402. "filename4",
  15403. {}});
  15404. {
  15405. auto res = cli.Post("/post-providers", {}, {}, providers);
  15406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15407. ASSERT_EQ(StatusCode::OK_200, res->status);
  15408. }
  15409. {
  15410. auto res = cli.Post("/post-both", {}, items, providers);
  15411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15412. ASSERT_EQ(StatusCode::OK_200, res->status);
  15413. }
  15414. }
  15415. }
  15416. TEST(MultipartFormDataTest, BadHeader) {
  15417. Server svr;
  15418. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15419. res.set_content("ok", "text/plain");
  15420. });
  15421. thread t = thread([&] { svr.listen(HOST, PORT); });
  15422. auto se = detail::scope_exit([&] {
  15423. svr.stop();
  15424. t.join();
  15425. ASSERT_FALSE(svr.is_running());
  15426. });
  15427. svr.wait_until_ready();
  15428. const std::string body =
  15429. "This is the preamble. It is to be ignored, though it\r\n"
  15430. "is a handy place for composition agents to include an\r\n"
  15431. "explanatory note to non-MIME conformant readers.\r\n"
  15432. "\r\n"
  15433. "\r\n"
  15434. "--simple boundary\r\n"
  15435. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15436. ": BAD...\r\n"
  15437. "\r\n"
  15438. "value1\r\n"
  15439. "--simple boundary\r\n"
  15440. "Content-Disposition: form-data; name=\"field2\"; "
  15441. "filename=\"example.txt\"\r\n"
  15442. "\r\n"
  15443. "value2\r\n"
  15444. "--simple boundary--\r\n"
  15445. "This is the epilogue. It is also to be ignored.\r\n";
  15446. std::string content_type =
  15447. R"(multipart/form-data; boundary="simple boundary")";
  15448. Client cli(HOST, PORT);
  15449. auto res = cli.Post("/post", body, content_type.c_str());
  15450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15451. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15452. }
  15453. TEST(MultipartFormDataTest, WithPreamble) {
  15454. Server svr;
  15455. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15456. res.set_content("ok", "text/plain");
  15457. });
  15458. thread t = thread([&] { svr.listen(HOST, PORT); });
  15459. auto se = detail::scope_exit([&] {
  15460. svr.stop();
  15461. t.join();
  15462. ASSERT_FALSE(svr.is_running());
  15463. });
  15464. svr.wait_until_ready();
  15465. const std::string body =
  15466. "This is the preamble. It is to be ignored, though it\r\n"
  15467. "is a handy place for composition agents to include an\r\n"
  15468. "explanatory note to non-MIME conformant readers.\r\n"
  15469. "\r\n"
  15470. "\r\n"
  15471. "--simple boundary\r\n"
  15472. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15473. "\r\n"
  15474. "value1\r\n"
  15475. "--simple boundary\r\n"
  15476. "Content-Disposition: form-data; name=\"field2\"; "
  15477. "filename=\"example.txt\"\r\n"
  15478. "\r\n"
  15479. "value2\r\n"
  15480. "--simple boundary--\r\n"
  15481. "This is the epilogue. It is also to be ignored.\r\n";
  15482. std::string content_type =
  15483. R"(multipart/form-data; boundary="simple boundary")";
  15484. Client cli(HOST, PORT);
  15485. auto res = cli.Post("/post", body, content_type.c_str());
  15486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15487. EXPECT_EQ(StatusCode::OK_200, res->status);
  15488. }
  15489. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15490. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15491. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15492. const ContentReader &content_reader) {
  15493. if (req.is_multipart_form_data()) {
  15494. std::vector<FormData> items;
  15495. content_reader(
  15496. [&](const FormData &file) {
  15497. items.push_back(file);
  15498. return true;
  15499. },
  15500. [&](const char *data, size_t data_length) {
  15501. items.back().content.append(data, data_length);
  15502. return true;
  15503. });
  15504. EXPECT_TRUE(std::string(items[0].name) == "document");
  15505. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15506. EXPECT_TRUE(items[0].filename == "2MB_data");
  15507. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15508. EXPECT_TRUE(items[1].name == "hello");
  15509. EXPECT_TRUE(items[1].content == "world");
  15510. EXPECT_TRUE(items[1].filename == "");
  15511. EXPECT_TRUE(items[1].content_type == "");
  15512. } else {
  15513. std::string body;
  15514. content_reader([&](const char *data, size_t data_length) {
  15515. body.append(data, data_length);
  15516. return true;
  15517. });
  15518. }
  15519. });
  15520. auto port = svr.bind_to_any_port("localhost");
  15521. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15522. auto se = detail::scope_exit([&] {
  15523. svr.stop();
  15524. t.join();
  15525. ASSERT_FALSE(svr.is_running());
  15526. });
  15527. svr.wait_until_ready();
  15528. {
  15529. std::string data(1024 * 1024 * 2, '.');
  15530. std::stringstream buffer;
  15531. buffer << data;
  15532. SSLClient cli("localhost", port);
  15533. cli.enable_server_certificate_verification(false);
  15534. UploadFormDataItems items{
  15535. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15536. {"hello", "world", "", ""},
  15537. };
  15538. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15540. ASSERT_EQ(StatusCode::OK_200, res->status);
  15541. }
  15542. }
  15543. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15544. std::string data(1024 * 1024 * 2, '&');
  15545. std::stringstream buffer;
  15546. buffer << data;
  15547. Client cli("https://localhost:8080");
  15548. UploadFormDataItems items{
  15549. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15550. {"hello", "world", "", ""},
  15551. };
  15552. for (const char &c : " \t\r\n") {
  15553. auto res =
  15554. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15555. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15556. ASSERT_FALSE(res);
  15557. }
  15558. }
  15559. TEST(MultipartFormDataTest, PutFormData) {
  15560. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15561. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15562. const ContentReader &content_reader) {
  15563. if (req.is_multipart_form_data()) {
  15564. std::vector<FormData> items;
  15565. content_reader(
  15566. [&](const FormData &file) {
  15567. items.push_back(file);
  15568. return true;
  15569. },
  15570. [&](const char *data, size_t data_length) {
  15571. items.back().content.append(data, data_length);
  15572. return true;
  15573. });
  15574. EXPECT_TRUE(std::string(items[0].name) == "document");
  15575. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15576. EXPECT_TRUE(items[0].filename == "2MB_data");
  15577. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15578. EXPECT_TRUE(items[1].name == "hello");
  15579. EXPECT_TRUE(items[1].content == "world");
  15580. EXPECT_TRUE(items[1].filename == "");
  15581. EXPECT_TRUE(items[1].content_type == "");
  15582. } else {
  15583. std::string body;
  15584. content_reader([&](const char *data, size_t data_length) {
  15585. body.append(data, data_length);
  15586. return true;
  15587. });
  15588. }
  15589. });
  15590. auto port = svr.bind_to_any_port("localhost");
  15591. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15592. auto se = detail::scope_exit([&] {
  15593. svr.stop();
  15594. t.join();
  15595. ASSERT_FALSE(svr.is_running());
  15596. });
  15597. svr.wait_until_ready();
  15598. {
  15599. std::string data(1024 * 1024 * 2, '&');
  15600. std::stringstream buffer;
  15601. buffer << data;
  15602. SSLClient cli("localhost", port);
  15603. cli.enable_server_certificate_verification(false);
  15604. UploadFormDataItems items{
  15605. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15606. {"hello", "world", "", ""},
  15607. };
  15608. auto res = cli.Put("/put", items);
  15609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15610. ASSERT_EQ(StatusCode::OK_200, res->status);
  15611. }
  15612. }
  15613. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15614. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15615. svr.Put("/put_customboundary",
  15616. [&](const Request &req, const Response & /*res*/,
  15617. const ContentReader &content_reader) {
  15618. if (req.is_multipart_form_data()) {
  15619. std::vector<FormData> items;
  15620. content_reader(
  15621. [&](const FormData &file) {
  15622. items.push_back(file);
  15623. return true;
  15624. },
  15625. [&](const char *data, size_t data_length) {
  15626. items.back().content.append(data, data_length);
  15627. return true;
  15628. });
  15629. EXPECT_TRUE(std::string(items[0].name) == "document");
  15630. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15631. EXPECT_TRUE(items[0].filename == "2MB_data");
  15632. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15633. EXPECT_TRUE(items[1].name == "hello");
  15634. EXPECT_TRUE(items[1].content == "world");
  15635. EXPECT_TRUE(items[1].filename == "");
  15636. EXPECT_TRUE(items[1].content_type == "");
  15637. } else {
  15638. std::string body;
  15639. content_reader([&](const char *data, size_t data_length) {
  15640. body.append(data, data_length);
  15641. return true;
  15642. });
  15643. }
  15644. });
  15645. auto port = svr.bind_to_any_port("localhost");
  15646. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15647. auto se = detail::scope_exit([&] {
  15648. svr.stop();
  15649. t.join();
  15650. ASSERT_FALSE(svr.is_running());
  15651. });
  15652. svr.wait_until_ready();
  15653. {
  15654. std::string data(1024 * 1024 * 2, '&');
  15655. std::stringstream buffer;
  15656. buffer << data;
  15657. SSLClient cli("localhost", port);
  15658. cli.enable_server_certificate_verification(false);
  15659. UploadFormDataItems items{
  15660. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15661. {"hello", "world", "", ""},
  15662. };
  15663. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15665. ASSERT_EQ(StatusCode::OK_200, res->status);
  15666. }
  15667. }
  15668. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15669. std::string data(1024 * 1024 * 2, '&');
  15670. std::stringstream buffer;
  15671. buffer << data;
  15672. Client cli("https://localhost:8080");
  15673. cli.enable_server_certificate_verification(false);
  15674. UploadFormDataItems items{
  15675. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15676. {"hello", "world", "", ""},
  15677. };
  15678. for (const char &c : " \t\r\n") {
  15679. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15680. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15681. ASSERT_FALSE(res);
  15682. }
  15683. }
  15684. TEST(MultipartFormDataTest, AlternateFilename) {
  15685. auto handled = false;
  15686. Server svr;
  15687. svr.Post("/test", [&](const Request &req, Response &res) {
  15688. ASSERT_EQ(2u, req.form.files.size());
  15689. ASSERT_EQ(1u, req.form.fields.size());
  15690. // Test files
  15691. const auto &file1 = req.form.get_file("file1");
  15692. ASSERT_EQ("file1", file1.name);
  15693. ASSERT_EQ("A.txt", file1.filename);
  15694. ASSERT_EQ("text/plain", file1.content_type);
  15695. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15696. const auto &file2 = req.form.get_file("file2");
  15697. ASSERT_EQ("file2", file2.name);
  15698. ASSERT_EQ("a.html", file2.filename);
  15699. ASSERT_EQ("text/html", file2.content_type);
  15700. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15701. file2.content);
  15702. // Test text field
  15703. const auto &text = req.form.get_field("text");
  15704. ASSERT_EQ("text default", text);
  15705. res.set_content("ok", "text/plain");
  15706. handled = true;
  15707. });
  15708. thread t = thread([&] { svr.listen(HOST, PORT); });
  15709. auto se = detail::scope_exit([&] {
  15710. svr.stop();
  15711. t.join();
  15712. ASSERT_FALSE(svr.is_running());
  15713. ASSERT_TRUE(handled);
  15714. });
  15715. svr.wait_until_ready();
  15716. auto req = "POST /test HTTP/1.1\r\n"
  15717. "Host: localhost\r\n"
  15718. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15719. "Content-Length: 399\r\n"
  15720. "\r\n"
  15721. "----------\r\n"
  15722. "Content-Disposition: form-data; name=\"text\"\r\n"
  15723. "\r\n"
  15724. "text default\r\n"
  15725. "----------\r\n"
  15726. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15727. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15728. "Content-Type: text/plain\r\n"
  15729. "\r\n"
  15730. "Content of a.txt.\r\n"
  15731. "\r\n"
  15732. "----------\r\n"
  15733. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15734. "\"a.html\"\r\n"
  15735. "Content-Type: text/html\r\n"
  15736. "\r\n"
  15737. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15738. "\r\n"
  15739. "------------\r\n";
  15740. ASSERT_TRUE(send_request(1, req));
  15741. }
  15742. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15743. auto handled = false;
  15744. Server svr;
  15745. svr.Post("/test", [&](const Request &req, Response &res) {
  15746. // Case-insensitive "utf-8''" prefix with a long value
  15747. const auto &file = req.form.get_file("file1");
  15748. ASSERT_EQ("file1", file.name);
  15749. // 8000 chars exercises both the Content-Disposition parser and the
  15750. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15751. // Prior to the fix, std::regex_match on this header would cause O(N)
  15752. // stack recursion in libstdc++, leading to SIGSEGV.
  15753. std::string expected_filename(8000, 'A');
  15754. ASSERT_EQ(expected_filename, file.filename);
  15755. res.set_content("ok", "text/plain");
  15756. handled = true;
  15757. });
  15758. thread t = thread([&] { svr.listen(HOST, PORT); });
  15759. auto se = detail::scope_exit([&] {
  15760. svr.stop();
  15761. t.join();
  15762. ASSERT_FALSE(svr.is_running());
  15763. ASSERT_TRUE(handled);
  15764. });
  15765. svr.wait_until_ready();
  15766. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15767. // Regression test for GHSA-qq6v-r583-3h69
  15768. std::string long_filename(8000, 'A');
  15769. std::string body = "----------\r\n"
  15770. "Content-Disposition: form-data; name=\"file1\"; "
  15771. "filename*=\"Utf-8''" +
  15772. long_filename +
  15773. "\"\r\n"
  15774. "\r\n"
  15775. "hello\r\n"
  15776. "------------\r\n";
  15777. auto req = "POST /test HTTP/1.1\r\n"
  15778. "Host: localhost\r\n"
  15779. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15780. "Content-Length: " +
  15781. std::to_string(body.size()) + "\r\n\r\n" + body;
  15782. ASSERT_TRUE(send_request(1, req));
  15783. }
  15784. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15785. auto handled = false;
  15786. Server svr;
  15787. svr.Post("/test", [&](const Request &req, Response &) {
  15788. ASSERT_EQ(2u, req.form.fields.size());
  15789. const auto &text1 = req.form.get_field("text1");
  15790. ASSERT_EQ("text1", text1);
  15791. const auto &text2 = req.form.get_field("text2");
  15792. ASSERT_EQ("text2", text2);
  15793. handled = true;
  15794. });
  15795. thread t = thread([&] { svr.listen(HOST, PORT); });
  15796. auto se = detail::scope_exit([&] {
  15797. svr.stop();
  15798. t.join();
  15799. ASSERT_FALSE(svr.is_running());
  15800. ASSERT_TRUE(handled);
  15801. });
  15802. svr.wait_until_ready();
  15803. auto req = "POST /test HTTP/1.1\r\n"
  15804. "Host: localhost\r\n"
  15805. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15806. "Content-Length: 146\r\n"
  15807. "\r\n----------\r\n"
  15808. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15809. "\r\n"
  15810. "text1"
  15811. "\r\n----------\r\n"
  15812. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15813. "\r\n"
  15814. "text2"
  15815. "\r\n------------";
  15816. std::string response;
  15817. ASSERT_TRUE(send_request(1, req, &response));
  15818. ASSERT_EQ("200", response.substr(9, 3));
  15819. }
  15820. TEST(MultipartFormDataTest, ContentLength) {
  15821. auto handled = false;
  15822. Server svr;
  15823. svr.Post("/test", [&](const Request &req, Response &) {
  15824. ASSERT_EQ(2u, req.form.fields.size());
  15825. const auto &text1 = req.form.get_field("text1");
  15826. ASSERT_EQ("text1", text1);
  15827. const auto &text2 = req.form.get_field("text2");
  15828. ASSERT_EQ("text2", text2);
  15829. handled = true;
  15830. });
  15831. thread t = thread([&] { svr.listen(HOST, PORT); });
  15832. auto se = detail::scope_exit([&] {
  15833. svr.stop();
  15834. t.join();
  15835. ASSERT_FALSE(svr.is_running());
  15836. ASSERT_TRUE(handled);
  15837. });
  15838. svr.wait_until_ready();
  15839. auto req = "POST /test HTTP/1.1\r\n"
  15840. "Host: localhost\r\n"
  15841. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15842. "Content-Length: 167\r\n"
  15843. "\r\n----------\r\n"
  15844. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15845. "Content-Length: 5\r\n"
  15846. "\r\n"
  15847. "text1"
  15848. "\r\n----------\r\n"
  15849. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15850. "\r\n"
  15851. "text2"
  15852. "\r\n------------\r\n";
  15853. std::string response;
  15854. ASSERT_TRUE(send_request(1, req, &response));
  15855. ASSERT_EQ("200", response.substr(9, 3));
  15856. }
  15857. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15858. auto handled = false;
  15859. Server svr;
  15860. svr.Post("/test", [&](const Request &req, Response &) {
  15861. ASSERT_EQ(2u, req.form.fields.size());
  15862. const auto &text1 = req.form.get_field("text1");
  15863. ASSERT_EQ("text1", text1);
  15864. // TODO: Add header access for text fields if needed
  15865. const auto &text2 = req.form.get_field("text2");
  15866. ASSERT_EQ("text2", text2);
  15867. // TODO: Header access for text fields needs to be implemented
  15868. // auto &headers = it->second.headers;
  15869. // ASSERT_EQ(3U, headers.size());
  15870. // auto custom_header = headers.find("x-whatever");
  15871. // ASSERT_TRUE(custom_header != headers.end());
  15872. // ASSERT_NE("customvalue", custom_header->second);
  15873. // ASSERT_EQ("CustomValue", custom_header->second);
  15874. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15875. handled = true;
  15876. });
  15877. thread t = thread([&] { svr.listen(HOST, PORT); });
  15878. auto se = detail::scope_exit([&] {
  15879. svr.stop();
  15880. t.join();
  15881. ASSERT_FALSE(svr.is_running());
  15882. ASSERT_TRUE(handled);
  15883. });
  15884. svr.wait_until_ready();
  15885. auto req = "POST /test HTTP/1.1\r\n"
  15886. "Host: localhost\r\n"
  15887. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15888. "Content-Length: 232\r\n"
  15889. "\r\n----------\r\n"
  15890. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15891. "Content-Length: 5\r\n"
  15892. "X-Test: 1\r\n"
  15893. "\r\n"
  15894. "text1"
  15895. "\r\n----------\r\n"
  15896. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15897. "Content-Type: text/plain\r\n"
  15898. "X-Whatever: CustomValue\r\n"
  15899. "\r\n"
  15900. "text2"
  15901. "\r\n------------\r\n"
  15902. "That should be disregarded. Not even read";
  15903. std::string response;
  15904. ASSERT_TRUE(send_request(1, req, &response));
  15905. ASSERT_EQ("200", response.substr(9, 3));
  15906. }
  15907. TEST(MultipartFormDataTest, LargeHeader) {
  15908. auto handled = false;
  15909. Server svr;
  15910. svr.Post("/test", [&](const Request &req, Response &) {
  15911. ASSERT_EQ(1u, req.form.fields.size());
  15912. const auto &text = req.form.get_field("name1");
  15913. ASSERT_EQ("text1", text);
  15914. handled = true;
  15915. });
  15916. thread t = thread([&] { svr.listen(HOST, PORT); });
  15917. auto se = detail::scope_exit([&] {
  15918. svr.stop();
  15919. t.join();
  15920. ASSERT_FALSE(svr.is_running());
  15921. ASSERT_TRUE(handled);
  15922. });
  15923. svr.wait_until_ready();
  15924. auto boundary = std::string("cpp-httplib-multipart-data");
  15925. std::string content = "--" + boundary +
  15926. "\r\n"
  15927. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15928. "\r\n"
  15929. "text1\r\n"
  15930. "--" +
  15931. boundary + "--\r\n";
  15932. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15933. "Host: localhost\r\n"
  15934. "Content-Type: multipart/form-data;boundary=" +
  15935. boundary +
  15936. "\r\n"
  15937. "Content-Length: " +
  15938. std::to_string(content.size()) +
  15939. "\r\n"
  15940. "Dummy-Header: ";
  15941. std::string header_suffix = "\r\n"
  15942. "\r\n";
  15943. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15944. size_t header_dummy_size =
  15945. read_buff_size -
  15946. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15947. auto header_dummy = std::string(header_dummy_size, '@');
  15948. auto req = header_prefix + header_dummy + header_suffix + content;
  15949. std::string response;
  15950. ASSERT_TRUE(send_request(1, req, &response));
  15951. ASSERT_EQ("200", response.substr(9, 3));
  15952. }
  15953. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15954. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15955. // (not chunked Transfer-Encoding) after the streaming refactor.
  15956. auto handled = false;
  15957. Server svr;
  15958. svr.Post("/upload", [&](const Request &req, Response &res) {
  15959. auto cl_it = req.headers.find("Content-Length");
  15960. EXPECT_TRUE(cl_it != req.headers.end());
  15961. auto te_it = req.headers.find("Transfer-Encoding");
  15962. EXPECT_TRUE(te_it == req.headers.end());
  15963. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15964. res.set_content("ok", "text/plain");
  15965. handled = true;
  15966. });
  15967. auto port = svr.bind_to_any_port(HOST);
  15968. auto t = thread([&] { svr.listen_after_bind(); });
  15969. auto se = detail::scope_exit([&] {
  15970. svr.stop();
  15971. t.join();
  15972. ASSERT_FALSE(svr.is_running());
  15973. ASSERT_TRUE(handled);
  15974. });
  15975. svr.wait_until_ready();
  15976. UploadFormDataItems items = {
  15977. {"field1", "hello", "", "text/plain"},
  15978. {"file1", "world", "test.txt", "application/octet-stream"},
  15979. };
  15980. Client cli(HOST, port);
  15981. auto res = cli.Post("/upload", {}, items);
  15982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15983. EXPECT_EQ(StatusCode::OK_200, res->status);
  15984. }
  15985. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15986. // Verify that make_multipart_content_provider coalesces many small segments
  15987. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15988. constexpr size_t kItemCount = 1000;
  15989. UploadFormDataItems items;
  15990. items.reserve(kItemCount);
  15991. for (size_t i = 0; i < kItemCount; i++) {
  15992. items.push_back(
  15993. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15994. }
  15995. const std::string boundary = "----test-boundary";
  15996. auto content_length = detail::get_multipart_content_length(items, boundary);
  15997. auto provider = detail::make_multipart_content_provider(items, boundary);
  15998. // Drive the provider the same way write_content_with_progress does
  15999. size_t write_count = 0;
  16000. size_t total_bytes = 0;
  16001. DataSink sink;
  16002. size_t offset = 0;
  16003. sink.write = [&](const char *d, size_t l) -> bool {
  16004. (void)d;
  16005. write_count++;
  16006. total_bytes += l;
  16007. offset += l;
  16008. return true;
  16009. };
  16010. sink.is_writable = []() -> bool { return true; };
  16011. while (offset < content_length) {
  16012. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16013. }
  16014. EXPECT_EQ(content_length, total_bytes);
  16015. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16016. // With buffering into 64KB blocks, write_count should be much smaller.
  16017. auto segment_count = 3 * kItemCount + 1;
  16018. EXPECT_LT(write_count, segment_count / 10);
  16019. }
  16020. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16021. // Integration test: send many UploadFormDataItems and verify the server
  16022. // receives all of them correctly (#2410).
  16023. constexpr size_t kItemCount = 500;
  16024. auto handled = false;
  16025. Server svr;
  16026. svr.Post("/upload", [&](const Request &req, Response &res) {
  16027. EXPECT_EQ(kItemCount, req.form.fields.size());
  16028. for (size_t i = 0; i < kItemCount; i++) {
  16029. auto key = "field" + std::to_string(i);
  16030. auto val = "value" + std::to_string(i);
  16031. auto it = req.form.fields.find(key);
  16032. if (it != req.form.fields.end()) {
  16033. EXPECT_EQ(val, it->second.content);
  16034. } else {
  16035. ADD_FAILURE() << "Missing field: " << key;
  16036. }
  16037. }
  16038. res.set_content("ok", "text/plain");
  16039. handled = true;
  16040. });
  16041. auto port = svr.bind_to_any_port(HOST);
  16042. auto t = thread([&] { svr.listen_after_bind(); });
  16043. auto se = detail::scope_exit([&] {
  16044. svr.stop();
  16045. t.join();
  16046. ASSERT_FALSE(svr.is_running());
  16047. ASSERT_TRUE(handled);
  16048. });
  16049. svr.wait_until_ready();
  16050. UploadFormDataItems items;
  16051. items.reserve(kItemCount);
  16052. for (size_t i = 0; i < kItemCount; i++) {
  16053. items.push_back(
  16054. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16055. }
  16056. Client cli(HOST, port);
  16057. auto res = cli.Post("/upload", items);
  16058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16059. EXPECT_EQ(StatusCode::OK_200, res->status);
  16060. }
  16061. TEST(MultipartFormDataTest, MakeFileProvider) {
  16062. // Verify make_file_provider sends a file's contents correctly.
  16063. const std::string file_content(4096, 'Z');
  16064. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16065. {
  16066. std::ofstream ofs(tmp_path, std::ios::binary);
  16067. ofs.write(file_content.data(),
  16068. static_cast<std::streamsize>(file_content.size()));
  16069. }
  16070. auto handled = false;
  16071. Server svr;
  16072. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16073. const ContentReader &content_reader) {
  16074. ASSERT_TRUE(req.is_multipart_form_data());
  16075. std::vector<FormData> items;
  16076. content_reader(
  16077. [&](const FormData &file) {
  16078. items.push_back(file);
  16079. return true;
  16080. },
  16081. [&](const char *data, size_t data_length) {
  16082. items.back().content.append(data, data_length);
  16083. return true;
  16084. });
  16085. ASSERT_EQ(1u, items.size());
  16086. EXPECT_EQ("myfile", items[0].name);
  16087. EXPECT_EQ("data.bin", items[0].filename);
  16088. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16089. EXPECT_EQ(file_content, items[0].content);
  16090. handled = true;
  16091. });
  16092. auto port = svr.bind_to_any_port(HOST);
  16093. auto t = thread([&] { svr.listen_after_bind(); });
  16094. auto se = detail::scope_exit([&] {
  16095. svr.stop();
  16096. t.join();
  16097. ASSERT_FALSE(svr.is_running());
  16098. ASSERT_TRUE(handled);
  16099. std::remove(tmp_path.c_str());
  16100. });
  16101. svr.wait_until_ready();
  16102. FormDataProviderItems providers;
  16103. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16104. "application/octet-stream"));
  16105. Client cli(HOST, port);
  16106. auto res = cli.Post("/upload", {}, {}, providers);
  16107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16108. EXPECT_EQ(StatusCode::OK_200, res->status);
  16109. }
  16110. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16111. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16112. // (100) headers is rejected with a 400 Bad Request response.
  16113. Server svr;
  16114. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16115. res.set_content("ok", "text/plain");
  16116. });
  16117. thread t = thread([&] { svr.listen(HOST, PORT); });
  16118. auto se = detail::scope_exit([&] {
  16119. svr.stop();
  16120. t.join();
  16121. ASSERT_FALSE(svr.is_running());
  16122. });
  16123. svr.wait_until_ready();
  16124. // Build a multipart part with 101 custom headers (exceeding
  16125. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16126. std::stringstream body;
  16127. body << "--simpleboundary\r\n"
  16128. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16129. for (int i = 0; i < 101; i++) {
  16130. body << "X-Custom-Header-" << i << ": value\r\n";
  16131. }
  16132. body << "\r\n"
  16133. << "value1\r\n"
  16134. << "--simpleboundary--\r\n";
  16135. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16136. Client cli(HOST, PORT);
  16137. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16139. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16140. }
  16141. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16142. // A body that never contains the declared boundary must not be accumulated
  16143. // while the parser waits for it. Buffering it would also make every read
  16144. // rescan everything seen so far, which is quadratic in the body size.
  16145. Server svr;
  16146. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16147. res.set_content("ok", "text/plain");
  16148. });
  16149. auto port = svr.bind_to_any_port(HOST);
  16150. thread t = thread([&] { svr.listen_after_bind(); });
  16151. auto se = detail::scope_exit([&] {
  16152. svr.stop();
  16153. t.join();
  16154. ASSERT_FALSE(svr.is_running());
  16155. });
  16156. svr.wait_until_ready();
  16157. Client cli(HOST, port);
  16158. cli.set_read_timeout(60, 0);
  16159. cli.set_write_timeout(60, 0);
  16160. // '-' is the worst case: it matches the first character of the boundary, so
  16161. // every position has to be checked against it.
  16162. auto post_dashes = [&](size_t size) {
  16163. const std::string body(size, '-');
  16164. auto start = std::chrono::steady_clock::now();
  16165. auto res =
  16166. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16167. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16168. std::chrono::steady_clock::now() - start)
  16169. .count();
  16170. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16171. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16172. return ms;
  16173. };
  16174. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16175. // Windows.
  16176. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16177. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16178. // Comparing the two sizes rather than checking an absolute duration keeps
  16179. // this meaningful across build types and CI load, both of which move the
  16180. // absolute numbers by more than an order of magnitude. Four times the bytes
  16181. // costs about four times the time when parsing is linear, and about sixteen
  16182. // times when the body is buffered and rescanned.
  16183. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16184. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16185. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16186. << "ms, which suggests the body is being buffered and rescanned";
  16187. }
  16188. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16189. // A boundary can only be followed by CRLF or by "--", so anything else is
  16190. // malformed no matter what comes next. The parser must say so right away
  16191. // instead of buffering the rest of the declared body.
  16192. Server svr;
  16193. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16194. res.set_content("ok", "text/plain");
  16195. });
  16196. auto port = svr.bind_to_any_port(HOST);
  16197. thread t = thread([&] { svr.listen_after_bind(); });
  16198. auto se = detail::scope_exit([&] {
  16199. svr.stop();
  16200. t.join();
  16201. ASSERT_FALSE(svr.is_running());
  16202. });
  16203. svr.wait_until_ready();
  16204. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16205. // buffers instead of failing would still be waiting for the remaining bytes.
  16206. const std::string body = "--zzzz\r\n"
  16207. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16208. "\r\n"
  16209. "text1"
  16210. "\r\n--zzzzXX";
  16211. const std::string req = "POST /post HTTP/1.1\r\n"
  16212. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16213. "Content-Length: 1048576\r\n"
  16214. "\r\n" +
  16215. body;
  16216. std::string response;
  16217. ASSERT_TRUE(send_request(3, req, &response, port));
  16218. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16219. EXPECT_EQ("400", response.substr(9, 3));
  16220. }
  16221. // Posts a multipart body split into two writes, so that the server sees the
  16222. // split at whatever offset the caller chose, and expects the single "text1"
  16223. // field to come through.
  16224. static void expect_split_multipart_ok(const std::string &body1,
  16225. const std::string &body2) {
  16226. auto handled = false;
  16227. Server svr;
  16228. svr.Post("/post", [&](const Request &req, Response &) {
  16229. EXPECT_EQ(1u, req.form.fields.size());
  16230. EXPECT_EQ("text1", req.form.get_field("text1"));
  16231. handled = true;
  16232. });
  16233. auto port = svr.bind_to_any_port(HOST);
  16234. thread t = thread([&] { svr.listen_after_bind(); });
  16235. auto se = detail::scope_exit([&] {
  16236. svr.stop();
  16237. t.join();
  16238. ASSERT_FALSE(svr.is_running());
  16239. ASSERT_TRUE(handled);
  16240. });
  16241. svr.wait_until_ready();
  16242. // "Connection: close" makes the server close once it has answered, so the
  16243. // response drain ends immediately instead of idling until the read timeout.
  16244. const std::string head =
  16245. "POST /post HTTP/1.1\r\n"
  16246. "Host: localhost\r\n"
  16247. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16248. "Connection: close\r\n"
  16249. "Content-Length: " +
  16250. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16251. std::string response;
  16252. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16253. ASSERT_GE(response.size(), 12u) << "no response";
  16254. EXPECT_EQ("200", response.substr(9, 3));
  16255. }
  16256. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16257. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16258. // ignored, including when it does not arrive in the same read as the
  16259. // close-delimiter itself.
  16260. expect_split_multipart_ok("--zzzz\r\n"
  16261. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16262. "\r\n"
  16263. "text1"
  16264. "\r\n--zzzz--",
  16265. "\r\nthis epilogue must be ignored\r\n");
  16266. }
  16267. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16268. // The initial boundary may be preceded by a preamble of any length and may
  16269. // straddle a read boundary. Discarding data while waiting for it must not
  16270. // throw away a partial boundary sitting at the end of the buffer.
  16271. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16272. "zz\r\n"
  16273. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16274. "\r\n"
  16275. "text1"
  16276. "\r\n--zzzz--\r\n");
  16277. }
  16278. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16279. // The received boundary was only checked for being non-empty, so it could be
  16280. // as long as a header is allowed to be. The parser scans the body for
  16281. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16282. // costs a nearly full comparison at nearly every position, making the
  16283. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16284. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16285. Server svr;
  16286. svr.Post("/post", [](const Request &req, Response &res) {
  16287. EXPECT_EQ(1u, req.form.fields.size());
  16288. EXPECT_EQ("text1", req.form.get_field("text1"));
  16289. res.set_content("ok", "text/plain");
  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. });
  16298. svr.wait_until_ready();
  16299. Client cli(HOST, port);
  16300. auto post_with_boundary_of_length = [&](size_t len) {
  16301. const std::string boundary(len, 'a');
  16302. const std::string body =
  16303. "--" + boundary +
  16304. "\r\n"
  16305. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16306. "\r\n"
  16307. "text1"
  16308. "\r\n--" +
  16309. boundary + "--\r\n";
  16310. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16311. };
  16312. auto res = post_with_boundary_of_length(70);
  16313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16314. EXPECT_EQ(StatusCode::OK_200, res->status);
  16315. res = post_with_boundary_of_length(71);
  16316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16317. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16318. }
  16319. TEST(MakeFileBodyTest, Basic) {
  16320. const std::string file_content(4096, 'Z');
  16321. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16322. {
  16323. std::ofstream ofs(tmp_path, std::ios::binary);
  16324. ofs.write(file_content.data(),
  16325. static_cast<std::streamsize>(file_content.size()));
  16326. }
  16327. auto handled = false;
  16328. Server svr;
  16329. svr.Post("/upload", [&](const Request &req, Response &res) {
  16330. EXPECT_EQ(file_content, req.body);
  16331. handled = true;
  16332. res.status = StatusCode::OK_200;
  16333. });
  16334. auto port = svr.bind_to_any_port(HOST);
  16335. auto t = thread([&] { svr.listen_after_bind(); });
  16336. auto se = detail::scope_exit([&] {
  16337. svr.stop();
  16338. t.join();
  16339. ASSERT_FALSE(svr.is_running());
  16340. ASSERT_TRUE(handled);
  16341. std::remove(tmp_path.c_str());
  16342. });
  16343. svr.wait_until_ready();
  16344. auto fb = make_file_body(tmp_path);
  16345. ASSERT_GT(fb.first, 0u);
  16346. Client cli(HOST, port);
  16347. auto res =
  16348. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16350. EXPECT_EQ(StatusCode::OK_200, res->status);
  16351. }
  16352. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16353. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16354. {
  16355. std::ofstream ofs(path, std::ios::binary);
  16356. const std::string content(100, 'A');
  16357. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16358. }
  16359. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16360. auto body = make_file_body(path);
  16361. ASSERT_EQ(100u, body.first);
  16362. ASSERT_TRUE(static_cast<bool>(body.second));
  16363. // Rewritten shorter after its length was measured - and, on a server, after
  16364. // that length has already gone out as Content-Length.
  16365. {
  16366. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16367. const std::string content(10, 'A');
  16368. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16369. }
  16370. std::string written;
  16371. DataSink sink;
  16372. sink.write = [&](const char *d, size_t l) {
  16373. written.append(d, l);
  16374. return true;
  16375. };
  16376. // The provider has to report failure. write_content_with_progress() advances
  16377. // its offset only by what was written, so a provider that returns true
  16378. // without completing the length it promised is called again straight away,
  16379. // and again.
  16380. EXPECT_FALSE(body.second(0, body.first, sink));
  16381. EXPECT_EQ(std::string(10, 'A'), written);
  16382. }
  16383. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16384. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16385. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16386. {
  16387. std::ofstream ofs(path, std::ios::binary);
  16388. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16389. }
  16390. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16391. auto body = make_file_body(path);
  16392. ASSERT_EQ(content.size(), body.first);
  16393. ASSERT_TRUE(static_cast<bool>(body.second));
  16394. std::string written;
  16395. DataSink sink;
  16396. sink.write = [&](const char *d, size_t l) {
  16397. written.append(d, l);
  16398. return true;
  16399. };
  16400. EXPECT_TRUE(body.second(0, body.first, sink));
  16401. EXPECT_EQ(content, written);
  16402. }
  16403. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16404. static constexpr unsigned int number_of_tasks{1000000};
  16405. std::atomic_uint count{0};
  16406. std::unique_ptr<TaskQueue> task_queue{
  16407. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16408. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16409. auto queued = task_queue->enqueue(
  16410. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16411. EXPECT_TRUE(queued);
  16412. }
  16413. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16414. task_queue->shutdown();
  16415. #else
  16416. EXPECT_NO_THROW(task_queue->shutdown());
  16417. #endif
  16418. EXPECT_EQ(number_of_tasks, count.load());
  16419. }
  16420. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16421. static constexpr unsigned int number_of_tasks{1000000};
  16422. static constexpr unsigned int qlimit{2};
  16423. unsigned int queued_count{0};
  16424. std::atomic_uint count{0};
  16425. std::unique_ptr<TaskQueue> task_queue{
  16426. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16427. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16428. if (task_queue->enqueue(
  16429. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16430. queued_count++;
  16431. }
  16432. }
  16433. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16434. task_queue->shutdown();
  16435. #else
  16436. EXPECT_NO_THROW(task_queue->shutdown());
  16437. #endif
  16438. EXPECT_EQ(queued_count, count.load());
  16439. EXPECT_TRUE(queued_count <= number_of_tasks);
  16440. EXPECT_TRUE(queued_count >= qlimit);
  16441. }
  16442. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16443. // Use a short idle timeout so a dynamic thread spawns, times out and
  16444. // exits during the test, and the pool keeps working afterwards.
  16445. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16446. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16447. /*idle_timeout_sec=*/1}};
  16448. std::atomic_uint count{0};
  16449. std::condition_variable cv;
  16450. std::mutex mtx;
  16451. bool release = false;
  16452. // Block the base thread so the second task spawns a dynamic thread.
  16453. EXPECT_TRUE(task_queue->enqueue([&] {
  16454. std::unique_lock<std::mutex> lock(mtx);
  16455. while (!release) {
  16456. cv.wait(lock);
  16457. }
  16458. count++;
  16459. }));
  16460. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16461. // Let the dynamic thread finish its task and exceed the idle timeout.
  16462. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16463. {
  16464. std::unique_lock<std::mutex> lock(mtx);
  16465. release = true;
  16466. }
  16467. cv.notify_all();
  16468. // The pool must still accept and run tasks after the dynamic thread exited.
  16469. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16470. task_queue->shutdown();
  16471. EXPECT_EQ(3u, count.load());
  16472. }
  16473. TEST(TaskQueueTest, MaxQueuedRequests) {
  16474. static constexpr unsigned int qlimit{3};
  16475. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16476. std::condition_variable sem_cv;
  16477. std::mutex sem_mtx;
  16478. int credits = 0;
  16479. bool queued;
  16480. /* Fill up the queue with tasks that will block until we give them credits to
  16481. * complete. */
  16482. for (unsigned int n = 0; n <= qlimit;) {
  16483. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16484. std::unique_lock<std::mutex> lock(sem_mtx);
  16485. while (credits <= 0) {
  16486. sem_cv.wait(lock);
  16487. }
  16488. /* Consume the credit and signal the test code if they are all gone. */
  16489. if (--credits == 0) { sem_cv.notify_one(); }
  16490. });
  16491. if (n < qlimit) {
  16492. /* The first qlimit enqueues must succeed. */
  16493. EXPECT_TRUE(queued);
  16494. } else {
  16495. /* The last one will succeed only when the worker thread
  16496. * starts and dequeues the first blocking task. Although
  16497. * not necessary for the correctness of this test, we sleep for
  16498. * a short while to avoid busy waiting. */
  16499. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16500. }
  16501. if (queued) { n++; }
  16502. }
  16503. /* Further enqueues must fail since the queue is full. */
  16504. for (auto i = 0; i < 4; i++) {
  16505. queued = task_queue->enqueue([] {});
  16506. EXPECT_FALSE(queued);
  16507. }
  16508. /* Give the credits to allow the previous tasks to complete. */
  16509. {
  16510. std::unique_lock<std::mutex> lock(sem_mtx);
  16511. credits += qlimit + 1;
  16512. }
  16513. sem_cv.notify_all();
  16514. /* Wait for all the credits to be consumed. */
  16515. {
  16516. std::unique_lock<std::mutex> lock(sem_mtx);
  16517. while (credits > 0) {
  16518. sem_cv.wait(lock);
  16519. }
  16520. }
  16521. /* Check that we are able again to enqueue at least qlimit tasks. */
  16522. for (unsigned int i = 0; i < qlimit; i++) {
  16523. queued = task_queue->enqueue([] {});
  16524. EXPECT_TRUE(queued);
  16525. }
  16526. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16527. task_queue->shutdown();
  16528. #else
  16529. EXPECT_NO_THROW(task_queue->shutdown());
  16530. #endif
  16531. }
  16532. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16533. Server svr;
  16534. std::string method;
  16535. std::string body;
  16536. auto has_content_length = false;
  16537. auto has_transfer_encoding = false;
  16538. std::atomic<int> bad_requests{0};
  16539. // Leftover body bytes get parsed as a malformed request and answered with
  16540. // 400
  16541. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16542. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16543. });
  16544. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16545. res.set_redirect("/down", StatusCode::SeeOther_303);
  16546. });
  16547. svr.Get("/down", [&](const Request &req, Response &res) {
  16548. method = req.method;
  16549. body = req.body;
  16550. has_content_length = req.has_header("Content-Length");
  16551. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16552. res.set_content("ok", "text/plain");
  16553. });
  16554. auto port = svr.bind_to_any_port(HOST);
  16555. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16556. auto se = detail::scope_exit([&] {
  16557. svr.stop();
  16558. thread.join();
  16559. ASSERT_FALSE(svr.is_running());
  16560. });
  16561. svr.wait_until_ready();
  16562. const std::string payload = "SECRET-BODY";
  16563. auto check = [&](Client &cli, const Result &res) {
  16564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16565. EXPECT_EQ(StatusCode::OK_200, res->status);
  16566. EXPECT_EQ("ok", res->body);
  16567. EXPECT_EQ("GET", method);
  16568. EXPECT_TRUE(body.empty());
  16569. EXPECT_FALSE(has_content_length);
  16570. EXPECT_FALSE(has_transfer_encoding);
  16571. // Nothing of the original body may be left on the connection
  16572. auto res2 = cli.Get("/down");
  16573. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16574. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16575. EXPECT_EQ("ok", res2->body);
  16576. EXPECT_EQ(0, bad_requests);
  16577. };
  16578. // With content length
  16579. {
  16580. Client cli(HOST, port);
  16581. cli.set_keep_alive(true);
  16582. cli.set_follow_location(true);
  16583. auto res = cli.Post(
  16584. "/up", payload.size(),
  16585. [&](size_t offset, size_t length, DataSink &sink) {
  16586. return sink.write(payload.data() + offset, length);
  16587. },
  16588. "text/plain");
  16589. check(cli, res);
  16590. }
  16591. // Without content length (chunked)
  16592. {
  16593. Client cli(HOST, port);
  16594. cli.set_keep_alive(true);
  16595. cli.set_follow_location(true);
  16596. auto res = cli.Post(
  16597. "/up",
  16598. [&](size_t /*offset*/, DataSink &sink) {
  16599. sink.write(payload.data(), payload.size());
  16600. sink.done();
  16601. return true;
  16602. },
  16603. "text/plain");
  16604. check(cli, res);
  16605. }
  16606. }
  16607. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16608. Server svr;
  16609. std::string target;
  16610. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16611. // Echo the still-encoded name back in the Location
  16612. const std::string prefix = "/start/";
  16613. res.status = StatusCode::Found_302;
  16614. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16615. });
  16616. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16617. target = req.target;
  16618. res.set_content("ok", "text/plain");
  16619. });
  16620. auto port = svr.bind_to_any_port(HOST);
  16621. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16622. auto se = detail::scope_exit([&] {
  16623. svr.stop();
  16624. thread.join();
  16625. ASSERT_FALSE(svr.is_running());
  16626. });
  16627. svr.wait_until_ready();
  16628. // Decoding the Location path would turn the first four into a path
  16629. // separator, a query delimiter, a fragment delimiter and a different
  16630. // percent-encoded octet. The rest must keep reaching the server as they are.
  16631. const std::vector<std::string> names = {
  16632. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16633. };
  16634. for (auto path_encode : {true, false}) {
  16635. Client cli(HOST, port);
  16636. cli.set_follow_location(true);
  16637. cli.set_path_encode(path_encode);
  16638. for (const auto &name : names) {
  16639. target.clear();
  16640. auto res = cli.Get("/start/" + name);
  16641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16642. EXPECT_EQ(StatusCode::OK_200, res->status);
  16643. EXPECT_EQ("/dest/" + name, target);
  16644. }
  16645. }
  16646. }
  16647. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16648. Server svr;
  16649. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16650. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16651. });
  16652. svr.Get("/hello", [](const Request &req, Response &res) {
  16653. res.set_content(req.get_param_value("key"), "text/plain");
  16654. });
  16655. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16656. auto se = detail::scope_exit([&] {
  16657. svr.stop();
  16658. thread.join();
  16659. ASSERT_FALSE(svr.is_running());
  16660. });
  16661. svr.wait_until_ready();
  16662. {
  16663. Client cli(HOST, PORT);
  16664. cli.set_follow_location(true);
  16665. auto res = cli.Get("/");
  16666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16667. EXPECT_EQ(StatusCode::OK_200, res->status);
  16668. EXPECT_EQ("val&key2=val2", res->body);
  16669. }
  16670. }
  16671. #endif
  16672. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16673. Server svr;
  16674. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16675. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16676. });
  16677. svr.Get("/hello", [](const Request &req, Response &res) {
  16678. res.set_content(req.get_param_value("key"), "text/plain");
  16679. });
  16680. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16681. auto se = detail::scope_exit([&] {
  16682. svr.stop();
  16683. thread.join();
  16684. ASSERT_FALSE(svr.is_running());
  16685. });
  16686. svr.wait_until_ready();
  16687. {
  16688. Client cli(HOST, PORT);
  16689. cli.set_follow_location(true);
  16690. auto res = cli.Get("/");
  16691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16692. EXPECT_EQ(StatusCode::OK_200, res->status);
  16693. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16694. }
  16695. }
  16696. TEST(RedirectTest, RedirectWithPlusInPath) {
  16697. Server svr;
  16698. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16699. res.set_redirect("/a+b");
  16700. });
  16701. // Route pattern uses regex; escape + as \\+
  16702. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16703. res.set_content(req.path, "text/plain");
  16704. });
  16705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16706. auto se = detail::scope_exit([&] {
  16707. svr.stop();
  16708. thread.join();
  16709. ASSERT_FALSE(svr.is_running());
  16710. });
  16711. svr.wait_until_ready();
  16712. {
  16713. Client cli(HOST, PORT);
  16714. cli.set_follow_location(true);
  16715. auto res = cli.Get("/");
  16716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16717. EXPECT_EQ(StatusCode::OK_200, res->status);
  16718. EXPECT_EQ("/a+b", res->body);
  16719. }
  16720. }
  16721. TEST(RedirectTest, ResolveRelativeLocation) {
  16722. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16723. const std::vector<std::pair<std::string, std::string>> cases = {
  16724. {"g", "/b/c/g"},
  16725. {"./g", "/b/c/g"},
  16726. {"g/", "/b/c/g/"},
  16727. {"?y", "/b/c/d;p?y"},
  16728. {"g?y", "/b/c/g?y"},
  16729. {"#s", "/b/c/d;p?q#s"},
  16730. {"g#s", "/b/c/g#s"},
  16731. {"g?y#s", "/b/c/g?y#s"},
  16732. {";x", "/b/c/;x"},
  16733. {"g;x", "/b/c/g;x"},
  16734. {".", "/b/c/"},
  16735. {"./", "/b/c/"},
  16736. {"..", "/b/"},
  16737. {"../", "/b/"},
  16738. {"../g", "/b/g"},
  16739. {"../..", "/"},
  16740. {"../../", "/"},
  16741. {"../../g", "/g"},
  16742. {"../../../g", "/g"},
  16743. {"g.", "/b/c/g."},
  16744. {".g", "/b/c/.g"},
  16745. {"g..", "/b/c/g.."},
  16746. {"..g", "/b/c/..g"},
  16747. {"./../g", "/b/g"},
  16748. {"./g/.", "/b/c/g/"},
  16749. {"g/./h", "/b/c/g/h"},
  16750. {"g/../h", "/b/c/h"},
  16751. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16752. {"g;x=1/../y", "/b/c/y"},
  16753. {"g?y/./x", "/b/c/g?y/./x"},
  16754. {"g#s/../x", "/b/c/g#s/../x"},
  16755. // Not relative-path references, so left for parse_url.
  16756. {"/g", "/g"},
  16757. {"//g", "//g"},
  16758. {"http://g/x", "http://g/x"},
  16759. {"g:h", "g:h"},
  16760. };
  16761. for (const auto &c : cases) {
  16762. EXPECT_EQ(c.second,
  16763. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16764. << c.first;
  16765. }
  16766. }
  16767. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16768. Server svr;
  16769. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16770. res.set_redirect(req.get_param_value("to"));
  16771. });
  16772. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16773. res.set_content(req.target, "text/plain");
  16774. });
  16775. svr.Get("/other", [](const Request &req, Response &res) {
  16776. res.set_content(req.target, "text/plain");
  16777. });
  16778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16779. auto se = detail::scope_exit([&] {
  16780. svr.stop();
  16781. thread.join();
  16782. ASSERT_FALSE(svr.is_running());
  16783. });
  16784. svr.wait_until_ready();
  16785. const std::vector<std::pair<std::string, std::string>> cases = {
  16786. {"next", "/dir/next"},
  16787. {"./next?x=1", "/dir/next?x=1"},
  16788. {"../other", "/other"},
  16789. };
  16790. for (const auto &c : cases) {
  16791. Client cli(HOST, PORT);
  16792. cli.set_follow_location(true);
  16793. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16794. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16795. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16796. EXPECT_EQ(c.second, res->body) << c.first;
  16797. }
  16798. }
  16799. #ifdef CPPHTTPLIB_SSL_ENABLED
  16800. TEST(RedirectTest, Issue2185_Online) {
  16801. SSLClient client("github.com");
  16802. client.set_follow_location(true);
  16803. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16804. "Coollab-Windows.zip");
  16805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16806. EXPECT_EQ(StatusCode::OK_200, res->status);
  16807. EXPECT_EQ(9920427U, res->body.size());
  16808. }
  16809. #endif
  16810. TEST(VulnerabilityTest, CRLFInjection) {
  16811. Server svr;
  16812. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16813. res.set_content("Hello 1", "text/plain");
  16814. });
  16815. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16816. res.set_content("Hello 2", "text/plain");
  16817. });
  16818. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16819. res.set_content("Hello 3", "text/plain");
  16820. });
  16821. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16822. res.set_content("Hello 4", "text/plain");
  16823. });
  16824. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16825. for (const auto &x : req.headers) {
  16826. auto key = x.first;
  16827. EXPECT_STRNE("evil", key.c_str());
  16828. }
  16829. });
  16830. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16831. auto se = detail::scope_exit([&] {
  16832. svr.stop();
  16833. thread.join();
  16834. ASSERT_FALSE(svr.is_running());
  16835. });
  16836. svr.wait_until_ready();
  16837. {
  16838. Client cli(HOST, PORT);
  16839. cli.Post("/test1", "A=B",
  16840. "application/x-www-form-urlencoded\r\nevil: hello1");
  16841. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16842. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16843. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16844. }
  16845. }
  16846. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16847. auto server_thread = std::thread([] {
  16848. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16849. default_socket_options(srv);
  16850. sockaddr_in addr{};
  16851. addr.sin_family = AF_INET;
  16852. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16853. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16854. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16855. ::listen(srv, 1);
  16856. sockaddr_in cli_addr{};
  16857. socklen_t cli_len = sizeof(cli_addr);
  16858. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16859. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16860. std::string buf_all;
  16861. char buf[2048];
  16862. ssize_t n;
  16863. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16864. buf_all.append(buf, static_cast<size_t>(n));
  16865. size_t pos;
  16866. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16867. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16868. auto e = request_block.find("\r\n");
  16869. if (e != std::string::npos) {
  16870. auto request_line = request_block.substr(0, e);
  16871. std::string msg =
  16872. "CRLF injection detected in request line: '" + request_line + "'";
  16873. EXPECT_FALSE(true) << msg;
  16874. }
  16875. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16876. ::send(cli,
  16877. #ifdef _WIN32
  16878. static_cast<const char *>(resp.c_str()),
  16879. static_cast<int>(resp.size()),
  16880. #else
  16881. resp.c_str(), resp.size(),
  16882. #endif
  16883. 0);
  16884. buf_all.erase(0, pos + 4);
  16885. }
  16886. }
  16887. detail::close_socket(cli);
  16888. detail::close_socket(srv);
  16889. });
  16890. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16891. auto cli = Client("127.0.0.1", PORT + 1);
  16892. auto headers = Headers{
  16893. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16894. {"Connection", "keep-alive"}};
  16895. auto res = cli.Get("/hi", headers);
  16896. EXPECT_FALSE(res);
  16897. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16898. server_thread.join();
  16899. }
  16900. // A request rejected before any byte reaches the socket must fail right away
  16901. // instead of waiting for a response the server will never send.
  16902. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16903. // The kernel completes the TCP handshake from the listen backlog, so the
  16904. // client connects, but nothing ever reads, responds or closes.
  16905. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16906. default_socket_options(srv);
  16907. sockaddr_in addr{};
  16908. addr.sin_family = AF_INET;
  16909. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16910. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16911. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16912. ASSERT_EQ(0, ::listen(srv, 8));
  16913. auto cli = Client("127.0.0.1", PORT + 1);
  16914. cli.set_read_timeout(10, 0);
  16915. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16916. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16917. std::chrono::steady_clock::now() - start)
  16918. .count();
  16919. };
  16920. {
  16921. Request req;
  16922. req.method = "GE T";
  16923. req.path = "/";
  16924. auto start = std::chrono::steady_clock::now();
  16925. auto res = cli.send(req);
  16926. EXPECT_FALSE(res);
  16927. EXPECT_EQ(Error::Write, res.error());
  16928. EXPECT_LT(elapsed_ms(start), 1000);
  16929. }
  16930. {
  16931. auto start = std::chrono::steady_clock::now();
  16932. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16933. EXPECT_FALSE(res);
  16934. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16935. EXPECT_LT(elapsed_ms(start), 1000);
  16936. }
  16937. EXPECT_FALSE(cli.is_socket_open());
  16938. detail::close_socket(srv);
  16939. }
  16940. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16941. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16942. default_socket_options(srv);
  16943. sockaddr_in addr{};
  16944. addr.sin_family = AF_INET;
  16945. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16946. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16947. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16948. ASSERT_EQ(0, ::listen(srv, 1));
  16949. std::string received;
  16950. auto server_thread = std::thread([&] {
  16951. auto sock = ::accept(srv, nullptr, nullptr);
  16952. if (sock == INVALID_SOCKET) { return; }
  16953. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16954. char buf[2048];
  16955. ssize_t n;
  16956. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16957. received.append(buf, static_cast<size_t>(n));
  16958. }
  16959. detail::close_socket(sock);
  16960. });
  16961. {
  16962. auto cli = Client("127.0.0.1", PORT + 1);
  16963. // "Z" sorts after the default headers, so writing straight to the socket
  16964. // would have sent the request line and those headers before the rejection.
  16965. auto handle =
  16966. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16967. EXPECT_FALSE(handle.is_valid());
  16968. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16969. }
  16970. server_thread.join();
  16971. detail::close_socket(srv);
  16972. EXPECT_TRUE(received.empty()) << received;
  16973. }
  16974. TEST(PathParamsTest, StaticMatch) {
  16975. const auto pattern = "/users/all";
  16976. detail::PathParamsMatcher matcher(pattern);
  16977. Request request;
  16978. request.path = "/users/all";
  16979. ASSERT_TRUE(matcher.match(request));
  16980. std::unordered_map<std::string, std::string> expected_params = {};
  16981. EXPECT_EQ(request.path_params, expected_params);
  16982. }
  16983. TEST(PathParamsTest, StaticMismatch) {
  16984. const auto pattern = "/users/all";
  16985. detail::PathParamsMatcher matcher(pattern);
  16986. Request request;
  16987. request.path = "/users/1";
  16988. ASSERT_FALSE(matcher.match(request));
  16989. }
  16990. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16991. const auto pattern = "/users/:id/subscriptions";
  16992. detail::PathParamsMatcher matcher(pattern);
  16993. Request request;
  16994. request.path = "/users/42/subscriptions";
  16995. ASSERT_TRUE(matcher.match(request));
  16996. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16997. EXPECT_EQ(request.path_params, expected_params);
  16998. }
  16999. TEST(PathParamsTest, SingleParamInTheEnd) {
  17000. const auto pattern = "/users/:id";
  17001. detail::PathParamsMatcher matcher(pattern);
  17002. Request request;
  17003. request.path = "/users/24";
  17004. ASSERT_TRUE(matcher.match(request));
  17005. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17006. EXPECT_EQ(request.path_params, expected_params);
  17007. }
  17008. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17009. const auto pattern = "/users/:id/";
  17010. detail::PathParamsMatcher matcher(pattern);
  17011. Request request;
  17012. request.path = "/users/42/";
  17013. ASSERT_TRUE(matcher.match(request));
  17014. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17015. EXPECT_EQ(request.path_params, expected_params);
  17016. }
  17017. TEST(PathParamsTest, EmptyParam) {
  17018. const auto pattern = "/users/:id/";
  17019. detail::PathParamsMatcher matcher(pattern);
  17020. Request request;
  17021. request.path = "/users//";
  17022. ASSERT_TRUE(matcher.match(request));
  17023. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17024. EXPECT_EQ(request.path_params, expected_params);
  17025. }
  17026. TEST(PathParamsTest, FragmentMismatch) {
  17027. const auto pattern = "/users/:id/";
  17028. detail::PathParamsMatcher matcher(pattern);
  17029. Request request;
  17030. request.path = "/admins/24/";
  17031. ASSERT_FALSE(matcher.match(request));
  17032. }
  17033. TEST(PathParamsTest, ExtraFragments) {
  17034. const auto pattern = "/users/:id";
  17035. detail::PathParamsMatcher matcher(pattern);
  17036. Request request;
  17037. request.path = "/users/42/subscriptions";
  17038. ASSERT_FALSE(matcher.match(request));
  17039. }
  17040. TEST(PathParamsTest, MissingTrailingParam) {
  17041. const auto pattern = "/users/:id";
  17042. detail::PathParamsMatcher matcher(pattern);
  17043. Request request;
  17044. request.path = "/users";
  17045. ASSERT_FALSE(matcher.match(request));
  17046. }
  17047. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17048. const auto pattern = "/users/:id/subscriptions";
  17049. detail::PathParamsMatcher matcher(pattern);
  17050. Request request;
  17051. request.path = "/users/subscriptions";
  17052. ASSERT_FALSE(matcher.match(request));
  17053. }
  17054. TEST(PathParamsTest, MultipleParams) {
  17055. const auto pattern = "/users/:userid/subscriptions/:subid";
  17056. detail::PathParamsMatcher matcher(pattern);
  17057. Request request;
  17058. request.path = "/users/42/subscriptions/2";
  17059. ASSERT_TRUE(matcher.match(request));
  17060. std::unordered_map<std::string, std::string> expected_params = {
  17061. {"userid", "42"}, {"subid", "2"}};
  17062. EXPECT_EQ(request.path_params, expected_params);
  17063. }
  17064. TEST(PathParamsTest, SequenceOfParams) {
  17065. const auto pattern = "/values/:x/:y/:z";
  17066. detail::PathParamsMatcher matcher(pattern);
  17067. Request request;
  17068. request.path = "/values/1/2/3";
  17069. ASSERT_TRUE(matcher.match(request));
  17070. std::unordered_map<std::string, std::string> expected_params = {
  17071. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17072. EXPECT_EQ(request.path_params, expected_params);
  17073. }
  17074. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17075. const auto pattern = "/prefix:suffix";
  17076. detail::PathParamsMatcher matcher(pattern);
  17077. Request request;
  17078. request.path = "/prefix:suffix";
  17079. ASSERT_TRUE(matcher.match(request));
  17080. const std::unordered_map<std::string, std::string> expected_params = {};
  17081. EXPECT_EQ(request.path_params, expected_params);
  17082. }
  17083. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17084. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17085. // calling thread's stack on a long enough path for a quantified pattern;
  17086. // RegexMatcher must refuse to run regex matching on paths beyond
  17087. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17088. detail::RegexMatcher matcher("/files/(.*)");
  17089. Request within_limit;
  17090. within_limit.path = "/files/" + std::string(10, 'A');
  17091. EXPECT_TRUE(matcher.match(within_limit));
  17092. Request over_limit;
  17093. over_limit.path =
  17094. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17095. EXPECT_FALSE(matcher.match(over_limit));
  17096. }
  17097. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17098. Server svr;
  17099. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17100. res.set_content("ok", "text/plain");
  17101. });
  17102. auto port = svr.bind_to_any_port(HOST);
  17103. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17104. auto se = detail::scope_exit([&] {
  17105. svr.stop();
  17106. thread.join();
  17107. ASSERT_FALSE(svr.is_running());
  17108. });
  17109. svr.wait_until_ready();
  17110. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17111. // request URI limit; this used to be able to crash the process.
  17112. std::string path =
  17113. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17114. std::string req = "GET " + path +
  17115. " HTTP/1.1\r\n"
  17116. "Host: " +
  17117. std::string(HOST) + ":" + std::to_string(port) +
  17118. "\r\n"
  17119. "Connection: close\r\n"
  17120. "\r\n";
  17121. std::string response;
  17122. ASSERT_TRUE(send_request(5, req, &response, port));
  17123. EXPECT_NE(std::string::npos, response.find("404"));
  17124. }
  17125. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17126. Server svr;
  17127. auto handler = [](const Request & /*req*/, Response &res) {
  17128. res.set_content("hit", "text/plain");
  17129. };
  17130. // No regex metacharacter, so this one is compared literally
  17131. svr.Get("/literal/route", handler);
  17132. // '.' is a regex metacharacter, so this one must keep regex semantics
  17133. svr.Get("/a.c", handler);
  17134. auto port = svr.bind_to_any_port(HOST);
  17135. std::thread t([&]() { svr.listen_after_bind(); });
  17136. auto se = detail::scope_exit([&] {
  17137. svr.stop();
  17138. t.join();
  17139. ASSERT_FALSE(svr.is_running());
  17140. });
  17141. svr.wait_until_ready();
  17142. Client cli(HOST, port);
  17143. struct {
  17144. const char *path;
  17145. int status;
  17146. } cases[] = {
  17147. {"/literal/route", StatusCode::OK_200},
  17148. {"/literal/routes", StatusCode::NotFound_404},
  17149. {"/literal/rout", StatusCode::NotFound_404},
  17150. {"/abc", StatusCode::OK_200},
  17151. {"/a.c", StatusCode::OK_200},
  17152. };
  17153. for (const auto &x : cases) {
  17154. auto res = cli.Get(x.path);
  17155. ASSERT_TRUE(res) << x.path;
  17156. EXPECT_EQ(x.status, res->status) << x.path;
  17157. }
  17158. }
  17159. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17160. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17161. // from exhausting the stack, so it must only constrain routes that actually
  17162. // run a regular expression. A literal route is matched by comparison and
  17163. // stays usable at any length.
  17164. Server svr;
  17165. const std::string pattern =
  17166. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17167. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17168. res.set_content("hit", "text/plain");
  17169. });
  17170. auto port = svr.bind_to_any_port(HOST);
  17171. std::thread t([&]() { svr.listen_after_bind(); });
  17172. auto se = detail::scope_exit([&] {
  17173. svr.stop();
  17174. t.join();
  17175. ASSERT_FALSE(svr.is_running());
  17176. });
  17177. svr.wait_until_ready();
  17178. Client cli(HOST, port);
  17179. auto res = cli.Get(pattern);
  17180. ASSERT_TRUE(res);
  17181. EXPECT_EQ(StatusCode::OK_200, res->status);
  17182. }
  17183. TEST(ParseUrlTest, VariousPatterns) {
  17184. {
  17185. detail::UrlComponents uc;
  17186. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17187. EXPECT_EQ("http", uc.scheme);
  17188. EXPECT_EQ("example.com", uc.host);
  17189. EXPECT_EQ("8080", uc.port);
  17190. EXPECT_EQ("/path", uc.path);
  17191. EXPECT_EQ("?q=1", uc.query);
  17192. }
  17193. {
  17194. detail::UrlComponents uc;
  17195. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17196. EXPECT_EQ("https", uc.scheme);
  17197. EXPECT_EQ("example.com", uc.host);
  17198. EXPECT_TRUE(uc.port.empty());
  17199. EXPECT_EQ("/path", uc.path);
  17200. }
  17201. {
  17202. detail::UrlComponents uc;
  17203. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17204. EXPECT_EQ("::1", uc.host);
  17205. EXPECT_EQ("8080", uc.port);
  17206. EXPECT_EQ("/path", uc.path);
  17207. }
  17208. {
  17209. detail::UrlComponents uc;
  17210. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17211. }
  17212. {
  17213. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17214. // the path while the connection still targets the bracketed host.
  17215. detail::UrlComponents uc;
  17216. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17217. }
  17218. {
  17219. detail::UrlComponents uc;
  17220. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17221. }
  17222. {
  17223. detail::UrlComponents uc;
  17224. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17225. EXPECT_EQ("::1", uc.host);
  17226. EXPECT_TRUE(uc.port.empty());
  17227. EXPECT_EQ("/path", uc.path);
  17228. }
  17229. {
  17230. detail::UrlComponents uc;
  17231. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17232. EXPECT_TRUE(uc.scheme.empty());
  17233. EXPECT_EQ("example.com", uc.host);
  17234. EXPECT_EQ("/path", uc.path);
  17235. EXPECT_EQ("?q=1", uc.query);
  17236. }
  17237. {
  17238. detail::UrlComponents uc;
  17239. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17240. EXPECT_TRUE(uc.host.empty());
  17241. EXPECT_EQ("/path", uc.path);
  17242. EXPECT_EQ("?q=1", uc.query);
  17243. }
  17244. {
  17245. detail::UrlComponents uc;
  17246. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17247. EXPECT_EQ("example.com", uc.host);
  17248. EXPECT_EQ("8080", uc.port);
  17249. }
  17250. {
  17251. // Unix socket path — must not be parsed as host
  17252. detail::UrlComponents uc;
  17253. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17254. EXPECT_TRUE(uc.host.empty());
  17255. }
  17256. {
  17257. detail::UrlComponents uc;
  17258. ASSERT_TRUE(detail::parse_url("", uc));
  17259. EXPECT_TRUE(uc.host.empty());
  17260. EXPECT_TRUE(uc.path.empty());
  17261. }
  17262. {
  17263. detail::UrlComponents uc;
  17264. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17265. }
  17266. {
  17267. detail::UrlComponents uc;
  17268. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17269. }
  17270. {
  17271. // Accepted by parse_url; callers restrict to http/https
  17272. detail::UrlComponents uc;
  17273. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17274. EXPECT_EQ("ftp", uc.scheme);
  17275. }
  17276. {
  17277. detail::UrlComponents uc;
  17278. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17279. }
  17280. {
  17281. detail::UrlComponents uc;
  17282. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17283. }
  17284. }
  17285. TEST(ParseUrlTest, FragmentHandling) {
  17286. {
  17287. detail::UrlComponents uc;
  17288. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17289. EXPECT_EQ("/path", uc.path);
  17290. EXPECT_TRUE(uc.query.empty());
  17291. }
  17292. {
  17293. detail::UrlComponents uc;
  17294. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17295. EXPECT_TRUE(uc.path.empty());
  17296. EXPECT_TRUE(uc.query.empty());
  17297. }
  17298. }
  17299. TEST(ParseUrlTest, UserinfoHandling) {
  17300. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17301. // parsers would see evil.com as the host.
  17302. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17303. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17304. for (auto url : urls) {
  17305. detail::UrlComponents uc;
  17306. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17307. }
  17308. }
  17309. TEST(ParseUrlTest, IPv6EdgeCases) {
  17310. {
  17311. detail::UrlComponents uc;
  17312. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17313. EXPECT_TRUE(uc.scheme.empty());
  17314. EXPECT_EQ("::1", uc.host);
  17315. EXPECT_EQ("8080", uc.port);
  17316. }
  17317. {
  17318. // Zone ID '%25' is not in [a-fA-F0-9:]
  17319. detail::UrlComponents uc;
  17320. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17321. }
  17322. }
  17323. TEST(ParseUrlTest, SchemeEdgeCases) {
  17324. {
  17325. detail::UrlComponents uc;
  17326. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17327. }
  17328. {
  17329. detail::UrlComponents uc;
  17330. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17331. }
  17332. {
  17333. detail::UrlComponents uc;
  17334. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17335. }
  17336. }
  17337. TEST(ParseUrlTest, PortEdgeCases) {
  17338. {
  17339. detail::UrlComponents uc;
  17340. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17341. EXPECT_TRUE(uc.port.empty());
  17342. EXPECT_EQ("/path", uc.path);
  17343. }
  17344. {
  17345. // parse_url accepts any port string; validation is done by parse_port
  17346. detail::UrlComponents uc;
  17347. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17348. EXPECT_EQ("abc", uc.port);
  17349. }
  17350. }
  17351. TEST(ParseUrlTest, WebSocketPatterns) {
  17352. {
  17353. detail::UrlComponents uc;
  17354. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17355. EXPECT_EQ("ws", uc.scheme);
  17356. EXPECT_EQ("echo.example.com", uc.host);
  17357. EXPECT_EQ("8080", uc.port);
  17358. EXPECT_EQ("/ws", uc.path);
  17359. }
  17360. {
  17361. detail::UrlComponents uc;
  17362. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17363. EXPECT_EQ("wss", uc.scheme);
  17364. EXPECT_EQ("echo.example.com", uc.host);
  17365. EXPECT_TRUE(uc.port.empty());
  17366. EXPECT_EQ("/ws", uc.path);
  17367. }
  17368. }
  17369. TEST(ParseUrlTest, QueryOnly) {
  17370. detail::UrlComponents uc;
  17371. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17372. EXPECT_TRUE(uc.host.empty());
  17373. EXPECT_TRUE(uc.path.empty());
  17374. EXPECT_EQ("?q=1&r=2", uc.query);
  17375. }
  17376. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17377. detail::UrlComponents uc;
  17378. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17379. EXPECT_TRUE(uc.scheme.empty());
  17380. EXPECT_EQ("example.com", uc.host);
  17381. EXPECT_EQ("443", uc.port);
  17382. EXPECT_EQ("/path", uc.path);
  17383. }
  17384. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17385. // If ipv6 regex working, regex match codepath is taken.
  17386. // else port will default to 80 in Client impl
  17387. int clientImplMagicPort = 80;
  17388. int port = 4321;
  17389. // above ports must be different to avoid false negative
  17390. EXPECT_NE(clientImplMagicPort, port);
  17391. std::string ipV6TestURL = "http://[ff06::c3]";
  17392. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17393. CLIENT_PRIVATE_KEY_FILE);
  17394. EXPECT_EQ(cli.port(), port);
  17395. }
  17396. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17397. auto file_path = "./www/dir/index.html";
  17398. auto dir_path = "./www/dir";
  17399. detail::FileStat stat_file(file_path);
  17400. EXPECT_TRUE(stat_file.is_file());
  17401. EXPECT_FALSE(stat_file.is_dir());
  17402. detail::FileStat stat_dir(dir_path);
  17403. EXPECT_FALSE(stat_dir.is_file());
  17404. EXPECT_TRUE(stat_dir.is_dir());
  17405. }
  17406. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17407. // IPv4 with default HTTP port (80)
  17408. EXPECT_EQ("example.com",
  17409. detail::make_host_and_port_string("example.com", 80, false));
  17410. // IPv4 with default HTTPS port (443)
  17411. EXPECT_EQ("example.com",
  17412. detail::make_host_and_port_string("example.com", 443, true));
  17413. // IPv4 with non-default HTTP port
  17414. EXPECT_EQ("example.com:8080",
  17415. detail::make_host_and_port_string("example.com", 8080, false));
  17416. // IPv4 with non-default HTTPS port
  17417. EXPECT_EQ("example.com:8443",
  17418. detail::make_host_and_port_string("example.com", 8443, true));
  17419. // IPv6 with default HTTP port (80)
  17420. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17421. // IPv6 with default HTTPS port (443)
  17422. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17423. // IPv6 with non-default HTTP port
  17424. EXPECT_EQ("[::1]:8080",
  17425. detail::make_host_and_port_string("::1", 8080, false));
  17426. // IPv6 with non-default HTTPS port
  17427. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17428. // IPv6 full address with default port
  17429. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17430. detail::make_host_and_port_string(
  17431. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17432. // IPv6 full address with non-default port
  17433. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17434. detail::make_host_and_port_string(
  17435. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17436. // IPv6 localhost with non-default port
  17437. EXPECT_EQ("[::1]:3000",
  17438. detail::make_host_and_port_string("::1", 3000, false));
  17439. // IPv6 with zone ID (link-local address) with default port
  17440. EXPECT_EQ("[fe80::1%eth0]",
  17441. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17442. // IPv6 with zone ID (link-local address) with non-default port
  17443. EXPECT_EQ("[fe80::1%eth0]:8080",
  17444. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17445. // Edge case: Port 443 with is_ssl=false (should add port)
  17446. EXPECT_EQ("example.com:443",
  17447. detail::make_host_and_port_string("example.com", 443, false));
  17448. // Edge case: Port 80 with is_ssl=true (should add port)
  17449. EXPECT_EQ("example.com:80",
  17450. detail::make_host_and_port_string("example.com", 80, true));
  17451. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17452. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17453. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17454. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17455. // Security fix: Already bracketed IPv6 should not get double brackets
  17456. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17457. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17458. EXPECT_EQ("[::1]:8080",
  17459. detail::make_host_and_port_string("[::1]", 8080, false));
  17460. EXPECT_EQ("[2001:db8::1]:8080",
  17461. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17462. EXPECT_EQ("[fe80::1%eth0]",
  17463. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17464. EXPECT_EQ("[fe80::1%eth0]:8080",
  17465. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17466. // Edge case: Empty host (should return as-is)
  17467. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17468. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17469. // This is a known limitation but shouldn't crash
  17470. EXPECT_EQ("[host:name]",
  17471. detail::make_host_and_port_string("host:name", 80, false));
  17472. // Port number edge cases (no validation, but should not crash)
  17473. EXPECT_EQ("example.com:0",
  17474. detail::make_host_and_port_string("example.com", 0, false));
  17475. EXPECT_EQ("example.com:-1",
  17476. detail::make_host_and_port_string("example.com", -1, false));
  17477. EXPECT_EQ("example.com:65535",
  17478. detail::make_host_and_port_string("example.com", 65535, false));
  17479. EXPECT_EQ("example.com:65536",
  17480. detail::make_host_and_port_string("example.com", 65536, false));
  17481. }
  17482. #ifdef CPPHTTPLIB_SSL_ENABLED
  17483. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17484. httplib::SSLClient cli("roblox.com", 443);
  17485. cli.set_follow_location(true);
  17486. auto res = cli.Get("/");
  17487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17488. EXPECT_EQ(StatusCode::OK_200, res->status);
  17489. }
  17490. #endif
  17491. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17492. Server svr;
  17493. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17494. EXPECT_EQ(res.status, 400);
  17495. });
  17496. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17497. auto se = detail::scope_exit([&] {
  17498. svr.stop();
  17499. thread.join();
  17500. ASSERT_FALSE(svr.is_running());
  17501. });
  17502. svr.wait_until_ready();
  17503. Client cli(HOST, PORT);
  17504. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17505. }
  17506. TEST(InvalidHeaderCharsTest, is_field_name) {
  17507. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17508. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17509. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17510. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17511. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17512. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17513. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17514. EXPECT_FALSE(detail::fields::is_field_name(""));
  17515. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17516. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17517. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17518. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17519. }
  17520. TEST(InvalidHeaderCharsTest, is_field_value) {
  17521. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17522. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17523. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17524. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17525. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17526. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17527. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17528. EXPECT_TRUE(detail::fields::is_field_value(""));
  17529. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17530. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17531. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17532. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17533. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17534. }
  17535. TEST(InvalidHeaderCharsTest, OnServer) {
  17536. Server svr;
  17537. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17538. std::string header = "Not Set";
  17539. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17540. res.set_header(header, "value");
  17541. res.set_content("Page Content Page Content", "text/plain");
  17542. });
  17543. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17544. std::string header = "Not Set";
  17545. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17546. res.set_header("X-Test", header);
  17547. res.set_content("Page Content Page Content", "text/plain");
  17548. });
  17549. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17550. auto se = detail::scope_exit([&] {
  17551. svr.stop();
  17552. thread.join();
  17553. ASSERT_FALSE(svr.is_running());
  17554. });
  17555. svr.wait_until_ready();
  17556. Client cli(HOST, PORT);
  17557. {
  17558. auto res = cli.Get(
  17559. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17561. EXPECT_EQ("Page Content Page Content", res->body);
  17562. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17563. }
  17564. {
  17565. auto res = cli.Get(
  17566. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17568. EXPECT_EQ("Page Content Page Content", res->body);
  17569. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17570. }
  17571. }
  17572. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17573. auto handled = false;
  17574. Server svr;
  17575. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17576. thread t = thread([&] { svr.listen(HOST, PORT); });
  17577. auto se = detail::scope_exit([&] {
  17578. svr.stop();
  17579. t.join();
  17580. ASSERT_FALSE(svr.is_running());
  17581. ASSERT_FALSE(handled);
  17582. });
  17583. svr.wait_until_ready();
  17584. auto req = "POST /test HTTP/1.1\r\n"
  17585. "Content-Length: x\r\n"
  17586. "\r\n";
  17587. std::string response;
  17588. ASSERT_TRUE(send_request(1, req, &response));
  17589. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17590. response.substr(0, response.find("\r\n")));
  17591. }
  17592. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17593. // case-insensitive, and a server that receives a 100-continue expectation in
  17594. // an HTTP/1.0 request MUST ignore it.
  17595. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17596. std::string response;
  17597. ASSERT_TRUE(send_request(1, req, &response, port));
  17598. *got_100 = response.find("100 Continue") != std::string::npos;
  17599. }
  17600. class ExpectTokenTest : public ::testing::Test {
  17601. protected:
  17602. void SetUp() override {
  17603. svr_.Post("/p", [](const Request &, Response &res) {
  17604. res.set_content("ok", "text/plain");
  17605. });
  17606. port_ = svr_.bind_to_any_port(HOST);
  17607. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17608. svr_.wait_until_ready();
  17609. }
  17610. void TearDown() override {
  17611. svr_.stop();
  17612. if (thread_.joinable()) { thread_.join(); }
  17613. }
  17614. std::string request(const char *version, const char *expect_value) const {
  17615. return std::string("POST /p ") + version +
  17616. "\r\n"
  17617. "Host: localhost\r\n"
  17618. "Content-Length: 2\r\n"
  17619. "Connection: close\r\n"
  17620. "Expect: " +
  17621. expect_value +
  17622. "\r\n"
  17623. "\r\n"
  17624. "hi";
  17625. }
  17626. Server svr_;
  17627. int port_ = 0;
  17628. thread thread_;
  17629. };
  17630. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17631. bool got_100 = false;
  17632. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17633. EXPECT_TRUE(got_100);
  17634. }
  17635. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17636. bool got_100 = true;
  17637. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17638. EXPECT_FALSE(got_100);
  17639. }
  17640. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17641. bool got_100 = false;
  17642. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17643. EXPECT_TRUE(got_100);
  17644. }
  17645. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17646. bool got_100 = false;
  17647. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17648. EXPECT_TRUE(got_100);
  17649. }
  17650. // `100 Continue` is sent only when the server starts reading the body, so a
  17651. // request rejected before that never invites the client to send it. The
  17652. // requests below carry the expectation but withhold the body, as a client
  17653. // waiting for `100 Continue` would.
  17654. // A POST that expects `100 Continue` and withholds its two-byte body.
  17655. static std::string expect_headers_only(const std::string &path) {
  17656. return "POST " + path +
  17657. " HTTP/1.1\r\n"
  17658. "Host: localhost\r\n"
  17659. "Content-Length: 2\r\n"
  17660. "Expect: 100-continue\r\n"
  17661. "\r\n";
  17662. }
  17663. class ExpectLazyContinueTest : public ::testing::Test {
  17664. protected:
  17665. void SetUp() override {
  17666. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17667. if (req.path == "/pre-routing") {
  17668. res.status = StatusCode::Unauthorized_401;
  17669. return Server::HandlerResponse::Handled;
  17670. }
  17671. return Server::HandlerResponse::Unhandled;
  17672. });
  17673. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17674. if (req.matched_route == "/pre-request") {
  17675. res.status = StatusCode::Forbidden_403;
  17676. return Server::HandlerResponse::Handled;
  17677. }
  17678. return Server::HandlerResponse::Unhandled;
  17679. });
  17680. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17681. res.set_content("ok", "text/plain");
  17682. });
  17683. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17684. res.set_content("ok", "text/plain");
  17685. });
  17686. svr_.Post("/reader-used", [](const Request &, Response &res,
  17687. const ContentReader &content_reader) {
  17688. std::string body;
  17689. content_reader([&](const char *data, size_t len) {
  17690. body.append(data, len);
  17691. return true;
  17692. });
  17693. res.set_content(body, "text/plain");
  17694. });
  17695. svr_.Post("/reader-unused",
  17696. [](const Request &, Response &res, const ContentReader &) {
  17697. res.set_content("ignored", "text/plain");
  17698. });
  17699. port_ = svr_.bind_to_any_port(HOST);
  17700. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17701. svr_.wait_until_ready();
  17702. }
  17703. void TearDown() override {
  17704. svr_.stop();
  17705. if (thread_.joinable()) { thread_.join(); }
  17706. }
  17707. // Sends `req` and reads until the server closes the connection. Returns
  17708. // false if the read had to wait for the client-side timeout instead.
  17709. bool send_until_closed(const std::string &req, std::string *resp) const {
  17710. auto start = std::chrono::steady_clock::now();
  17711. if (!send_request(3, req, resp, port_)) { return false; }
  17712. auto elapsed = std::chrono::steady_clock::now() - start;
  17713. return elapsed < std::chrono::seconds(2);
  17714. }
  17715. // The final response comes without `100 Continue`, and the server closes
  17716. // the connection since the body may or may not follow.
  17717. void expect_final_without_interim(const std::string &path,
  17718. const char *status_line) const {
  17719. std::string resp;
  17720. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17721. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17722. EXPECT_EQ(0u, resp.find(status_line));
  17723. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17724. }
  17725. Server svr_;
  17726. int port_ = 0;
  17727. thread thread_;
  17728. };
  17729. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17730. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17731. }
  17732. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17733. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17734. }
  17735. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17736. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17737. }
  17738. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17739. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17740. }
  17741. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17742. // The body follows once `100 Continue` has had time to arrive.
  17743. auto req = expect_headers_only("/reader-used");
  17744. req.insert(req.size() - 2, "Connection: close\r\n");
  17745. std::string resp;
  17746. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17747. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17748. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17749. EXPECT_NE(std::string::npos, resp.find("hi"));
  17750. }
  17751. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17752. // Large enough for the client to add `Expect: 100-continue` itself.
  17753. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17754. std::atomic<bool> body_sent{false};
  17755. Client cli(HOST, port_);
  17756. auto res = cli.Post(
  17757. "/pre-request", length,
  17758. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17759. body_sent = true;
  17760. std::string chunk(len, 'x');
  17761. sink.write(chunk.data(), chunk.size());
  17762. return true;
  17763. },
  17764. "application/octet-stream");
  17765. ASSERT_TRUE(res);
  17766. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17767. EXPECT_FALSE(body_sent);
  17768. }
  17769. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17770. Server svr;
  17771. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17772. return StatusCode::ExpectationFailed_417;
  17773. });
  17774. svr.Post("/p", [](const Request &, Response &res) {
  17775. res.set_content("ok", "text/plain");
  17776. });
  17777. auto port = svr.bind_to_any_port(HOST);
  17778. thread t = thread([&] { svr.listen_after_bind(); });
  17779. auto se = detail::scope_exit([&] {
  17780. svr.stop();
  17781. t.join();
  17782. });
  17783. svr.wait_until_ready();
  17784. std::string resp;
  17785. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17786. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17787. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17788. // Exactly one response: the route handler must not run after the 417.
  17789. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17790. }
  17791. #ifndef _WIN32
  17792. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17793. static constexpr char reject[] = "Unauthorized";
  17794. static constexpr char accept[] = "Upload accepted";
  17795. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17796. Server svr;
  17797. svr.set_expect_100_continue_handler(
  17798. [](const Request & /*req*/, Response &res) {
  17799. res.status = StatusCode::Unauthorized_401;
  17800. res.set_content(reject, "text/plain");
  17801. return res.status;
  17802. });
  17803. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17804. res.set_content(accept, "text/plain");
  17805. });
  17806. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17807. auto se = detail::scope_exit([&] {
  17808. svr.stop();
  17809. thread.join();
  17810. ASSERT_FALSE(svr.is_running());
  17811. });
  17812. svr.wait_until_ready();
  17813. {
  17814. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17815. curl_easy_init(), &curl_easy_cleanup};
  17816. ASSERT_NE(curl, nullptr);
  17817. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17818. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17819. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17820. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17821. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17822. &curl_slist_free_all};
  17823. ASSERT_NE(list, nullptr);
  17824. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17825. struct read_data {
  17826. size_t read_size;
  17827. size_t total_size;
  17828. } data = {0, total_size};
  17829. using read_callback_t =
  17830. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17831. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17832. void *userdata) -> size_t {
  17833. read_data *d = (read_data *)userdata;
  17834. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17835. std::fill_n(ptr, size * nmemb, 'A');
  17836. d->read_size += size * nmemb;
  17837. return size * nmemb;
  17838. };
  17839. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17840. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17841. std::vector<char> buffer;
  17842. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17843. using write_callback_t =
  17844. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17845. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17846. void *userdata) -> size_t {
  17847. std::vector<char> *buf = (std::vector<char> *)userdata;
  17848. buf->reserve(buf->size() + size * nmemb + 1);
  17849. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17850. return size * nmemb;
  17851. };
  17852. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17853. {
  17854. const auto res = curl_easy_perform(curl.get());
  17855. ASSERT_EQ(res, CURLE_OK);
  17856. }
  17857. {
  17858. auto response_code = long{};
  17859. const auto res =
  17860. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17861. ASSERT_EQ(res, CURLE_OK);
  17862. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17863. }
  17864. {
  17865. auto dl = curl_off_t{};
  17866. const auto res =
  17867. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17868. ASSERT_EQ(res, CURLE_OK);
  17869. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17870. }
  17871. {
  17872. buffer.push_back('\0');
  17873. ASSERT_STRCASEEQ(buffer.data(), reject);
  17874. }
  17875. }
  17876. }
  17877. #endif
  17878. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17879. // Regression test for #2458.
  17880. //
  17881. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17882. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17883. // ticket can make the client socket spuriously readable during the
  17884. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17885. // the client withholds the body and then blocks reading a response that never
  17886. // comes, failing with `Failed to read connection`.
  17887. //
  17888. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17889. // within the timeout. This raw OpenSSL server deliberately never sends
  17890. // `100 Continue`; the client must still deliver the body and receive 200.
  17891. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17892. signal(SIGPIPE, SIG_IGN);
  17893. const auto port = PORT + 4;
  17894. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17895. ASSERT_NE(srv, INVALID_SOCKET);
  17896. int opt = 1;
  17897. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17898. sockaddr_in addr{};
  17899. addr.sin_family = AF_INET;
  17900. addr.sin_port = htons(static_cast<uint16_t>(port));
  17901. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17902. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17903. ASSERT_EQ(0, ::listen(srv, 1));
  17904. std::atomic<size_t> server_body_bytes{0};
  17905. auto server_thread = std::thread([&] {
  17906. sockaddr_in cli_addr{};
  17907. socklen_t cli_len = sizeof(cli_addr);
  17908. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17909. if (cli == INVALID_SOCKET) { return; }
  17910. // Bound the lifetime of the server side so a buggy client (which never
  17911. // sends the body) cannot make this thread block forever on join.
  17912. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17913. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17914. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17915. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17916. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17917. SSL *ssl = SSL_new(ctx);
  17918. SSL_set_fd(ssl, static_cast<int>(cli));
  17919. if (SSL_accept(ssl) > 0) {
  17920. // Read the request headers. Reading here also flushes the TLS 1.3
  17921. // session tickets to the client. Deliberately do NOT send
  17922. // `100 Continue`.
  17923. std::string buf;
  17924. char tmp[1024];
  17925. while (buf.find("\r\n\r\n") == std::string::npos) {
  17926. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17927. if (n <= 0) { break; }
  17928. buf.append(tmp, static_cast<size_t>(n));
  17929. }
  17930. // A correct client sends the body now; count what arrives.
  17931. auto pos = buf.find("\r\n\r\n");
  17932. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17933. while (body < 4096) {
  17934. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17935. if (n <= 0) { break; }
  17936. body += static_cast<size_t>(n);
  17937. }
  17938. server_body_bytes = body;
  17939. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17940. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17941. SSL_shutdown(ssl);
  17942. }
  17943. SSL_free(ssl);
  17944. detail::close_socket(cli);
  17945. SSL_CTX_free(ctx);
  17946. });
  17947. auto se = detail::scope_exit([&] {
  17948. server_thread.join();
  17949. detail::close_socket(srv);
  17950. });
  17951. SSLClient cli("127.0.0.1", port);
  17952. cli.enable_server_certificate_verification(false);
  17953. cli.set_connection_timeout(5, 0);
  17954. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17955. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17956. std::string body(4096, 'A');
  17957. auto res = cli.Put("/api/test", body, "application/json");
  17958. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17959. EXPECT_EQ(StatusCode::OK_200, res->status);
  17960. EXPECT_EQ(body.size(), server_body_bytes.load());
  17961. }
  17962. #endif
  17963. template <typename S, typename C>
  17964. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17965. svr.Get("/stream", [&](const Request &, Response &res) {
  17966. auto data = new std::string("01234567890123456789");
  17967. res.set_content_provider(
  17968. data->size(), "text/plain",
  17969. [&, data](size_t offset, size_t length, DataSink &sink) {
  17970. const size_t DATA_CHUNK_SIZE = 4;
  17971. const auto &d = *data;
  17972. std::this_thread::sleep_for(std::chrono::seconds(1));
  17973. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17974. return true;
  17975. },
  17976. [data](bool success) {
  17977. EXPECT_FALSE(success);
  17978. delete data;
  17979. });
  17980. });
  17981. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17982. auto i = new size_t(0);
  17983. res.set_content_provider(
  17984. "text/plain",
  17985. [i](size_t, DataSink &sink) {
  17986. if (*i < 5) {
  17987. std::this_thread::sleep_for(std::chrono::seconds(1));
  17988. sink.write("abcd", 4);
  17989. (*i)++;
  17990. } else {
  17991. sink.done();
  17992. }
  17993. return true;
  17994. },
  17995. [i](bool success) {
  17996. EXPECT_FALSE(success);
  17997. delete i;
  17998. });
  17999. });
  18000. svr.Get("/chunked", [&](const Request &, Response &res) {
  18001. auto i = new size_t(0);
  18002. res.set_chunked_content_provider(
  18003. "text/plain",
  18004. [i](size_t, DataSink &sink) {
  18005. if (*i < 5) {
  18006. std::this_thread::sleep_for(std::chrono::seconds(1));
  18007. sink.os << "abcd";
  18008. (*i)++;
  18009. } else {
  18010. sink.done();
  18011. }
  18012. return true;
  18013. },
  18014. [i](bool success) {
  18015. EXPECT_FALSE(success);
  18016. delete i;
  18017. });
  18018. });
  18019. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18020. auto se = detail::scope_exit([&] {
  18021. svr.stop();
  18022. listen_thread.join();
  18023. ASSERT_FALSE(svr.is_running());
  18024. });
  18025. svr.wait_until_ready();
  18026. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18027. {
  18028. auto start = std::chrono::steady_clock::now();
  18029. auto res = cli.Get("/stream");
  18030. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18031. std::chrono::steady_clock::now() - start)
  18032. .count();
  18033. ASSERT_FALSE(res);
  18034. EXPECT_EQ(Error::Read, res.error());
  18035. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18036. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18037. }
  18038. {
  18039. auto start = std::chrono::steady_clock::now();
  18040. auto res = cli.Get("/stream_without_length");
  18041. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18042. std::chrono::steady_clock::now() - start)
  18043. .count();
  18044. ASSERT_FALSE(res);
  18045. EXPECT_EQ(Error::Read, res.error());
  18046. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18047. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18048. }
  18049. {
  18050. auto start = std::chrono::steady_clock::now();
  18051. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18052. EXPECT_EQ("abcd", string(data, data_length));
  18053. return true;
  18054. });
  18055. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18056. std::chrono::steady_clock::now() - start)
  18057. .count();
  18058. ASSERT_FALSE(res);
  18059. EXPECT_EQ(Error::Read, res.error());
  18060. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18061. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18062. }
  18063. }
  18064. TEST(MaxTimeoutTest, ContentStream) {
  18065. time_t timeout = 2000;
  18066. time_t threshold = 200;
  18067. Server svr;
  18068. Client cli("localhost", PORT);
  18069. max_timeout_test(svr, cli, timeout, threshold);
  18070. }
  18071. #ifdef CPPHTTPLIB_SSL_ENABLED
  18072. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18073. time_t timeout = 2000;
  18074. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18075. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18076. SSLClient cli("localhost", PORT);
  18077. cli.enable_server_certificate_verification(false);
  18078. max_timeout_test(svr, cli, timeout, threshold);
  18079. }
  18080. #endif
  18081. class EventDispatcher {
  18082. public:
  18083. EventDispatcher() {}
  18084. bool wait_event(DataSink *sink) {
  18085. unique_lock<mutex> lk(m_);
  18086. int id = id_;
  18087. // Wait with timeout to prevent hanging if client disconnects
  18088. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18089. [&] { return cid_ == id; })) {
  18090. return false; // Timeout occurred
  18091. }
  18092. sink->write(message_.data(), message_.size());
  18093. return true;
  18094. }
  18095. void send_event(const string &message) {
  18096. lock_guard<mutex> lk(m_);
  18097. cid_ = id_++;
  18098. message_ = message;
  18099. cv_.notify_all();
  18100. }
  18101. private:
  18102. mutex m_;
  18103. condition_variable cv_;
  18104. atomic_int id_{0};
  18105. atomic_int cid_{-1};
  18106. string message_;
  18107. };
  18108. TEST(ClientInThreadTest, Issue2068) {
  18109. EventDispatcher ed;
  18110. Server svr;
  18111. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18112. res.set_chunked_content_provider("text/event-stream",
  18113. [&](size_t /*offset*/, DataSink &sink) {
  18114. return ed.wait_event(&sink);
  18115. });
  18116. });
  18117. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18118. svr.wait_until_ready();
  18119. thread event_thread([&] {
  18120. int id = 0;
  18121. while (svr.is_running()) {
  18122. this_thread::sleep_for(chrono::milliseconds(500));
  18123. std::stringstream ss;
  18124. ss << "data: " << id << "\n\n";
  18125. ed.send_event(ss.str());
  18126. id++;
  18127. }
  18128. });
  18129. auto se = detail::scope_exit([&] {
  18130. svr.stop();
  18131. listen_thread.join();
  18132. event_thread.join();
  18133. ASSERT_FALSE(svr.is_running());
  18134. });
  18135. {
  18136. auto client = detail::make_unique<Client>(HOST, PORT);
  18137. client->set_read_timeout(std::chrono::minutes(10));
  18138. std::atomic<bool> stop{false};
  18139. std::thread t([&] {
  18140. client->Get("/event1",
  18141. [&](const char *, size_t) -> bool { return !stop; });
  18142. });
  18143. std::this_thread::sleep_for(std::chrono::seconds(2));
  18144. stop = true;
  18145. client->stop();
  18146. t.join();
  18147. // Reset client after thread has finished
  18148. client.reset();
  18149. }
  18150. }
  18151. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18152. auto handled = false;
  18153. Server svr;
  18154. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18155. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18156. auto se = detail::scope_exit([&] {
  18157. svr.stop();
  18158. t.join();
  18159. ASSERT_FALSE(svr.is_running());
  18160. ASSERT_FALSE(handled);
  18161. });
  18162. svr.wait_until_ready();
  18163. // Two Content-Length headers with different values — must be rejected
  18164. auto req = "POST /test HTTP/1.1\r\n"
  18165. "Content-Length: 5\r\n"
  18166. "Content-Length: 10\r\n"
  18167. "\r\n"
  18168. "hello";
  18169. std::string response;
  18170. ASSERT_TRUE(send_request(1, req, &response));
  18171. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18172. response.substr(0, response.find("\r\n")));
  18173. }
  18174. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18175. auto handled = false;
  18176. Server svr;
  18177. svr.Post("/test", [&](const Request &, Response &res) {
  18178. handled = true;
  18179. res.set_content("ok", "text/plain");
  18180. });
  18181. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18182. auto se = detail::scope_exit([&] {
  18183. svr.stop();
  18184. t.join();
  18185. ASSERT_FALSE(svr.is_running());
  18186. ASSERT_TRUE(handled);
  18187. });
  18188. svr.wait_until_ready();
  18189. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18190. auto req = "POST /test HTTP/1.1\r\n"
  18191. "Host: localhost\r\n"
  18192. "Content-Length: 5\r\n"
  18193. "Content-Length: 5\r\n"
  18194. "\r\n"
  18195. "hello";
  18196. std::string response;
  18197. ASSERT_TRUE(send_request(1, req, &response));
  18198. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18199. }
  18200. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18201. Server svr;
  18202. svr.Get("/test", [](const Request &, Response &res) {
  18203. res.set_content("ok", "text/plain");
  18204. });
  18205. auto port = svr.bind_to_any_port(HOST);
  18206. thread t = thread([&] { svr.listen_after_bind(); });
  18207. auto se = detail::scope_exit([&] {
  18208. svr.stop();
  18209. t.join();
  18210. ASSERT_FALSE(svr.is_running());
  18211. });
  18212. svr.wait_until_ready();
  18213. auto status_line = [&](const std::string &host_lines) {
  18214. std::string res;
  18215. send_request(
  18216. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18217. &res, port);
  18218. return res.substr(0, res.find("\r\n"));
  18219. };
  18220. const char *accepted[] = {
  18221. "Host: localhost\r\n",
  18222. "Host: a.example:8080\r\n",
  18223. "Host: my_service\r\n",
  18224. "Host: [::1]:8080\r\n",
  18225. "Host: [fe80::1%25eth0]\r\n",
  18226. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18227. };
  18228. for (auto host_lines : accepted) {
  18229. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18230. }
  18231. const char *rejected[] = {
  18232. "Host: a.example\r\nHost: b.example\r\n",
  18233. "Host: a.example\r\nHost: a.example\r\n",
  18234. "Host: a@b.example\r\n",
  18235. "Host: a.example/b\r\n",
  18236. "Host: a.example\\b\r\n",
  18237. "Host: a.example?b\r\n",
  18238. "Host: a.example#b\r\n",
  18239. "Host: a.example b.example\r\n",
  18240. };
  18241. for (auto host_lines : rejected) {
  18242. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18243. << host_lines;
  18244. }
  18245. }
  18246. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18247. Server svr;
  18248. svr.Get("/", [](const Request &req, Response &res) {
  18249. EXPECT_EQ(2U, req.trailers.size());
  18250. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18251. // Denied
  18252. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18253. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18254. // Accepted
  18255. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18256. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18257. EXPECT_TRUE(req.has_trailer("X-World"));
  18258. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18259. res.set_content("ok", "text/plain");
  18260. });
  18261. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18262. auto se = detail::scope_exit([&] {
  18263. svr.stop();
  18264. t.join();
  18265. ASSERT_FALSE(svr.is_running());
  18266. });
  18267. svr.wait_until_ready();
  18268. const std::string req = "GET / HTTP/1.1\r\n"
  18269. "Transfer-Encoding: chunked\r\n"
  18270. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18271. "\r\n"
  18272. "0\r\n"
  18273. "Content-Length: 10\r\n"
  18274. "Host: internal.local\r\n"
  18275. "Content-Type: malicious/content\r\n"
  18276. "Cookie: any\r\n"
  18277. "Set-Cookie: any\r\n"
  18278. "X-Forwarded-For: attacker.com\r\n"
  18279. "X-Real-Ip: 1.1.1.1\r\n"
  18280. "X-Hello: hello\r\n"
  18281. "X-World: world\r\n"
  18282. "\r\n";
  18283. std::string res;
  18284. ASSERT_TRUE(send_request(1, req, &res));
  18285. }
  18286. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18287. // several field lines, and the combined value is what has to be parsed. A
  18288. // Trailer field split across lines therefore declares every name it lists;
  18289. // reading only the first line silently drops the trailers the later lines
  18290. // declare. The prohibited-trailer filter still applies to every line.
  18291. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18292. Server svr;
  18293. size_t observed_trailer_count = 0;
  18294. std::string observed_hello;
  18295. std::string observed_world;
  18296. bool observed_content_length = true;
  18297. svr.Get("/", [&](const Request &req, Response &res) {
  18298. observed_trailer_count = req.trailers.size();
  18299. observed_hello = req.get_trailer_value("X-Hello");
  18300. observed_world = req.get_trailer_value("X-World");
  18301. observed_content_length = req.has_trailer("Content-Length");
  18302. res.set_content("ok", "text/plain");
  18303. });
  18304. auto port = svr.bind_to_any_port(HOST);
  18305. thread t = thread([&]() { svr.listen_after_bind(); });
  18306. auto se = detail::scope_exit([&] {
  18307. svr.stop();
  18308. t.join();
  18309. ASSERT_FALSE(svr.is_running());
  18310. });
  18311. svr.wait_until_ready();
  18312. const std::string req = "GET / HTTP/1.1\r\n"
  18313. "Host: localhost\r\n"
  18314. "Transfer-Encoding: chunked\r\n"
  18315. "Trailer: X-Hello\r\n"
  18316. "Trailer: X-World, Content-Length\r\n"
  18317. "\r\n"
  18318. "0\r\n"
  18319. "X-Hello: hello\r\n"
  18320. "X-World: world\r\n"
  18321. "Content-Length: 10\r\n"
  18322. "\r\n";
  18323. std::string res;
  18324. ASSERT_TRUE(send_request(1, req, &res, port));
  18325. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18326. // Accepted: both field lines contribute to the declared set
  18327. EXPECT_EQ(2U, observed_trailer_count);
  18328. EXPECT_EQ(observed_hello, "hello");
  18329. EXPECT_EQ(observed_world, "world");
  18330. // Denied: a prohibited name stays prohibited on a later field line
  18331. EXPECT_FALSE(observed_content_length);
  18332. }
  18333. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18334. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18335. // unbounded run of fields that are never declared, because the counter would
  18336. // only advance for declared fields.
  18337. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18338. Server svr;
  18339. bool handler_called = false;
  18340. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18341. handler_called = true;
  18342. res.set_content("ok", "text/plain");
  18343. });
  18344. auto port = svr.bind_to_any_port(HOST);
  18345. thread t = thread([&]() { svr.listen_after_bind(); });
  18346. auto se = detail::scope_exit([&] {
  18347. svr.stop();
  18348. t.join();
  18349. ASSERT_FALSE(svr.is_running());
  18350. });
  18351. svr.wait_until_ready();
  18352. // Declare nothing, then send far more undeclared trailer fields than the
  18353. // header-count limit. Parsing must stop and reject the request rather than
  18354. // read every line.
  18355. std::string req = "GET / HTTP/1.1\r\n"
  18356. "Transfer-Encoding: chunked\r\n"
  18357. "\r\n"
  18358. "0\r\n";
  18359. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18360. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18361. }
  18362. req += "\r\n";
  18363. std::string res;
  18364. ASSERT_TRUE(send_request(1, req, &res, port));
  18365. // The request is rejected before the handler runs.
  18366. EXPECT_FALSE(handler_called);
  18367. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18368. }
  18369. // The set of declared trailer names is capped so a peer cannot grow it without
  18370. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18371. // declared past the cap is not honored, even if the field is actually sent.
  18372. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18373. Server svr;
  18374. // One name inside the cap and one past it, so the test tracks the cap rather
  18375. // than a fixed count.
  18376. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18377. const std::string within_cap_name = "X-T-0";
  18378. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18379. bool observed_within_cap = false;
  18380. bool observed_past_cap = false;
  18381. svr.Get("/", [&](const Request &req, Response &res) {
  18382. observed_within_cap = req.has_trailer(within_cap_name);
  18383. observed_past_cap = req.has_trailer(past_cap_name);
  18384. res.set_content("ok", "text/plain");
  18385. });
  18386. auto port = svr.bind_to_any_port(HOST);
  18387. thread t = thread([&]() { svr.listen_after_bind(); });
  18388. auto se = detail::scope_exit([&] {
  18389. svr.stop();
  18390. t.join();
  18391. ASSERT_FALSE(svr.is_running());
  18392. });
  18393. svr.wait_until_ready();
  18394. // Declare more trailer names than the cap in a single Trailer field, then
  18395. // actually send the first (within the cap) and the last (past it).
  18396. std::string trailer_decl = "Trailer: ";
  18397. for (int i = 0; i < declared_count; i++) {
  18398. if (i != 0) { trailer_decl += ", "; }
  18399. trailer_decl += "X-T-" + std::to_string(i);
  18400. }
  18401. trailer_decl += "\r\n";
  18402. const std::string req = "GET / HTTP/1.1\r\n"
  18403. "Host: localhost\r\n"
  18404. "Transfer-Encoding: chunked\r\n" +
  18405. trailer_decl +
  18406. "\r\n"
  18407. "0\r\n" +
  18408. within_cap_name + ": a\r\n" + past_cap_name +
  18409. ": b\r\n"
  18410. "\r\n";
  18411. std::string res;
  18412. ASSERT_TRUE(send_request(1, req, &res, port));
  18413. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18414. // A name within the cap is honored; one declared past the cap is dropped.
  18415. EXPECT_TRUE(observed_within_cap);
  18416. EXPECT_FALSE(observed_past_cap);
  18417. }
  18418. // A direct client that is not listed in trusted_proxies must not be able to
  18419. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18420. // the peer address on the actual TCP connection determines whether the
  18421. // header is honored.
  18422. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18423. Server svr;
  18424. // Deliberately does NOT include the loopback address the test client
  18425. // actually connects from, so the direct connection is not a trusted proxy.
  18426. svr.set_trusted_proxies({"203.0.113.66"});
  18427. std::string observed_remote_addr;
  18428. svr.Get("/ip", [&](const Request &req, Response &res) {
  18429. observed_remote_addr = req.remote_addr;
  18430. res.set_content("ok", "text/plain");
  18431. });
  18432. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18433. auto se = detail::scope_exit([&] {
  18434. svr.stop();
  18435. t.join();
  18436. ASSERT_FALSE(svr.is_running());
  18437. });
  18438. svr.wait_until_ready();
  18439. Client cli(HOST, PORT);
  18440. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18442. EXPECT_EQ(StatusCode::OK_200, res->status);
  18443. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18444. // ignored entirely and the real connection-level address retained.
  18445. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18446. observed_remote_addr == "127.0.0.1");
  18447. }
  18448. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18449. Server svr;
  18450. std::string observed_remote_addr;
  18451. std::string observed_xff;
  18452. svr.Get("/ip", [&](const Request &req, Response &res) {
  18453. observed_remote_addr = req.remote_addr;
  18454. observed_xff = req.get_header_value("X-Forwarded-For");
  18455. res.set_content("ok", "text/plain");
  18456. });
  18457. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18458. auto se = detail::scope_exit([&] {
  18459. svr.stop();
  18460. t.join();
  18461. ASSERT_FALSE(svr.is_running());
  18462. });
  18463. svr.wait_until_ready();
  18464. Client cli(HOST, PORT);
  18465. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18467. EXPECT_EQ(StatusCode::OK_200, res->status);
  18468. EXPECT_EQ(observed_xff, "203.0.113.66");
  18469. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18470. observed_remote_addr == "127.0.0.1");
  18471. }
  18472. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18473. Server svr;
  18474. svr.set_trusted_proxies({"203.0.113.66"});
  18475. std::string observed_remote_addr;
  18476. std::string observed_xff;
  18477. svr.Get("/ip", [&](const Request &req, Response &res) {
  18478. observed_remote_addr = req.remote_addr;
  18479. observed_xff = req.get_header_value("X-Forwarded-For");
  18480. res.set_content("ok", "text/plain");
  18481. });
  18482. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18483. auto se = detail::scope_exit([&] {
  18484. svr.stop();
  18485. t.join();
  18486. ASSERT_FALSE(svr.is_running());
  18487. });
  18488. svr.wait_until_ready();
  18489. Client cli(HOST, PORT);
  18490. auto res = cli.Get("/ip");
  18491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18492. EXPECT_EQ(StatusCode::OK_200, res->status);
  18493. EXPECT_EQ(observed_xff, "");
  18494. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18495. observed_remote_addr == "127.0.0.1");
  18496. }
  18497. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18498. Server svr;
  18499. // Include the loopback address the test client actually connects from, so
  18500. // the direct connection itself is recognized as the trusted proxy hop.
  18501. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18502. std::string observed_remote_addr;
  18503. std::string observed_xff;
  18504. svr.Get("/ip", [&](const Request &req, Response &res) {
  18505. observed_remote_addr = req.remote_addr;
  18506. observed_xff = req.get_header_value("X-Forwarded-For");
  18507. res.set_content("ok", "text/plain");
  18508. });
  18509. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18510. auto se = detail::scope_exit([&] {
  18511. svr.stop();
  18512. t.join();
  18513. ASSERT_FALSE(svr.is_running());
  18514. });
  18515. svr.wait_until_ready();
  18516. Client cli(HOST, PORT);
  18517. auto res = cli.Get(
  18518. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18520. EXPECT_EQ(StatusCode::OK_200, res->status);
  18521. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18522. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18523. }
  18524. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18525. Server svr;
  18526. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18527. std::string observed_remote_addr;
  18528. std::string observed_xff;
  18529. svr.Get("/ip", [&](const Request &req, Response &res) {
  18530. observed_remote_addr = req.remote_addr;
  18531. observed_xff = req.get_header_value("X-Forwarded-For");
  18532. res.set_content("ok", "text/plain");
  18533. });
  18534. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18535. auto se = detail::scope_exit([&] {
  18536. svr.stop();
  18537. t.join();
  18538. ASSERT_FALSE(svr.is_running());
  18539. });
  18540. svr.wait_until_ready();
  18541. Client cli(HOST, PORT);
  18542. auto res = cli.Get(
  18543. "/ip",
  18544. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18546. EXPECT_EQ(StatusCode::OK_200, res->status);
  18547. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18548. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18549. }
  18550. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18551. Server svr;
  18552. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18553. std::string observed_remote_addr;
  18554. std::string observed_xff;
  18555. svr.Get("/ip", [&](const Request &req, Response &res) {
  18556. observed_remote_addr = req.remote_addr;
  18557. observed_xff = req.get_header_value("X-Forwarded-For");
  18558. res.set_content("ok", "text/plain");
  18559. });
  18560. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18561. auto se = detail::scope_exit([&] {
  18562. svr.stop();
  18563. t.join();
  18564. ASSERT_FALSE(svr.is_running());
  18565. });
  18566. svr.wait_until_ready();
  18567. Client cli(HOST, PORT);
  18568. auto res = cli.Get(
  18569. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18571. EXPECT_EQ(StatusCode::OK_200, res->status);
  18572. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18573. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18574. // and must not be selected.
  18575. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18576. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18577. }
  18578. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18579. Server svr;
  18580. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18581. std::string observed_remote_addr;
  18582. svr.Get("/ip", [&](const Request &req, Response &res) {
  18583. observed_remote_addr = req.remote_addr;
  18584. res.set_content("ok", "text/plain");
  18585. });
  18586. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18587. auto se = detail::scope_exit([&] {
  18588. svr.stop();
  18589. t.join();
  18590. ASSERT_FALSE(svr.is_running());
  18591. });
  18592. svr.wait_until_ready();
  18593. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18594. // a forged address and the trusted proxy's own address; the forged value must
  18595. // not win over the address the trusted proxy actually recorded.
  18596. Client cli(HOST, PORT);
  18597. auto res = cli.Get(
  18598. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18600. EXPECT_EQ(StatusCode::OK_200, res->status);
  18601. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18602. }
  18603. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18604. Server svr;
  18605. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18606. std::string observed_remote_addr;
  18607. std::string observed_xff;
  18608. svr.Get("/ip", [&](const Request &req, Response &res) {
  18609. observed_remote_addr = req.remote_addr;
  18610. observed_xff = req.get_header_value("X-Forwarded-For");
  18611. res.set_content("ok", "text/plain");
  18612. });
  18613. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18614. auto se = detail::scope_exit([&] {
  18615. svr.stop();
  18616. t.join();
  18617. ASSERT_FALSE(svr.is_running());
  18618. });
  18619. svr.wait_until_ready();
  18620. Client cli(HOST, PORT);
  18621. auto res = cli.Get(
  18622. "/ip",
  18623. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18625. EXPECT_EQ(StatusCode::OK_200, res->status);
  18626. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18627. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18628. }
  18629. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18630. Server svr;
  18631. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18632. std::string observed_remote_addr;
  18633. std::string observed_xff;
  18634. svr.Get("/ip", [&](const Request &req, Response &res) {
  18635. observed_remote_addr = req.remote_addr;
  18636. observed_xff = req.get_header_value("X-Forwarded-For");
  18637. res.set_content("ok", "text/plain");
  18638. });
  18639. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18640. auto se = detail::scope_exit([&] {
  18641. svr.stop();
  18642. t.join();
  18643. ASSERT_FALSE(svr.is_running());
  18644. });
  18645. svr.wait_until_ready();
  18646. std::string raw_req =
  18647. "GET /ip HTTP/1.1\r\n"
  18648. "Host: localhost\r\n"
  18649. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18650. "Connection: close\r\n"
  18651. "\r\n";
  18652. std::string out;
  18653. ASSERT_TRUE(send_request(5, raw_req, &out));
  18654. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18655. // Header parser trims surrounding whitespace of the header value
  18656. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18657. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18658. }
  18659. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18660. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18661. // their own X-Forwarded-For as a separate field line rather than extending the
  18662. // one the client sent, so every occurrence has to be taken into account.
  18663. // Reading only the first one hands back the address the client chose.
  18664. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18665. Server svr;
  18666. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18667. std::string observed_remote_addr;
  18668. size_t observed_xff_count = 0;
  18669. svr.Get("/ip", [&](const Request &req, Response &res) {
  18670. observed_remote_addr = req.remote_addr;
  18671. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18672. res.set_content("ok", "text/plain");
  18673. });
  18674. auto port = svr.bind_to_any_port(HOST);
  18675. thread t = thread([&]() { svr.listen_after_bind(); });
  18676. auto se = detail::scope_exit([&] {
  18677. svr.stop();
  18678. t.join();
  18679. ASSERT_FALSE(svr.is_running());
  18680. });
  18681. svr.wait_until_ready();
  18682. // The client supplies the first field line; the trusted proxy appends the
  18683. // address it observed as a second one.
  18684. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18685. "Host: localhost\r\n"
  18686. "X-Forwarded-For: 1.2.3.4\r\n"
  18687. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18688. "Connection: close\r\n"
  18689. "\r\n";
  18690. std::string out;
  18691. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18692. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18693. EXPECT_EQ(observed_xff_count, 2U);
  18694. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18695. // The same chain spread over one field line per hop derives the same client
  18696. // address, i.e. the split and the comma-joined representations agree.
  18697. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18698. "Host: localhost\r\n"
  18699. "X-Forwarded-For: 1.2.3.4\r\n"
  18700. "X-Forwarded-For: 198.51.100.23\r\n"
  18701. "X-Forwarded-For: 192.0.2.45\r\n"
  18702. "Connection: close\r\n"
  18703. "\r\n";
  18704. out.clear();
  18705. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18706. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18707. EXPECT_EQ(observed_xff_count, 3U);
  18708. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18709. }
  18710. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18711. // crash the server (it used to call front() on an empty vector inside
  18712. // get_client_ip). The connection-level remote address must be retained instead.
  18713. static void run_malformed_xff_test(const std::string &xff_value) {
  18714. Server svr;
  18715. svr.set_trusted_proxies({"192.0.2.45"});
  18716. std::string observed_remote_addr;
  18717. svr.Get("/ip", [&](const Request &req, Response &res) {
  18718. observed_remote_addr = req.remote_addr;
  18719. res.set_content("ok", "text/plain");
  18720. });
  18721. int port = 0;
  18722. thread t = thread([&]() {
  18723. port = svr.bind_to_any_port(HOST);
  18724. svr.listen_after_bind();
  18725. });
  18726. auto se = detail::scope_exit([&] {
  18727. svr.stop();
  18728. t.join();
  18729. ASSERT_FALSE(svr.is_running());
  18730. });
  18731. svr.wait_until_ready();
  18732. Client cli(HOST, port);
  18733. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18735. EXPECT_EQ(StatusCode::OK_200, res->status);
  18736. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18737. observed_remote_addr == "127.0.0.1");
  18738. }
  18739. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18740. run_malformed_xff_test("");
  18741. }
  18742. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18743. run_malformed_xff_test(",");
  18744. }
  18745. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18746. run_malformed_xff_test(", , ,");
  18747. }
  18748. // The same rule applies to Accept: a request whose acceptable types are spread
  18749. // over several field lines must be negotiated against all of them.
  18750. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18751. // case-insensitive connection options. Comparing the whole field value against
  18752. // one option misses a client that sends several of them, and misses every
  18753. // casing but the one written in the comparison.
  18754. //
  18755. // Sends req, reads the response, then reuses the same socket for a second
  18756. // request to find out whether the server kept the connection.
  18757. static void probe_connection_reuse(int port, const std::string &req,
  18758. bool *announced_close, bool *reusable) {
  18759. auto error = Error::Success;
  18760. auto sock = detail::create_client_socket(
  18761. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18762. /*connection_timeout_sec=*/5, 0,
  18763. /*read_timeout_sec=*/1, 0,
  18764. /*write_timeout_sec=*/5, 0, std::string(), error);
  18765. ASSERT_NE(sock, INVALID_SOCKET);
  18766. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18767. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18768. "Host: localhost\r\n"
  18769. "Connection: close\r\n"
  18770. "\r\n";
  18771. std::string first_response;
  18772. std::string second_response;
  18773. detail::process_client_socket(
  18774. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18775. [&](Stream &strm) {
  18776. if (strm.write(req.data(), req.size()) !=
  18777. static_cast<ssize_t>(req.size())) {
  18778. return false;
  18779. }
  18780. char buf[512];
  18781. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18782. // Headers plus the two-byte body of the handler below
  18783. while (reader.getline()) {
  18784. first_response += reader.ptr();
  18785. if (first_response.find("ok") != std::string::npos) { break; }
  18786. }
  18787. if (strm.write(second.data(), second.size()) !=
  18788. static_cast<ssize_t>(second.size())) {
  18789. return true;
  18790. }
  18791. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18792. while (reader2.getline()) {
  18793. second_response += reader2.ptr();
  18794. if (second_response.find("ok") != std::string::npos) { break; }
  18795. }
  18796. return true;
  18797. });
  18798. *announced_close =
  18799. first_response.find("Connection: close") != std::string::npos;
  18800. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18801. }
  18802. class ConnectionTokenTest : public ::testing::Test {
  18803. protected:
  18804. void SetUp() override {
  18805. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18806. res.set_content("ok", "text/plain");
  18807. });
  18808. port_ = svr_.bind_to_any_port(HOST);
  18809. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18810. svr_.wait_until_ready();
  18811. }
  18812. void TearDown() override {
  18813. svr_.stop();
  18814. if (thread_.joinable()) { thread_.join(); }
  18815. }
  18816. Server svr_;
  18817. int port_ = 0;
  18818. thread thread_;
  18819. };
  18820. // "close" alongside another option still closes the connection, and the
  18821. // response says so rather than leaving the peer to discover it.
  18822. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18823. bool announced_close = false;
  18824. bool reusable = true;
  18825. probe_connection_reuse(port_,
  18826. "GET /keepalive HTTP/1.1\r\n"
  18827. "Host: localhost\r\n"
  18828. "Connection: keep-alive, close\r\n"
  18829. "\r\n",
  18830. &announced_close, &reusable);
  18831. EXPECT_TRUE(announced_close);
  18832. EXPECT_FALSE(reusable);
  18833. }
  18834. // "close" split over two field lines is the same list, so it is honored too.
  18835. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18836. bool announced_close = false;
  18837. bool reusable = true;
  18838. probe_connection_reuse(port_,
  18839. "GET /keepalive HTTP/1.1\r\n"
  18840. "Host: localhost\r\n"
  18841. "Connection: keep-alive\r\n"
  18842. "Connection: close\r\n"
  18843. "\r\n",
  18844. &announced_close, &reusable);
  18845. EXPECT_TRUE(announced_close);
  18846. EXPECT_FALSE(reusable);
  18847. }
  18848. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18849. // keep-alive in the spelling everyone actually sends keeps its connection.
  18850. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18851. bool announced_close = false;
  18852. bool reusable = false;
  18853. probe_connection_reuse(port_,
  18854. "GET /keepalive HTTP/1.0\r\n"
  18855. "Host: localhost\r\n"
  18856. "Connection: keep-alive\r\n"
  18857. "\r\n",
  18858. &announced_close, &reusable);
  18859. EXPECT_FALSE(announced_close);
  18860. EXPECT_TRUE(reusable);
  18861. }
  18862. // A token the value merely contains is not the token itself.
  18863. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18864. bool announced_close = false;
  18865. bool reusable = false;
  18866. probe_connection_reuse(port_,
  18867. "GET /keepalive HTTP/1.1\r\n"
  18868. "Host: localhost\r\n"
  18869. "Connection: notclose\r\n"
  18870. "\r\n",
  18871. &announced_close, &reusable);
  18872. EXPECT_FALSE(announced_close);
  18873. EXPECT_TRUE(reusable);
  18874. }
  18875. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18876. Server svr;
  18877. std::vector<std::string> observed_types;
  18878. svr.Get("/", [&](const Request &req, Response &res) {
  18879. observed_types = req.accept_content_types;
  18880. res.set_content("ok", "text/plain");
  18881. });
  18882. auto port = svr.bind_to_any_port(HOST);
  18883. thread t = thread([&]() { svr.listen_after_bind(); });
  18884. auto se = detail::scope_exit([&] {
  18885. svr.stop();
  18886. t.join();
  18887. ASSERT_FALSE(svr.is_running());
  18888. });
  18889. svr.wait_until_ready();
  18890. Client cli(HOST, port);
  18891. Headers headers;
  18892. headers.emplace("Accept", "text/plain;q=0.5");
  18893. headers.emplace("Accept", "application/json");
  18894. auto res = cli.Get("/", headers);
  18895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18896. EXPECT_EQ(StatusCode::OK_200, res->status);
  18897. // Sorted by q-value, so the second field line's type comes first
  18898. ASSERT_EQ(2U, observed_types.size());
  18899. EXPECT_EQ("application/json", observed_types[0]);
  18900. EXPECT_EQ("text/plain", observed_types[1]);
  18901. }
  18902. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18903. // empty field line must not contribute a bare comma to the combined value.
  18904. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18905. Server svr;
  18906. std::vector<std::string> observed_types;
  18907. svr.Get("/", [&](const Request &req, Response &res) {
  18908. observed_types = req.accept_content_types;
  18909. res.set_content("ok", "text/plain");
  18910. });
  18911. auto port = svr.bind_to_any_port(HOST);
  18912. thread t = thread([&]() { svr.listen_after_bind(); });
  18913. auto se = detail::scope_exit([&] {
  18914. svr.stop();
  18915. t.join();
  18916. ASSERT_FALSE(svr.is_running());
  18917. });
  18918. svr.wait_until_ready();
  18919. // Empty first field line, then a real one
  18920. std::string raw_req = "GET / HTTP/1.1\r\n"
  18921. "Host: localhost\r\n"
  18922. "Accept:\r\n"
  18923. "Accept: application/json\r\n"
  18924. "Connection: close\r\n"
  18925. "\r\n";
  18926. std::string out;
  18927. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18928. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18929. ASSERT_EQ(1U, observed_types.size());
  18930. EXPECT_EQ("application/json", observed_types[0]);
  18931. }
  18932. // The skip in get_combined_header_value() is what keeps an empty field line
  18933. // from contributing a bare comma. Only a trailing empty field line exercises
  18934. // it: a leading one is already covered by the "combined is still empty" check,
  18935. // and parse_accept_header() now ignores the empty element either way, so the
  18936. // request-level test above can no longer tell the two apart.
  18937. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18938. Headers headers;
  18939. headers.emplace("Accept", "text/html");
  18940. headers.emplace("Accept", "");
  18941. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18942. headers.clear();
  18943. headers.emplace("Accept", "");
  18944. headers.emplace("Accept", "application/json");
  18945. EXPECT_EQ("application/json",
  18946. detail::get_combined_header_value(headers, "Accept"));
  18947. }
  18948. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18949. // An encoding offered on a later Accept-Encoding field line is still offered.
  18950. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18951. Server svr;
  18952. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18953. res.set_content(std::string(1024, 'x'), "text/plain");
  18954. });
  18955. auto port = svr.bind_to_any_port(HOST);
  18956. thread t = thread([&]() { svr.listen_after_bind(); });
  18957. auto se = detail::scope_exit([&] {
  18958. svr.stop();
  18959. t.join();
  18960. ASSERT_FALSE(svr.is_running());
  18961. });
  18962. svr.wait_until_ready();
  18963. Client cli(HOST, port);
  18964. cli.set_decompress(false);
  18965. Headers headers;
  18966. headers.emplace("Accept-Encoding", "identity");
  18967. headers.emplace("Accept-Encoding", "gzip");
  18968. auto res = cli.Get("/", headers);
  18969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18970. EXPECT_EQ(StatusCode::OK_200, res->status);
  18971. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18972. }
  18973. #endif
  18974. #ifndef _WIN32
  18975. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18976. Server svr;
  18977. svr.Post("/post", [&](const Request &req, Response &res) {
  18978. res.set_content(req.body, "text/plain");
  18979. });
  18980. svr.Put("/put", [&](const Request &req, Response &res) {
  18981. res.set_content(req.body, "text/plain");
  18982. });
  18983. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18984. res.set_content(req.body, "text/plain");
  18985. });
  18986. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18987. res.set_content(req.body, "text/plain");
  18988. });
  18989. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18990. auto se = detail::scope_exit([&] {
  18991. svr.stop();
  18992. t.join();
  18993. ASSERT_FALSE(svr.is_running());
  18994. });
  18995. svr.wait_until_ready();
  18996. std::string resp;
  18997. // POST without Content-Length
  18998. ASSERT_TRUE(send_request(5,
  18999. "POST /post HTTP/1.1\r\n"
  19000. "Host: localhost\r\n"
  19001. "Connection: close\r\n"
  19002. "\r\n",
  19003. &resp));
  19004. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19005. // PUT without Content-Length
  19006. resp.clear();
  19007. ASSERT_TRUE(send_request(5,
  19008. "PUT /put HTTP/1.1\r\n"
  19009. "Host: localhost\r\n"
  19010. "Connection: close\r\n"
  19011. "\r\n",
  19012. &resp));
  19013. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19014. // PATCH without Content-Length
  19015. resp.clear();
  19016. ASSERT_TRUE(send_request(5,
  19017. "PATCH /patch HTTP/1.1\r\n"
  19018. "Host: localhost\r\n"
  19019. "Connection: close\r\n"
  19020. "\r\n",
  19021. &resp));
  19022. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19023. // DELETE without Content-Length
  19024. resp.clear();
  19025. ASSERT_TRUE(send_request(5,
  19026. "DELETE /delete HTTP/1.1\r\n"
  19027. "Host: localhost\r\n"
  19028. "Connection: close\r\n"
  19029. "\r\n",
  19030. &resp));
  19031. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19032. }
  19033. #endif
  19034. //==============================================================================
  19035. // open_stream() Tests
  19036. //==============================================================================
  19037. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19038. std::string result;
  19039. char buf[8192];
  19040. ssize_t n;
  19041. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19042. result.append(buf, static_cast<size_t>(n));
  19043. }
  19044. return result;
  19045. }
  19046. // Mock stream for unit tests
  19047. class MockStream : public Stream {
  19048. public:
  19049. std::string data;
  19050. size_t pos = 0;
  19051. ssize_t error_after = -1; // -1 = no error
  19052. explicit MockStream(const std::string &d, ssize_t err = -1)
  19053. : data(d), error_after(err) {}
  19054. bool is_readable() const override { return true; }
  19055. bool wait_readable() const override { return true; }
  19056. bool wait_writable() const override { return true; }
  19057. ssize_t read(char *ptr, size_t size) override {
  19058. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19059. if (pos >= data.size()) return 0;
  19060. size_t limit =
  19061. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19062. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19063. std::memcpy(ptr, data.data() + pos, to_read);
  19064. pos += to_read;
  19065. return static_cast<ssize_t>(to_read);
  19066. }
  19067. ssize_t write(const char *, size_t) override { return -1; }
  19068. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19069. ip = "127.0.0.1";
  19070. port = 0;
  19071. }
  19072. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19073. ip = "127.0.0.1";
  19074. port = 0;
  19075. }
  19076. socket_t socket() const override { return INVALID_SOCKET; }
  19077. time_t duration() const override { return 0; }
  19078. };
  19079. TEST(StreamHandleTest, Basic) {
  19080. ClientImpl::StreamHandle handle;
  19081. EXPECT_FALSE(handle.is_valid());
  19082. handle.response = detail::make_unique<Response>();
  19083. handle.error = Error::Connection;
  19084. EXPECT_FALSE(handle.is_valid());
  19085. handle.error = Error::Success;
  19086. EXPECT_TRUE(handle.is_valid());
  19087. }
  19088. TEST(BodyReaderTest, Basic) {
  19089. MockStream stream("Hello, World!");
  19090. detail::BodyReader reader;
  19091. reader.stream = &stream;
  19092. reader.content_length = 13;
  19093. char buf[32];
  19094. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19095. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19096. EXPECT_TRUE(reader.eof);
  19097. }
  19098. TEST(BodyReaderTest, NoStream) {
  19099. detail::BodyReader reader;
  19100. char buf[32];
  19101. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19102. EXPECT_EQ(Error::Connection, reader.last_error);
  19103. }
  19104. TEST(BodyReaderTest, Error) {
  19105. MockStream stream("Hello, World!", 5);
  19106. detail::BodyReader reader;
  19107. reader.stream = &stream;
  19108. reader.content_length = 13;
  19109. char buf[32];
  19110. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19111. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19112. EXPECT_EQ(Error::Read, reader.last_error);
  19113. }
  19114. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19115. // Mock-based StreamHandle tests relying on private internals are removed.
  19116. class OpenStreamTest : public ::testing::Test {
  19117. protected:
  19118. void SetUp() override {
  19119. svr_.Get("/hello", [](const Request &, Response &res) {
  19120. res.set_content("Hello World!", "text/plain");
  19121. });
  19122. svr_.Get("/large", [](const Request &, Response &res) {
  19123. res.set_content(std::string(10000, 'X'), "text/plain");
  19124. });
  19125. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19126. res.set_content("Hello World!", "image/jpeg");
  19127. res.set_header("Content-Encoding", "UTF-8");
  19128. });
  19129. svr_.Get("/chunked", [](const Request &, Response &res) {
  19130. res.set_chunked_content_provider("text/plain",
  19131. [](size_t offset, DataSink &sink) {
  19132. if (offset < 15) {
  19133. sink.write("chunk", 5);
  19134. return true;
  19135. }
  19136. sink.done();
  19137. return true;
  19138. });
  19139. });
  19140. svr_.Get("/compressible", [](const Request &, Response &res) {
  19141. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19142. DataSink &sink) {
  19143. if (offset < 100 * 1024) {
  19144. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19145. sink.write(chunk.data(), chunk.size());
  19146. return true;
  19147. }
  19148. sink.done();
  19149. return true;
  19150. });
  19151. });
  19152. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19153. [](const Request & /*req*/, Response &res) {
  19154. auto i = new int(0);
  19155. res.set_header("Trailer", "Content-Length, X-Allowed");
  19156. res.set_chunked_content_provider(
  19157. "text/plain",
  19158. [i](size_t /*offset*/, DataSink &sink) {
  19159. switch (*i) {
  19160. case 0: sink.os << "123"; break;
  19161. case 1: sink.os << "456"; break;
  19162. case 2: sink.os << "789"; break;
  19163. case 3: {
  19164. sink.done_with_trailer(
  19165. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19166. } break;
  19167. }
  19168. (*i)++;
  19169. return true;
  19170. },
  19171. [i](bool success) {
  19172. EXPECT_TRUE(success);
  19173. delete i;
  19174. });
  19175. });
  19176. // Echo headers endpoint for header-related tests
  19177. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19178. std::string body;
  19179. for (const auto &h : req.headers) {
  19180. body.append(h.first);
  19181. body.push_back(':');
  19182. body.append(h.second);
  19183. body.push_back('\n');
  19184. }
  19185. res.set_content(body, "text/plain");
  19186. });
  19187. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19188. std::string body;
  19189. for (const auto &h : req.headers) {
  19190. body.append(h.first);
  19191. body.push_back(':');
  19192. body.append(h.second);
  19193. body.push_back('\n');
  19194. }
  19195. res.set_content(body, "text/plain");
  19196. });
  19197. port_ = svr_.bind_to_any_port("127.0.0.1");
  19198. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19199. svr_.wait_until_ready();
  19200. }
  19201. void TearDown() override {
  19202. svr_.stop();
  19203. if (thread_.joinable()) thread_.join();
  19204. }
  19205. Server svr_;
  19206. std::thread thread_;
  19207. int port_ = 0;
  19208. };
  19209. TEST_F(OpenStreamTest, Basic) {
  19210. Client cli("127.0.0.1", port_);
  19211. auto handle = cli.open_stream("GET", "/hello");
  19212. EXPECT_TRUE(handle.is_valid());
  19213. EXPECT_EQ("Hello World!", read_all(handle));
  19214. }
  19215. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19216. Client cli("127.0.0.1", port_);
  19217. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19218. ASSERT_TRUE(handle.is_valid());
  19219. EXPECT_EQ("Hello World!", read_all(handle));
  19220. }
  19221. TEST_F(OpenStreamTest, SmallBuffer) {
  19222. Client cli("127.0.0.1", port_);
  19223. auto handle = cli.open_stream("GET", "/hello");
  19224. std::string result;
  19225. char buf[4];
  19226. ssize_t n;
  19227. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19228. result.append(buf, static_cast<size_t>(n));
  19229. EXPECT_EQ("Hello World!", result);
  19230. }
  19231. TEST_F(OpenStreamTest, DefaultHeaders) {
  19232. Client cli("127.0.0.1", port_);
  19233. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19234. {
  19235. auto handle = cli.open_stream("GET", "/echo-headers");
  19236. ASSERT_TRUE(handle.is_valid());
  19237. auto body = read_all(handle);
  19238. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19239. std::string::npos);
  19240. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19241. std::string::npos);
  19242. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19243. }
  19244. // open_stream POST with body and no explicit content_type should NOT add
  19245. // text/plain Content-Type (behavior differs from non-streaming path), but
  19246. // should include Content-Length
  19247. {
  19248. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19249. ASSERT_TRUE(handle.is_valid());
  19250. auto body = read_all(handle);
  19251. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19252. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19253. }
  19254. // open_stream POST with explicit Content-Type should preserve it
  19255. {
  19256. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19257. {{"Content-Type", "application/custom"}},
  19258. "{}", "application/custom");
  19259. ASSERT_TRUE(handle.is_valid());
  19260. auto body = read_all(handle);
  19261. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19262. }
  19263. // User-specified User-Agent must not be overwritten for stream API
  19264. {
  19265. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19266. {{"User-Agent", "MyAgent/1.2"}});
  19267. ASSERT_TRUE(handle.is_valid());
  19268. auto body = read_all(handle);
  19269. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19270. }
  19271. }
  19272. TEST_F(OpenStreamTest, Large) {
  19273. Client cli("127.0.0.1", port_);
  19274. auto handle = cli.open_stream("GET", "/large");
  19275. EXPECT_EQ(10000u, read_all(handle).size());
  19276. }
  19277. TEST_F(OpenStreamTest, ConnectionError) {
  19278. Client cli("127.0.0.1", 9999);
  19279. auto handle = cli.open_stream("GET", "/hello");
  19280. EXPECT_FALSE(handle.is_valid());
  19281. }
  19282. TEST_F(OpenStreamTest, Chunked) {
  19283. Client cli("127.0.0.1", port_);
  19284. auto handle = cli.open_stream("GET", "/chunked");
  19285. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19286. "Transfer-Encoding") == "chunked");
  19287. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19288. }
  19289. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19290. Client cli("127.0.0.1", port_);
  19291. auto handle =
  19292. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19293. ASSERT_TRUE(handle.is_valid());
  19294. // Consume body to allow trailers to be received/parsed
  19295. auto body = read_all(handle);
  19296. // Explicitly parse trailers (ensure trailers are available for assertion)
  19297. handle.parse_trailers_if_needed();
  19298. EXPECT_EQ(std::string("123456789"), body);
  19299. // The response should include a Trailer header declaring both names
  19300. ASSERT_TRUE(handle.response);
  19301. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19302. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19303. handle.response->get_header_value("Trailer"));
  19304. // Prohibited trailer must not be present
  19305. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19306. // Allowed trailer should be present
  19307. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19308. EXPECT_EQ(std::string("yes"),
  19309. handle.response->get_trailer_value("X-Allowed"));
  19310. // Verify trailers are NOT present as regular headers
  19311. EXPECT_EQ(std::string(""),
  19312. handle.response->get_header_value("Content-Length"));
  19313. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19314. }
  19315. // Accepts one connection on an OS-assigned port, which it hands over through
  19316. // port_promise, reads the request head and sends back response. after_send,
  19317. // if given, runs on the connection before it is closed.
  19318. static std::thread
  19319. serve_single_response(std::promise<int> &port_promise,
  19320. const std::string &response,
  19321. std::function<void(socket_t)> after_send = nullptr) {
  19322. return std::thread([&port_promise, response, after_send] {
  19323. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19324. default_socket_options(srv);
  19325. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19326. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19327. sockaddr_in addr{};
  19328. addr.sin_family = AF_INET;
  19329. addr.sin_port = htons(0); // Let OS assign a free port
  19330. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19331. int opt = 1;
  19332. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19333. #ifdef _WIN32
  19334. reinterpret_cast<const char *>(&opt),
  19335. #else
  19336. &opt,
  19337. #endif
  19338. sizeof(opt));
  19339. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19340. ::listen(srv, 1) != 0) {
  19341. port_promise.set_value(-1);
  19342. detail::close_socket(srv);
  19343. return;
  19344. }
  19345. socklen_t addr_len = sizeof(addr);
  19346. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19347. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19348. sockaddr_in cli_addr{};
  19349. socklen_t cli_len = sizeof(cli_addr);
  19350. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19351. if (cli != INVALID_SOCKET) {
  19352. // Read the complete HTTP request (until the blank line that terminates
  19353. // headers) before sending the response. If the server closes the socket
  19354. // while the client's request data is still unread in the kernel receive
  19355. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19356. // connection on both sides: it discards the client's receive buffer
  19357. // (which already holds our response) and causes any in-progress write on
  19358. // the client to fail with ECONNRESET. Reading all request data first
  19359. // ensures close() emits a graceful FIN.
  19360. {
  19361. char rbuf[256];
  19362. std::string req;
  19363. while (req.find("\r\n\r\n") == std::string::npos) {
  19364. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19365. if (n <= 0) { break; }
  19366. req.append(rbuf, static_cast<size_t>(n));
  19367. }
  19368. }
  19369. ::send(cli,
  19370. #ifdef _WIN32
  19371. static_cast<const char *>(response.c_str()),
  19372. static_cast<int>(response.size()),
  19373. #else
  19374. response.c_str(), response.size(),
  19375. #endif
  19376. 0);
  19377. if (after_send) { after_send(cli); }
  19378. detail::close_socket(cli);
  19379. }
  19380. detail::close_socket(srv);
  19381. });
  19382. }
  19383. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19384. #ifndef _WIN32
  19385. signal(SIGPIPE, SIG_IGN);
  19386. #endif
  19387. std::promise<int> port_promise;
  19388. auto port_future = port_promise.get_future();
  19389. auto server_thread =
  19390. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19391. "Content-Type: text/plain\r\n"
  19392. "Content-Length: not-a-number\r\n"
  19393. "Connection: close\r\n"
  19394. "\r\n"
  19395. "hello");
  19396. auto port = port_future.get();
  19397. ASSERT_GT(port, 0);
  19398. Client cli("127.0.0.1", port);
  19399. auto handle = cli.open_stream("GET", "/");
  19400. EXPECT_FALSE(handle.is_valid());
  19401. server_thread.join();
  19402. }
  19403. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19404. #ifndef _WIN32
  19405. signal(SIGPIPE, SIG_IGN);
  19406. #endif
  19407. std::promise<int> port_promise;
  19408. auto port_future = port_promise.get_future();
  19409. auto server_thread = serve_single_response(
  19410. port_promise, "HTTP/1.1 200 OK\r\n"
  19411. "Content-Type: text/plain\r\n"
  19412. "Content-Length: 99999999999999999999999999\r\n"
  19413. "Connection: close\r\n"
  19414. "\r\n"
  19415. "hello");
  19416. auto port = port_future.get();
  19417. ASSERT_GT(port, 0);
  19418. // Historically std::stoull would throw std::out_of_range here and crash
  19419. // the process, then parsing silently clamped to a bogus framing length and
  19420. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19421. // so the stream fails to open, matching the not-a-number case above. The
  19422. // process still must NOT terminate.
  19423. Client cli("127.0.0.1", port);
  19424. auto handle = cli.open_stream("GET", "/");
  19425. EXPECT_FALSE(handle.is_valid());
  19426. server_thread.join();
  19427. }
  19428. // Serves `response` to the single request `fn` makes with a fresh client.
  19429. template <typename Fn>
  19430. static void with_single_response(const std::string &response, Fn fn) {
  19431. #ifndef _WIN32
  19432. signal(SIGPIPE, SIG_IGN);
  19433. #endif
  19434. std::promise<int> port_promise;
  19435. auto port_future = port_promise.get_future();
  19436. auto server_thread = serve_single_response(port_promise, response);
  19437. auto se = detail::scope_exit([&] { server_thread.join(); });
  19438. auto port = port_future.get();
  19439. ASSERT_GT(port, 0);
  19440. Client cli("127.0.0.1", port);
  19441. fn(cli);
  19442. }
  19443. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19444. const char *responses[] = {
  19445. "HTTP/1.1 103 Early Hints\r\n"
  19446. "Link: </style.css>; rel=preload\r\n"
  19447. "\r\n"
  19448. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19449. "HTTP/1.1 100 Continue\r\n"
  19450. "X-Note: interim\r\n"
  19451. "\r\n"
  19452. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19453. };
  19454. for (auto response : responses) {
  19455. with_single_response(response, [](Client &cli) {
  19456. auto res = cli.Get("/");
  19457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19458. EXPECT_EQ(StatusCode::OK_200, res->status);
  19459. EXPECT_EQ("ok", res->body);
  19460. });
  19461. }
  19462. }
  19463. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19464. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19465. const std::string final_response =
  19466. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19467. std::string interims;
  19468. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19469. interims += interim;
  19470. }
  19471. with_single_response(interims + final_response, [](Client &cli) {
  19472. auto res = cli.Get("/");
  19473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19474. EXPECT_EQ("ok", res->body);
  19475. });
  19476. with_single_response(interims + interim + final_response, [](Client &cli) {
  19477. auto res = cli.Get("/");
  19478. ASSERT_FALSE(res);
  19479. EXPECT_EQ(Error::Read, res.error());
  19480. });
  19481. }
  19482. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19483. #ifndef _WIN32
  19484. signal(SIGPIPE, SIG_IGN);
  19485. #endif
  19486. // The server answers the head without asking for the body. Bytes it then
  19487. // reads on the connection would be taken for the body the request declared.
  19488. auto closed_by_client = false;
  19489. std::promise<int> port_promise;
  19490. auto server_thread = serve_single_response(
  19491. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19492. [&](socket_t sock) {
  19493. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19494. char buf[256];
  19495. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19496. });
  19497. Client cli("127.0.0.1", port_promise.get_future().get());
  19498. cli.set_keep_alive(true);
  19499. cli.set_read_timeout(1, 0);
  19500. // Long enough for the client to send Expect: 100-continue.
  19501. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19503. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19504. cli.Get("/second");
  19505. server_thread.join();
  19506. EXPECT_TRUE(closed_by_client);
  19507. }
  19508. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19509. // Long enough for the client to send Expect: 100-continue
  19510. with_single_response(
  19511. "HTTP/1.1 103 Early Hints\r\n"
  19512. "Link: </style.css>; rel=preload\r\n"
  19513. "\r\n"
  19514. "HTTP/1.1 401 Unauthorized\r\n"
  19515. "Content-Length: 0\r\n\r\n",
  19516. [](Client &cli) {
  19517. cli.set_read_timeout(2, 0);
  19518. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19520. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19521. });
  19522. }
  19523. #ifdef CPPHTTPLIB_SSL_ENABLED
  19524. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19525. #ifndef _WIN32
  19526. signal(SIGPIPE, SIG_IGN);
  19527. #endif
  19528. auto reused = false;
  19529. std::promise<int> port_promise;
  19530. auto server_thread = serve_single_response(
  19531. port_promise,
  19532. "HTTP/1.1 401 Unauthorized\r\n"
  19533. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19534. "Content-Length: 0\r\n\r\n",
  19535. [&](socket_t sock) {
  19536. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19537. char buf[256];
  19538. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19539. });
  19540. Client cli("127.0.0.1", port_promise.get_future().get());
  19541. cli.set_keep_alive(true);
  19542. cli.set_digest_auth("user", "pass");
  19543. cli.set_read_timeout(1, 0);
  19544. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19545. server_thread.join();
  19546. EXPECT_FALSE(reused);
  19547. }
  19548. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19549. // Any other answer to CONNECT would read as the origin's response.
  19550. struct {
  19551. const char *response;
  19552. bool passed_on;
  19553. } cases[] = {
  19554. {"HTTP/1.1 201 Created\r\n"
  19555. "Set-Cookie: session=from-proxy\r\n"
  19556. "Content-Length: 0\r\n\r\n",
  19557. false},
  19558. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19559. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19560. "Content-Length: 0\r\n\r\n",
  19561. true},
  19562. };
  19563. for (const auto &c : cases) {
  19564. std::promise<int> port_promise;
  19565. auto server_thread = serve_single_response(port_promise, c.response);
  19566. SSLClient cli("example.com", 443);
  19567. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19568. auto res = cli.Get("/");
  19569. server_thread.join();
  19570. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19571. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19572. if (res) {
  19573. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19574. }
  19575. }
  19576. }
  19577. #endif
  19578. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19579. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19580. // the chunked coding and drop Content-Length, so a front-end that trusts
  19581. // Content-Length would disagree about where the body ends (response
  19582. // smuggling). The client must reject such a response.
  19583. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19584. for (const char *te : {"chunked", "gzip, chunked"}) {
  19585. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19586. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19587. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19588. "5\r\nhello\r\n0\r\n\r\n";
  19589. with_single_response(response, [&](Client &cli) {
  19590. auto res = cli.Get("/");
  19591. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19592. EXPECT_EQ(Error::Read, res.error()) << te;
  19593. });
  19594. with_single_response(response, [&](Client &cli) {
  19595. auto handle = cli.open_stream("GET", "/");
  19596. EXPECT_FALSE(handle.is_valid()) << te;
  19597. EXPECT_EQ(Error::Read, handle.error) << te;
  19598. });
  19599. }
  19600. }
  19601. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19602. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19603. // closing the connection (unlike a request, which must be rejected).
  19604. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19605. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19606. "Transfer-Encoding: chunked\r\n"
  19607. "Connection: close\r\n"
  19608. "\r\n"
  19609. "5\r\nhello\r\n0\r\n\r\n",
  19610. "HTTP/1.1 200 OK\r\n"
  19611. "Transfer-Encoding: gzip\r\n"
  19612. "Connection: close\r\n"
  19613. "\r\n"
  19614. "hello"}) {
  19615. with_single_response(response, [&](Client &cli) {
  19616. auto res = cli.Get("/");
  19617. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19618. EXPECT_EQ("hello", res->body);
  19619. });
  19620. with_single_response(response, [&](Client &cli) {
  19621. auto handle = cli.open_stream("GET", "/");
  19622. ASSERT_TRUE(handle.is_valid()) << response;
  19623. EXPECT_EQ("hello", read_all(handle));
  19624. });
  19625. }
  19626. }
  19627. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19628. // framing headers describe nothing to read and must not be rejected.
  19629. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19630. const std::string framing = "Content-Length: 5\r\n"
  19631. "Transfer-Encoding: chunked\r\n"
  19632. "Connection: close\r\n"
  19633. "\r\n";
  19634. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19635. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19636. });
  19637. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19638. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19639. });
  19640. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19641. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19642. with_single_response(response, [&](Client &cli) {
  19643. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19644. });
  19645. with_single_response(response, [&](Client &cli) {
  19646. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19647. });
  19648. }
  19649. }
  19650. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19651. // response, is faulty framing, so the connection is not reused after it.
  19652. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19653. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19654. "Content-Length: 0\r\n"
  19655. "Transfer-Encoding: chunked\r\n"
  19656. "\r\n"
  19657. "5\r\nhello\r\n0\r\n\r\n",
  19658. "HTTP/1.0 200 Connection established\r\n"
  19659. "Connection: keep-alive\r\n"
  19660. "Transfer-Encoding: chunked\r\n"
  19661. "\r\n"
  19662. "5\r\nhello\r\n0\r\n\r\n"}) {
  19663. with_single_response(response, [&](Client &cli) {
  19664. cli.set_keep_alive(true);
  19665. auto res = cli.Get("/");
  19666. ASSERT_TRUE(res) << response;
  19667. EXPECT_EQ("hello", res->body);
  19668. EXPECT_FALSE(cli.is_socket_open()) << response;
  19669. });
  19670. }
  19671. }
  19672. // A payload max length of 0 means no limit, however the body is framed.
  19673. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19674. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19675. "Transfer-Encoding: chunked\r\n"
  19676. "\r\n"
  19677. "5\r\nhello\r\n0\r\n\r\n",
  19678. "HTTP/1.1 200 OK\r\n"
  19679. "Connection: close\r\n"
  19680. "\r\n"
  19681. "hello"}) {
  19682. with_single_response(response, [&](Client &cli) {
  19683. cli.set_payload_max_length(0);
  19684. auto res = cli.Get("/");
  19685. ASSERT_TRUE(res) << response;
  19686. EXPECT_EQ("hello", res->body) << response;
  19687. });
  19688. }
  19689. }
  19690. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19691. Server svr;
  19692. svr.set_payload_max_length(0);
  19693. svr.Post("/echo", [](const Request &req, Response &res) {
  19694. res.set_content(req.body, "text/plain");
  19695. });
  19696. auto port = svr.bind_to_any_port(HOST);
  19697. thread t = thread([&] { svr.listen_after_bind(); });
  19698. auto se = detail::scope_exit([&] {
  19699. svr.stop();
  19700. t.join();
  19701. ASSERT_FALSE(svr.is_running());
  19702. });
  19703. svr.wait_until_ready();
  19704. Client cli(HOST, port);
  19705. auto res = cli.Post(
  19706. "/echo",
  19707. [](size_t /*offset*/, DataSink &sink) {
  19708. sink.write("hello", 5);
  19709. sink.done();
  19710. return true;
  19711. },
  19712. "text/plain");
  19713. ASSERT_TRUE(res);
  19714. EXPECT_EQ(StatusCode::OK_200, res->status);
  19715. EXPECT_EQ("hello", res->body);
  19716. }
  19717. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19718. TEST_F(OpenStreamTest, Gzip) {
  19719. Client cli("127.0.0.1", port_);
  19720. auto handle = cli.open_stream("GET", "/compressible", {},
  19721. {{"Accept-Encoding", "gzip"}});
  19722. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19723. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19724. }
  19725. #endif
  19726. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19727. TEST_F(OpenStreamTest, Brotli) {
  19728. Client cli("127.0.0.1", port_);
  19729. auto handle =
  19730. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19731. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19732. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19733. }
  19734. #endif
  19735. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19736. TEST_F(OpenStreamTest, Zstd) {
  19737. Client cli("127.0.0.1", port_);
  19738. auto handle = cli.open_stream("GET", "/compressible", {},
  19739. {{"Accept-Encoding", "zstd"}});
  19740. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19741. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19742. }
  19743. #endif
  19744. #ifdef CPPHTTPLIB_SSL_ENABLED
  19745. class SSLOpenStreamTest : public ::testing::Test {
  19746. protected:
  19747. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19748. void SetUp() override {
  19749. svr_.Get("/hello", [](const Request &, Response &res) {
  19750. res.set_content("Hello SSL World!", "text/plain");
  19751. });
  19752. svr_.Get("/chunked", [](const Request &, Response &res) {
  19753. res.set_chunked_content_provider("text/plain",
  19754. [](size_t offset, DataSink &sink) {
  19755. if (offset < 15) {
  19756. sink.write("chunk", 5);
  19757. return true;
  19758. }
  19759. sink.done();
  19760. return true;
  19761. });
  19762. });
  19763. svr_.Post("/echo", [](const Request &req, Response &res) {
  19764. res.set_content(req.body, req.get_header_value("Content-Type"));
  19765. });
  19766. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19767. std::string body = req.body;
  19768. res.set_chunked_content_provider(
  19769. "text/plain", [body](size_t offset, DataSink &sink) {
  19770. if (offset < body.size()) {
  19771. sink.write(body.data() + offset, body.size() - offset);
  19772. }
  19773. sink.done();
  19774. return true;
  19775. });
  19776. });
  19777. port_ = svr_.bind_to_any_port("127.0.0.1");
  19778. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19779. svr_.wait_until_ready();
  19780. }
  19781. void TearDown() override {
  19782. svr_.stop();
  19783. if (thread_.joinable()) thread_.join();
  19784. }
  19785. SSLServer svr_;
  19786. std::thread thread_;
  19787. int port_ = 0;
  19788. };
  19789. TEST_F(SSLOpenStreamTest, Basic) {
  19790. SSLClient cli("127.0.0.1", port_);
  19791. cli.enable_server_certificate_verification(false);
  19792. auto handle = cli.open_stream("GET", "/hello");
  19793. ASSERT_TRUE(handle.is_valid());
  19794. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19795. }
  19796. TEST_F(SSLOpenStreamTest, Chunked) {
  19797. SSLClient cli("127.0.0.1", port_);
  19798. cli.enable_server_certificate_verification(false);
  19799. auto handle = cli.open_stream("GET", "/chunked");
  19800. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19801. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19802. "Transfer-Encoding") == "chunked");
  19803. auto body = read_all(handle);
  19804. EXPECT_EQ("chunkchunkchunk", body);
  19805. }
  19806. TEST_F(SSLOpenStreamTest, Post) {
  19807. SSLClient cli("127.0.0.1", port_);
  19808. cli.enable_server_certificate_verification(false);
  19809. auto handle =
  19810. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19811. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19812. EXPECT_EQ(200, handle.response->status);
  19813. auto body = read_all(handle);
  19814. EXPECT_EQ("Hello SSL POST", body);
  19815. }
  19816. TEST_F(SSLOpenStreamTest, PostChunked) {
  19817. SSLClient cli("127.0.0.1", port_);
  19818. cli.enable_server_certificate_verification(false);
  19819. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19820. "Chunked SSL Data", "text/plain");
  19821. ASSERT_TRUE(handle.is_valid());
  19822. EXPECT_EQ(200, handle.response->status);
  19823. auto body = read_all(handle);
  19824. EXPECT_EQ("Chunked SSL Data", body);
  19825. }
  19826. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19827. // Content-Length is terminated by the server closing the connection. When the
  19828. // SSL peer sends a close_notify after the body, the client must treat it as a
  19829. // clean EOF and return a successful response rather than an error.
  19830. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19832. ASSERT_TRUE(svr.is_valid());
  19833. svr.set_keep_alive_max_count(1);
  19834. const std::string expected_body = "Hello from connection-close response!";
  19835. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19836. res.set_content_provider("text/plain",
  19837. [&](size_t offset, DataSink &sink) -> bool {
  19838. if (offset < expected_body.size()) {
  19839. sink.write(expected_body.data() + offset,
  19840. expected_body.size() - offset);
  19841. }
  19842. sink.done();
  19843. return true;
  19844. });
  19845. });
  19846. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19847. auto se = detail::scope_exit([&] {
  19848. svr.stop();
  19849. listen_thread.join();
  19850. ASSERT_FALSE(svr.is_running());
  19851. });
  19852. svr.wait_until_ready();
  19853. SSLClient cli(HOST, PORT);
  19854. cli.enable_server_certificate_verification(false);
  19855. auto res = cli.Get("/no-content-length");
  19856. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19857. EXPECT_EQ(StatusCode::OK_200, res->status);
  19858. EXPECT_EQ(expected_body, res->body);
  19859. }
  19860. #endif // CPPHTTPLIB_SSL_ENABLED
  19861. //==============================================================================
  19862. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19863. // results for various scenarios.
  19864. //==============================================================================
  19865. TEST(ParityTest, GetVsOpenStream) {
  19866. Server svr;
  19867. const std::string path = "/parity";
  19868. const std::string content = "Parity test content: hello world";
  19869. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19870. res.set_content(content, "text/plain");
  19871. });
  19872. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19873. auto se = detail::scope_exit([&] {
  19874. svr.stop();
  19875. t.join();
  19876. ASSERT_FALSE(svr.is_running());
  19877. });
  19878. svr.wait_until_ready();
  19879. Client cli(HOST, PORT);
  19880. // Non-stream path
  19881. auto r1 = cli.Get(path);
  19882. ASSERT_TRUE(r1);
  19883. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19884. // Stream path
  19885. auto h = cli.open_stream("GET", path);
  19886. ASSERT_TRUE(h.is_valid());
  19887. EXPECT_EQ(r1->body, read_all(h));
  19888. }
  19889. // Helper to compress data with provided compressor type T
  19890. template <typename Compressor>
  19891. static std::string compress_payload_for_parity(const std::string &in) {
  19892. std::string out;
  19893. Compressor compressor;
  19894. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19895. [&](const char *data, size_t n) {
  19896. out.append(data, n);
  19897. return true;
  19898. });
  19899. EXPECT_TRUE(ok);
  19900. return out;
  19901. }
  19902. // Helper function for compression parity tests
  19903. template <typename Compressor>
  19904. static void test_compression_parity(const std::string &original,
  19905. const std::string &path,
  19906. const std::string &encoding) {
  19907. const std::string compressed =
  19908. compress_payload_for_parity<Compressor>(original);
  19909. Server svr;
  19910. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19911. res.set_content(compressed, "application/octet-stream");
  19912. res.set_header("Content-Encoding", encoding);
  19913. });
  19914. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19915. auto se = detail::scope_exit([&] {
  19916. svr.stop();
  19917. t.join();
  19918. ASSERT_FALSE(svr.is_running());
  19919. });
  19920. svr.wait_until_ready();
  19921. Client cli(HOST, PORT);
  19922. // Non-streaming
  19923. {
  19924. auto res = cli.Get(path);
  19925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19926. EXPECT_EQ(StatusCode::OK_200, res->status);
  19927. EXPECT_EQ(original, res->body);
  19928. }
  19929. // Streaming
  19930. {
  19931. auto h = cli.open_stream("GET", path);
  19932. ASSERT_TRUE(h.is_valid());
  19933. EXPECT_EQ(original, read_all(h));
  19934. }
  19935. }
  19936. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19937. TEST(ParityTest, Gzip) {
  19938. test_compression_parity<detail::gzip_compressor>(
  19939. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19940. }
  19941. #endif
  19942. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19943. TEST(ParityTest, Brotli) {
  19944. test_compression_parity<detail::brotli_compressor>(
  19945. "Hello, brotli parity test payload", "/parity-br", "br");
  19946. }
  19947. #endif
  19948. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19949. TEST(ParityTest, Zstd) {
  19950. test_compression_parity<detail::zstd_compressor>(
  19951. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19952. }
  19953. #endif
  19954. //==============================================================================
  19955. // New Stream API Tests
  19956. //==============================================================================
  19957. inline std::string read_body(httplib::stream::Result &result) {
  19958. std::string body;
  19959. while (result.next()) {
  19960. body.append(result.data(), result.size());
  19961. }
  19962. return body;
  19963. }
  19964. TEST(ClientConnectionTest, Basic) {
  19965. httplib::ClientConnection conn;
  19966. EXPECT_FALSE(conn.is_open());
  19967. conn.sock = 1;
  19968. EXPECT_TRUE(conn.is_open());
  19969. httplib::ClientConnection conn2(std::move(conn));
  19970. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19971. conn2.sock = INVALID_SOCKET;
  19972. }
  19973. // Unified test server for all stream::* tests
  19974. class StreamApiTest : public ::testing::Test {
  19975. protected:
  19976. void SetUp() override {
  19977. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19978. res.set_content("Hello World!", "text/plain");
  19979. });
  19980. svr_.Get("/echo-params",
  19981. [](const httplib::Request &req, httplib::Response &res) {
  19982. std::string r;
  19983. for (const auto &p : req.params) {
  19984. if (!r.empty()) r += "&";
  19985. r += p.first + "=" + p.second;
  19986. }
  19987. res.set_content(r, "text/plain");
  19988. });
  19989. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19990. res.set_content(req.body, req.get_header_value("Content-Type"));
  19991. });
  19992. svr_.Post("/echo-headers",
  19993. [](const httplib::Request &req, httplib::Response &res) {
  19994. std::string r;
  19995. for (const auto &h : req.headers)
  19996. r += h.first + ": " + h.second + "\n";
  19997. res.set_content(r, "text/plain");
  19998. });
  19999. svr_.Post("/echo-params",
  20000. [](const httplib::Request &req, httplib::Response &res) {
  20001. std::string r = "params:";
  20002. for (const auto &p : req.params)
  20003. r += p.first + "=" + p.second + ";";
  20004. res.set_content(r + " body:" + req.body, "text/plain");
  20005. });
  20006. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20007. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20008. });
  20009. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20010. res.set_content("PUT:" + req.body, "text/plain");
  20011. });
  20012. svr_.Patch("/echo",
  20013. [](const httplib::Request &req, httplib::Response &res) {
  20014. res.set_content("PATCH:" + req.body, "text/plain");
  20015. });
  20016. svr_.Delete(
  20017. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20018. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20019. "text/plain");
  20020. });
  20021. svr_.Get("/head-test",
  20022. [](const httplib::Request &, httplib::Response &res) {
  20023. res.set_content("body for HEAD", "text/plain");
  20024. });
  20025. svr_.Options("/options",
  20026. [](const httplib::Request &, httplib::Response &res) {
  20027. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20028. });
  20029. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20030. svr_.wait_until_ready();
  20031. }
  20032. void TearDown() override {
  20033. svr_.stop();
  20034. if (thread_.joinable()) thread_.join();
  20035. }
  20036. httplib::Server svr_;
  20037. std::thread thread_;
  20038. };
  20039. // stream::Get tests
  20040. TEST_F(StreamApiTest, GetBasic) {
  20041. httplib::Client cli(HOST, PORT);
  20042. auto result = httplib::stream::Get(cli, "/hello");
  20043. ASSERT_TRUE(result.is_valid());
  20044. EXPECT_EQ(200, result.status());
  20045. EXPECT_EQ("Hello World!", read_body(result));
  20046. }
  20047. TEST_F(StreamApiTest, GetWithParams) {
  20048. httplib::Client cli(HOST, PORT);
  20049. httplib::Params params{{"foo", "bar"}};
  20050. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20051. ASSERT_TRUE(result.is_valid());
  20052. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20053. }
  20054. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20055. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20056. httplib::Client cli(HOST, PORT);
  20057. cli.set_payload_max_length(0);
  20058. auto result = httplib::stream::Get(cli, "/hello");
  20059. ASSERT_TRUE(result.is_valid());
  20060. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20061. EXPECT_EQ("Hello World!", read_body(result));
  20062. }
  20063. #endif
  20064. TEST_F(StreamApiTest, GetConnectionError) {
  20065. httplib::Client cli(HOST, 9999);
  20066. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20067. }
  20068. TEST_F(StreamApiTest, Get404) {
  20069. httplib::Client cli(HOST, PORT);
  20070. auto result = httplib::stream::Get(cli, "/nonexistent");
  20071. EXPECT_TRUE(result.is_valid());
  20072. EXPECT_EQ(404, result.status());
  20073. }
  20074. // stream::Post tests
  20075. TEST_F(StreamApiTest, PostBasic) {
  20076. httplib::Client cli(HOST, PORT);
  20077. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20078. "application/json");
  20079. ASSERT_TRUE(result.is_valid());
  20080. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20081. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20082. }
  20083. TEST_F(StreamApiTest, PostWithHeaders) {
  20084. httplib::Client cli(HOST, PORT);
  20085. httplib::Headers headers{{"X-Custom", "value"}};
  20086. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20087. "text/plain");
  20088. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20089. }
  20090. TEST_F(StreamApiTest, PostWithParams) {
  20091. httplib::Client cli(HOST, PORT);
  20092. httplib::Params params{{"k", "v"}};
  20093. auto result =
  20094. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20095. auto body = read_body(result);
  20096. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20097. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20098. }
  20099. TEST_F(StreamApiTest, PostLarge) {
  20100. httplib::Client cli(HOST, PORT);
  20101. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20102. size_t total = 0;
  20103. while (result.next()) {
  20104. total += result.size();
  20105. }
  20106. EXPECT_EQ(100u * 1024u, total);
  20107. }
  20108. // stream::Put/Patch tests
  20109. TEST_F(StreamApiTest, PutAndPatch) {
  20110. httplib::Client cli(HOST, PORT);
  20111. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20112. EXPECT_EQ("PUT:test", read_body(put));
  20113. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20114. EXPECT_EQ("PATCH:test", read_body(patch));
  20115. }
  20116. // stream::Delete tests
  20117. TEST_F(StreamApiTest, Delete) {
  20118. httplib::Client cli(HOST, PORT);
  20119. auto del1 = httplib::stream::Delete(cli, "/resource");
  20120. EXPECT_EQ("Deleted", read_body(del1));
  20121. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20122. EXPECT_EQ("Deleted:data", read_body(del2));
  20123. }
  20124. // stream::Head/Options tests
  20125. TEST_F(StreamApiTest, HeadAndOptions) {
  20126. httplib::Client cli(HOST, PORT);
  20127. auto head = httplib::stream::Head(cli, "/head-test");
  20128. EXPECT_TRUE(head.is_valid());
  20129. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20130. auto opts = httplib::stream::Options(cli, "/options");
  20131. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20132. }
  20133. // SSL stream::* tests
  20134. #ifdef CPPHTTPLIB_SSL_ENABLED
  20135. class SSLStreamApiTest : public ::testing::Test {
  20136. protected:
  20137. void SetUp() override {
  20138. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20139. res.set_content("Hello SSL!", "text/plain");
  20140. });
  20141. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20142. res.set_content(req.body, "text/plain");
  20143. });
  20144. port_ = svr_.bind_to_any_port("127.0.0.1");
  20145. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20146. svr_.wait_until_ready();
  20147. }
  20148. void TearDown() override {
  20149. svr_.stop();
  20150. if (thread_.joinable()) thread_.join();
  20151. }
  20152. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20153. std::thread thread_;
  20154. int port_ = 0;
  20155. };
  20156. TEST_F(SSLStreamApiTest, GetAndPost) {
  20157. httplib::SSLClient cli("127.0.0.1", port_);
  20158. cli.enable_server_certificate_verification(false);
  20159. auto get = httplib::stream::Get(cli, "/hello");
  20160. EXPECT_EQ("Hello SSL!", read_body(get));
  20161. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20162. EXPECT_EQ("test", read_body(post));
  20163. }
  20164. #endif
  20165. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20166. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20167. // BodyReader
  20168. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20169. // Test that read timeout during streaming is detected
  20170. // Use a large content-length response where server delays mid-stream
  20171. Server svr;
  20172. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20173. // Send a large response with delay in the middle
  20174. res.set_content_provider(
  20175. 1000, // content_length
  20176. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20177. if (offset < 100) {
  20178. // Send first 100 bytes immediately
  20179. std::string data(100, 'A');
  20180. sink.write(data.c_str(), data.size());
  20181. return true;
  20182. }
  20183. // Then delay longer than client timeout
  20184. std::this_thread::sleep_for(std::chrono::seconds(3));
  20185. std::string data(900, 'B');
  20186. sink.write(data.c_str(), data.size());
  20187. return true;
  20188. });
  20189. });
  20190. auto port = 8091;
  20191. std::thread t([&]() { svr.listen("localhost", port); });
  20192. svr.wait_until_ready();
  20193. Client cli("localhost", port);
  20194. cli.set_read_timeout(1, 0); // 1 second timeout
  20195. auto handle = cli.open_stream("GET", "/slow-stream");
  20196. ASSERT_TRUE(handle.is_valid());
  20197. char buf[256];
  20198. ssize_t total = 0;
  20199. ssize_t n;
  20200. bool got_error = false;
  20201. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20202. total += n;
  20203. }
  20204. if (n < 0) {
  20205. got_error = true;
  20206. // Should be timeout or read error
  20207. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20208. handle.get_read_error() == Error::Read)
  20209. << "Actual error: " << to_string(handle.get_read_error());
  20210. }
  20211. // Either we got an error, or we got less data than expected
  20212. EXPECT_TRUE(got_error || total < 1000)
  20213. << "Expected timeout but got all " << total << " bytes";
  20214. svr.stop();
  20215. t.join();
  20216. }
  20217. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20218. // Test connection closed detection via BodyReader
  20219. Server svr;
  20220. std::atomic<bool> close_now{false};
  20221. svr.Get("/will-close", [&](const Request &, Response &res) {
  20222. res.set_content_provider(
  20223. 10000, // Large content_length that we won't fully send
  20224. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20225. if (offset < 100) {
  20226. std::string data(100, 'X');
  20227. sink.write(data.c_str(), data.size());
  20228. return true;
  20229. }
  20230. // Wait for signal then abort
  20231. while (!close_now) {
  20232. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20233. }
  20234. return false; // Abort - server will close connection
  20235. });
  20236. });
  20237. auto port = 8092;
  20238. std::thread t([&]() { svr.listen("localhost", port); });
  20239. svr.wait_until_ready();
  20240. Client cli("localhost", port);
  20241. auto handle = cli.open_stream("GET", "/will-close");
  20242. ASSERT_TRUE(handle.is_valid());
  20243. char buf[256];
  20244. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20245. EXPECT_GT(n, 0) << "First read should succeed";
  20246. // Signal server to close
  20247. close_now = true;
  20248. // Keep reading until error or EOF
  20249. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20250. // Keep reading
  20251. }
  20252. // Should get an error since content_length wasn't satisfied
  20253. if (n < 0) {
  20254. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20255. handle.get_read_error() == Error::Read)
  20256. << "Actual error: " << to_string(handle.get_read_error());
  20257. }
  20258. svr.stop();
  20259. t.join();
  20260. }
  20261. #ifdef CPPHTTPLIB_SSL_ENABLED
  20262. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20263. // Test that read timeout during SSL streaming is detected
  20264. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20265. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20266. res.set_content_provider(
  20267. 1000, "text/plain",
  20268. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20269. if (offset < 100) {
  20270. std::string data(100, 'A');
  20271. sink.write(data.c_str(), data.size());
  20272. return true;
  20273. }
  20274. std::this_thread::sleep_for(std::chrono::seconds(3));
  20275. std::string data(900, 'B');
  20276. sink.write(data.c_str(), data.size());
  20277. return true;
  20278. });
  20279. });
  20280. auto port = 8093;
  20281. std::thread t([&]() { svr.listen("localhost", port); });
  20282. svr.wait_until_ready();
  20283. SSLClient cli("localhost", port);
  20284. cli.enable_server_certificate_verification(false);
  20285. cli.set_read_timeout(1, 0); // 1 second timeout
  20286. auto handle = cli.open_stream("GET", "/slow-stream");
  20287. ASSERT_TRUE(handle.is_valid());
  20288. char buf[256];
  20289. ssize_t total = 0;
  20290. ssize_t n;
  20291. bool got_error = false;
  20292. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20293. total += n;
  20294. }
  20295. if (n < 0) {
  20296. got_error = true;
  20297. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20298. handle.get_read_error() == Error::Read)
  20299. << "Actual error: " << to_string(handle.get_read_error());
  20300. }
  20301. EXPECT_TRUE(got_error || total < 1000)
  20302. << "Expected timeout but got all " << total << " bytes";
  20303. svr.stop();
  20304. t.join();
  20305. }
  20306. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20307. // Test SSL connection closed detection
  20308. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20309. std::atomic<bool> close_now{false};
  20310. svr.Get("/will-close", [&](const Request &, Response &res) {
  20311. res.set_content_provider(
  20312. 10000, "text/plain",
  20313. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20314. if (offset < 100) {
  20315. std::string data(100, 'X');
  20316. sink.write(data.c_str(), data.size());
  20317. return true;
  20318. }
  20319. while (!close_now) {
  20320. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20321. }
  20322. return false;
  20323. });
  20324. });
  20325. auto port = 8094;
  20326. std::thread t([&]() { svr.listen("localhost", port); });
  20327. svr.wait_until_ready();
  20328. SSLClient cli("localhost", port);
  20329. cli.enable_server_certificate_verification(false);
  20330. auto handle = cli.open_stream("GET", "/will-close");
  20331. ASSERT_TRUE(handle.is_valid());
  20332. char buf[256];
  20333. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20334. EXPECT_GT(n, 0);
  20335. // Signal server to close
  20336. close_now = true;
  20337. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20338. // Keep reading
  20339. }
  20340. if (n < 0) {
  20341. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20342. handle.get_read_error() == Error::Read)
  20343. << "Actual error: " << to_string(handle.get_read_error());
  20344. }
  20345. svr.stop();
  20346. t.join();
  20347. }
  20348. #endif
  20349. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20350. using namespace httplib;
  20351. // Create a test file
  20352. const char *fname = "etag_testfile.txt";
  20353. const char *content = "etag-content";
  20354. {
  20355. std::ofstream ofs(fname);
  20356. ofs << content;
  20357. ASSERT_TRUE(ofs.good());
  20358. }
  20359. Server svr;
  20360. svr.set_mount_point("/static", ".");
  20361. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20362. svr.wait_until_ready();
  20363. Client cli(HOST, PORT);
  20364. // First request: should get 200 with ETag header
  20365. auto res1 = cli.Get("/static/etag_testfile.txt");
  20366. ASSERT_TRUE(res1);
  20367. ASSERT_EQ(200, res1->status);
  20368. ASSERT_TRUE(res1->has_header("ETag"));
  20369. std::string etag = res1->get_header_value("ETag");
  20370. EXPECT_FALSE(etag.empty());
  20371. // Verify ETag format: W/"hex-hex"
  20372. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20373. EXPECT_EQ('W', etag[0]);
  20374. EXPECT_EQ('/', etag[1]);
  20375. EXPECT_EQ('"', etag[2]);
  20376. EXPECT_EQ('"', etag.back());
  20377. // Exact match: expect 304 Not Modified
  20378. Headers h2 = {{"If-None-Match", etag}};
  20379. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20380. ASSERT_TRUE(res2);
  20381. EXPECT_EQ(304, res2->status);
  20382. // Wildcard match: expect 304 Not Modified
  20383. Headers h3 = {{"If-None-Match", "*"}};
  20384. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20385. ASSERT_TRUE(res3);
  20386. EXPECT_EQ(304, res3->status);
  20387. // Non-matching ETag: expect 200
  20388. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20389. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20390. ASSERT_TRUE(res4);
  20391. EXPECT_EQ(200, res4->status);
  20392. // Multiple ETags with one matching: expect 304
  20393. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20394. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20395. ASSERT_TRUE(res5);
  20396. EXPECT_EQ(304, res5->status);
  20397. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20398. // that equivalent to the single comma-separated list above, so the match on
  20399. // the second line must still be found.
  20400. Headers h6;
  20401. h6.emplace("If-None-Match", "W/\"other\"");
  20402. h6.emplace("If-None-Match", etag);
  20403. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20404. ASSERT_TRUE(res6);
  20405. EXPECT_EQ(304, res6->status);
  20406. svr.stop();
  20407. t.join();
  20408. std::remove(fname);
  20409. }
  20410. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20411. using namespace httplib;
  20412. Server svr;
  20413. svr.set_mount_point("/static", ".");
  20414. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20415. svr.wait_until_ready();
  20416. Client cli(HOST, PORT);
  20417. // Send If-None-Match: * to a non-existent file
  20418. Headers h = {{"If-None-Match", "*"}};
  20419. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20421. EXPECT_EQ(404, res->status);
  20422. svr.stop();
  20423. t.join();
  20424. }
  20425. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20426. using namespace httplib;
  20427. // Create a test file
  20428. const char *fname = "etag_boundary_testfile.txt";
  20429. const char *content = "boundary-test";
  20430. {
  20431. std::ofstream ofs(fname);
  20432. ofs << content;
  20433. ASSERT_TRUE(ofs.good());
  20434. }
  20435. Server svr;
  20436. svr.set_mount_point("/static", ".");
  20437. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20438. svr.wait_until_ready();
  20439. Client cli(HOST, PORT);
  20440. // Get the actual ETag
  20441. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20442. ASSERT_TRUE(res1);
  20443. ASSERT_EQ(200, res1->status);
  20444. ASSERT_TRUE(res1->has_header("ETag"));
  20445. std::string etag = res1->get_header_value("ETag");
  20446. // Test 1: Very long ETag value (longer than actual ETag)
  20447. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20448. Headers h1 = {{"If-None-Match", "W/"
  20449. "\"very-long-etag-value-that-is-much-longer-"
  20450. "than-the-actual-etag-value\""}};
  20451. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20452. ASSERT_TRUE(res2);
  20453. EXPECT_EQ(200, res2->status); // Should not match
  20454. // Test 2: Long string followed by wildcard
  20455. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20456. // string)
  20457. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20458. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20459. ASSERT_TRUE(res3);
  20460. EXPECT_EQ(304, res3->status); // Should match on "*"
  20461. // Test 3: Wildcard followed by long string
  20462. // Should match on "*" immediately and return 304
  20463. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20464. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20465. ASSERT_TRUE(res4);
  20466. EXPECT_EQ(304, res4->status); // Should match on "*"
  20467. // Test 4: Multiple long non-matching values
  20468. // Should NOT match and return 200 (test that all comparisons are safe)
  20469. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20470. "W/\"second-long-non-matching-value\", "
  20471. "W/\"third-long-non-matching-value\""}};
  20472. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20473. ASSERT_TRUE(res5);
  20474. EXPECT_EQ(200, res5->status); // Should not match
  20475. // Test 5: Single character that is not "*" (edge case)
  20476. Headers h5 = {{"If-None-Match", "X"}};
  20477. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20478. ASSERT_TRUE(res6);
  20479. EXPECT_EQ(200, res6->status); // Should not match
  20480. svr.stop();
  20481. t.join();
  20482. std::remove(fname);
  20483. }
  20484. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20485. using namespace httplib;
  20486. // Create a test file
  20487. const char *fname = "ims_testfile.txt";
  20488. const char *content = "if-modified-since-test";
  20489. {
  20490. std::ofstream ofs(fname);
  20491. ofs << content;
  20492. ASSERT_TRUE(ofs.good());
  20493. }
  20494. Server svr;
  20495. svr.set_mount_point("/static", ".");
  20496. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20497. svr.wait_until_ready();
  20498. Client cli(HOST, PORT);
  20499. // First request: should get 200 with Last-Modified header
  20500. auto res1 = cli.Get("/static/ims_testfile.txt");
  20501. ASSERT_TRUE(res1);
  20502. ASSERT_EQ(200, res1->status);
  20503. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20504. std::string last_modified = res1->get_header_value("Last-Modified");
  20505. EXPECT_FALSE(last_modified.empty());
  20506. // If-Modified-Since with same time: expect 304
  20507. Headers h2 = {{"If-Modified-Since", last_modified}};
  20508. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20509. ASSERT_TRUE(res2);
  20510. EXPECT_EQ(304, res2->status);
  20511. // If-Modified-Since with future time: expect 304
  20512. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20513. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20514. ASSERT_TRUE(res3);
  20515. EXPECT_EQ(304, res3->status);
  20516. // If-Modified-Since with past time: expect 200
  20517. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20518. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20519. ASSERT_TRUE(res4);
  20520. EXPECT_EQ(200, res4->status);
  20521. // If-None-Match takes precedence over If-Modified-Since
  20522. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20523. ASSERT_TRUE(res1->has_header("ETag"));
  20524. std::string etag = res1->get_header_value("ETag");
  20525. Headers h5 = {{"If-None-Match", etag},
  20526. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20527. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20528. ASSERT_TRUE(res5);
  20529. EXPECT_EQ(304, res5->status);
  20530. svr.stop();
  20531. t.join();
  20532. std::remove(fname);
  20533. }
  20534. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20535. using namespace httplib;
  20536. Server svr;
  20537. // Endpoint that returns compressible content
  20538. svr.Get("/compressible", [](const Request &, Response &res) {
  20539. // Return a large enough body to trigger compression
  20540. std::string body(1000, 'a');
  20541. res.set_content(body, "text/plain");
  20542. });
  20543. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20544. svr.wait_until_ready();
  20545. Client cli(HOST, PORT);
  20546. // Request with gzip support: should get Vary header when compressed
  20547. cli.set_compress(true);
  20548. auto res1 = cli.Get("/compressible");
  20549. ASSERT_TRUE(res1);
  20550. EXPECT_EQ(200, res1->status);
  20551. // If Content-Encoding is set, Vary should also be set
  20552. if (res1->has_header("Content-Encoding")) {
  20553. EXPECT_TRUE(res1->has_header("Vary"));
  20554. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20555. }
  20556. // Request without Accept-Encoding header: should not have compression
  20557. Headers h_no_compress;
  20558. auto res2 = cli.Get("/compressible", h_no_compress);
  20559. ASSERT_TRUE(res2);
  20560. EXPECT_EQ(200, res2->status);
  20561. // Verify Vary header is present when compression is applied
  20562. // (the exact behavior depends on server configuration)
  20563. svr.stop();
  20564. t.join();
  20565. }
  20566. TEST(ETagTest, IfRangeWithETag) {
  20567. using namespace httplib;
  20568. // Create a test file with known content
  20569. const char *fname = "if_range_testfile.txt";
  20570. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20571. {
  20572. std::ofstream ofs(fname);
  20573. ofs << content;
  20574. ASSERT_TRUE(ofs.good());
  20575. }
  20576. Server svr;
  20577. svr.set_mount_point("/static", ".");
  20578. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20579. svr.wait_until_ready();
  20580. Client cli(HOST, PORT);
  20581. // First request: get ETag
  20582. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20583. ASSERT_TRUE(res1);
  20584. ASSERT_EQ(200, res1->status);
  20585. ASSERT_TRUE(res1->has_header("ETag"));
  20586. std::string etag = res1->get_header_value("ETag");
  20587. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20588. // Since our server generates weak ETags (W/"..."), If-Range with our
  20589. // ETag should NOT result in partial content - it should return full content.
  20590. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20591. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20592. ASSERT_TRUE(res2);
  20593. // Weak ETag in If-Range -> full content (200), not partial (206)
  20594. EXPECT_EQ(200, res2->status);
  20595. EXPECT_EQ(content, res2->body);
  20596. EXPECT_FALSE(res2->has_header("Content-Range"));
  20597. // Range request with non-matching If-Range (ETag): should get 200 (full
  20598. // content)
  20599. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20600. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20601. ASSERT_TRUE(res3);
  20602. EXPECT_EQ(200, res3->status);
  20603. EXPECT_EQ(content, res3->body);
  20604. EXPECT_FALSE(res3->has_header("Content-Range"));
  20605. // Range request with strong ETag (hypothetical - our server doesn't generate
  20606. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20607. // should return full content)
  20608. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20609. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20610. ASSERT_TRUE(res4);
  20611. EXPECT_EQ(200, res4->status);
  20612. EXPECT_EQ(content, res4->body);
  20613. EXPECT_FALSE(res4->has_header("Content-Range"));
  20614. svr.stop();
  20615. t.join();
  20616. std::remove(fname);
  20617. }
  20618. TEST(ETagTest, IfRangeWithDate) {
  20619. using namespace httplib;
  20620. // Create a test file
  20621. const char *fname = "if_range_date_testfile.txt";
  20622. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  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(HOST, PORT); });
  20631. svr.wait_until_ready();
  20632. Client cli(HOST, PORT);
  20633. // First request: get Last-Modified
  20634. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20635. ASSERT_TRUE(res1);
  20636. ASSERT_EQ(200, res1->status);
  20637. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20638. std::string last_modified = res1->get_header_value("Last-Modified");
  20639. // Range request with matching If-Range (date): should get 206
  20640. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20641. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20642. ASSERT_TRUE(res2);
  20643. EXPECT_EQ(206, res2->status);
  20644. EXPECT_EQ("FGHIJ", res2->body);
  20645. // Range request with old If-Range date: should get 200 (full content)
  20646. Headers h3 = {{"Range", "bytes=5-9"},
  20647. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20648. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20649. ASSERT_TRUE(res3);
  20650. EXPECT_EQ(200, res3->status);
  20651. EXPECT_EQ(content, res3->body);
  20652. // Range request with future If-Range date: should get 206
  20653. Headers h4 = {{"Range", "bytes=0-4"},
  20654. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20655. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20656. ASSERT_TRUE(res4);
  20657. EXPECT_EQ(206, res4->status);
  20658. EXPECT_EQ("ABCDE", res4->body);
  20659. svr.stop();
  20660. t.join();
  20661. std::remove(fname);
  20662. }
  20663. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20664. using namespace httplib;
  20665. const char *fname = "etag_malformed.txt";
  20666. const char *content = "malformed-etag";
  20667. {
  20668. std::ofstream ofs(fname);
  20669. ofs << content;
  20670. ASSERT_TRUE(ofs.good());
  20671. }
  20672. Server svr;
  20673. svr.set_mount_point("/static", ".");
  20674. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20675. svr.wait_until_ready();
  20676. Client cli(HOST, PORT);
  20677. // baseline: should get 200 and an ETag
  20678. auto res1 = cli.Get("/static/etag_malformed.txt");
  20679. ASSERT_TRUE(res1);
  20680. ASSERT_EQ(200, res1->status);
  20681. ASSERT_TRUE(res1->has_header("ETag"));
  20682. // Malformed ETag value (missing quotes) should be treated as non-matching
  20683. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20684. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20685. ASSERT_TRUE(res_bad);
  20686. EXPECT_EQ(200, res_bad->status);
  20687. // Whitespace-only header value should be considered invalid / non-matching
  20688. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20689. "Host: localhost\r\n"
  20690. "If-None-Match: \r\n"
  20691. "Connection: close\r\n"
  20692. "\r\n";
  20693. std::string out;
  20694. ASSERT_TRUE(send_request(5, raw_req, &out));
  20695. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20696. svr.stop();
  20697. t.join();
  20698. std::remove(fname);
  20699. }
  20700. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20701. using namespace httplib;
  20702. const char *fname = "ims_invalid_format.txt";
  20703. const char *content = "ims-bad-format";
  20704. {
  20705. std::ofstream ofs(fname);
  20706. ofs << content;
  20707. ASSERT_TRUE(ofs.good());
  20708. }
  20709. Server svr;
  20710. svr.set_mount_point("/static", ".");
  20711. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20712. svr.wait_until_ready();
  20713. Client cli(HOST, PORT);
  20714. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20715. ASSERT_TRUE(res1);
  20716. ASSERT_EQ(200, res1->status);
  20717. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20718. // If-Modified-Since with invalid format should not result in 304
  20719. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20720. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20721. ASSERT_TRUE(res_bad);
  20722. EXPECT_EQ(200, res_bad->status);
  20723. // If-Range with invalid date format should be treated as mismatch -> full
  20724. // content (200)
  20725. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20726. {"If-Range", "invalid-date"}};
  20727. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20728. ASSERT_TRUE(res_ifrange);
  20729. EXPECT_EQ(200, res_ifrange->status);
  20730. svr.stop();
  20731. t.join();
  20732. std::remove(fname);
  20733. }
  20734. TEST(ETagTest, IfRangeWithMalformedETag) {
  20735. using namespace httplib;
  20736. const char *fname = "ifrange_malformed.txt";
  20737. const std::string content = "0123456789";
  20738. {
  20739. std::ofstream ofs(fname);
  20740. ofs << content;
  20741. ASSERT_TRUE(ofs.good());
  20742. }
  20743. Server svr;
  20744. svr.set_mount_point("/static", ".");
  20745. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20746. svr.wait_until_ready();
  20747. Client cli(HOST, PORT);
  20748. // First request: get ETag
  20749. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20750. ASSERT_TRUE(res1);
  20751. ASSERT_EQ(200, res1->status);
  20752. ASSERT_TRUE(res1->has_header("ETag"));
  20753. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20754. // full content (200)
  20755. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20756. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20757. ASSERT_TRUE(res2);
  20758. EXPECT_EQ(200, res2->status);
  20759. EXPECT_EQ(content, res2->body);
  20760. svr.stop();
  20761. t.join();
  20762. std::remove(fname);
  20763. }
  20764. TEST(ETagTest, ExtremeLargeDateValues) {
  20765. using namespace httplib;
  20766. const char *fname = "ims_extreme_date.txt";
  20767. const char *content = "ims-extreme-date";
  20768. {
  20769. std::ofstream ofs(fname);
  20770. ofs << content;
  20771. ASSERT_TRUE(ofs.good());
  20772. }
  20773. Server svr;
  20774. svr.set_mount_point("/static", ".");
  20775. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20776. svr.wait_until_ready();
  20777. Client cli(HOST, PORT);
  20778. auto res1 = cli.Get(std::string("/static/") + fname);
  20779. ASSERT_TRUE(res1);
  20780. ASSERT_EQ(200, res1->status);
  20781. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20782. // Extremely large year that may overflow date parsing routines.
  20783. Headers h_large_date = {
  20784. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20785. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20786. ASSERT_TRUE(res_bad);
  20787. // Expect server to treat this as invalid/mismatch and return full content
  20788. EXPECT_EQ(200, res_bad->status);
  20789. // If-Range with extremely large date should be treated as mismatch -> full
  20790. // content (200)
  20791. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20792. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20793. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20794. ASSERT_TRUE(res_ifrange);
  20795. EXPECT_EQ(200, res_ifrange->status);
  20796. svr.stop();
  20797. t.join();
  20798. std::remove(fname);
  20799. }
  20800. TEST(ETagTest, NegativeFileModificationTime) {
  20801. using namespace httplib;
  20802. const char *fname = "ims_negative_mtime.txt";
  20803. const std::string content = "negative-mtime";
  20804. {
  20805. std::ofstream ofs(fname);
  20806. ofs << content;
  20807. ASSERT_TRUE(ofs.good());
  20808. }
  20809. // Try to set file mtime to a negative value. This may fail on some
  20810. // platforms/filesystems; if it fails, the test will still verify server
  20811. // behaves safely by performing a regular conditional request.
  20812. #if defined(__APPLE__) || defined(__linux__)
  20813. bool set_negative = false;
  20814. do {
  20815. struct timeval times[2];
  20816. // access time: now
  20817. times[0].tv_sec = time(nullptr);
  20818. times[0].tv_usec = 0;
  20819. // modification time: negative (e.g., -1)
  20820. times[1].tv_sec = -1;
  20821. times[1].tv_usec = 0;
  20822. if (utimes(fname, times) == 0) { set_negative = true; }
  20823. } while (0);
  20824. #else
  20825. bool set_negative = false;
  20826. #endif
  20827. Server svr;
  20828. svr.set_mount_point("/static", ".");
  20829. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20830. svr.wait_until_ready();
  20831. Client cli(HOST, PORT);
  20832. auto res1 = cli.Get(std::string("/static/") + fname);
  20833. ASSERT_TRUE(res1);
  20834. ASSERT_EQ(200, res1->status);
  20835. bool has_last_modified = res1->has_header("Last-Modified");
  20836. std::string last_modified;
  20837. if (has_last_modified) {
  20838. last_modified = res1->get_header_value("Last-Modified");
  20839. }
  20840. if (set_negative) {
  20841. // If we successfully set a negative mtime, ensure server returns a
  20842. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20843. // with an old date and ensure server handles it without crash.
  20844. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20845. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20846. ASSERT_TRUE(res2);
  20847. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20848. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20849. } else {
  20850. // Could not set negative mtime on this platform; fall back to verifying
  20851. // that normal invalid/malformed dates are treated safely (non-304).
  20852. Headers h_bad_date = {
  20853. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20854. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20855. ASSERT_TRUE(res_bad);
  20856. EXPECT_EQ(200, res_bad->status);
  20857. }
  20858. svr.stop();
  20859. t.join();
  20860. std::remove(fname);
  20861. }
  20862. //==============================================================================
  20863. // Integration Tests with Server
  20864. //==============================================================================
  20865. class SSEIntegrationTest : public ::testing::Test {
  20866. protected:
  20867. void SetUp() override {
  20868. stop_server_.store(false);
  20869. events_.clear();
  20870. server_ = httplib::detail::make_unique<Server>();
  20871. setup_server();
  20872. start_server();
  20873. }
  20874. void TearDown() override {
  20875. stop_server_.store(true);
  20876. event_cv_.notify_all();
  20877. server_->stop();
  20878. if (server_thread_.joinable()) { server_thread_.join(); }
  20879. }
  20880. void setup_server() {
  20881. // Simple SSE endpoint
  20882. server_->Get("/events", [this](const Request &req, Response &res) {
  20883. auto last_id = req.get_header_value("Last-Event-ID");
  20884. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20885. res.set_chunked_content_provider(
  20886. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20887. std::unique_lock<std::mutex> lock(event_mutex_);
  20888. if (event_cv_.wait_for(
  20889. lock, std::chrono::milliseconds(200), [this] {
  20890. return !events_.empty() || stop_server_.load();
  20891. })) {
  20892. if (stop_server_.load()) { return false; }
  20893. if (!events_.empty()) {
  20894. std::string event = events_.front();
  20895. events_.erase(events_.begin());
  20896. sink.write(event.data(), event.size());
  20897. return true;
  20898. }
  20899. }
  20900. return !stop_server_.load();
  20901. });
  20902. });
  20903. // Endpoint that returns error
  20904. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20905. res.status = 500;
  20906. res.set_content("Internal Server Error", "text/plain");
  20907. });
  20908. // Endpoint for custom event types
  20909. server_->Get("/custom-events", [](const Request &, Response &res) {
  20910. res.set_chunked_content_provider(
  20911. "text/event-stream", [](size_t offset, DataSink &sink) {
  20912. if (offset == 0) {
  20913. std::string event = "event: update\ndata: updated\n\n"
  20914. "event: delete\ndata: deleted\n\n";
  20915. sink.write(event.data(), event.size());
  20916. }
  20917. return false; // End stream after sending
  20918. });
  20919. });
  20920. }
  20921. void start_server() {
  20922. port_ = server_->bind_to_any_port(HOST);
  20923. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20924. // Wait for server to start
  20925. while (!server_->is_running()) {
  20926. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20927. }
  20928. }
  20929. int get_port() const { return port_; }
  20930. void send_event(const std::string &event) {
  20931. std::lock_guard<std::mutex> lock(event_mutex_);
  20932. events_.push_back(event);
  20933. event_cv_.notify_all();
  20934. }
  20935. std::unique_ptr<Server> server_;
  20936. std::thread server_thread_;
  20937. std::mutex event_mutex_;
  20938. std::condition_variable event_cv_;
  20939. std::vector<std::string> events_;
  20940. std::atomic<bool> stop_server_{false};
  20941. std::string last_received_event_id_;
  20942. int port_ = 0;
  20943. };
  20944. //==============================================================================
  20945. // SSE Parsing Tests
  20946. //==============================================================================
  20947. class SSEParsingTest : public SSEIntegrationTest {
  20948. protected:
  20949. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20950. // A trailing sentinel event tells when the whole stream has been parsed.
  20951. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20952. auto body = stream + "event: end\ndata: end\n\n";
  20953. server_->Get("/parse", [body](const Request &, Response &res) {
  20954. res.set_content(body, "text/event-stream");
  20955. });
  20956. return collect("/parse");
  20957. }
  20958. // Runs SSEClient against path until an "end" event arrives and returns the
  20959. // messages dispatched before it
  20960. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20961. Client client(HOST, get_port());
  20962. sse::SSEClient sse(client, path);
  20963. std::mutex mutex;
  20964. std::condition_variable cv;
  20965. std::vector<sse::SSEMessage> messages;
  20966. auto done = false;
  20967. sse.on_message([&](const sse::SSEMessage &msg) {
  20968. std::lock_guard<std::mutex> lock(mutex);
  20969. // Ignore a replay from a reconnect that races with stop()
  20970. if (!done) { messages.push_back(msg); }
  20971. });
  20972. sse.on_event("end", [&](const sse::SSEMessage &) {
  20973. std::lock_guard<std::mutex> lock(mutex);
  20974. done = true;
  20975. cv.notify_all();
  20976. });
  20977. sse.set_reconnect_interval(100);
  20978. sse.start_async();
  20979. {
  20980. std::unique_lock<std::mutex> lock(mutex);
  20981. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20982. }
  20983. sse.stop();
  20984. EXPECT_TRUE(done);
  20985. return messages;
  20986. }
  20987. };
  20988. TEST_F(SSEParsingTest, SingleLineData) {
  20989. auto msgs = parse("data: hello\n\n");
  20990. ASSERT_EQ(msgs.size(), 1u);
  20991. EXPECT_EQ(msgs[0].data, "hello");
  20992. EXPECT_EQ(msgs[0].event, "message");
  20993. }
  20994. TEST_F(SSEParsingTest, MultiLineData) {
  20995. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20996. ASSERT_EQ(msgs.size(), 1u);
  20997. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20998. }
  20999. TEST_F(SSEParsingTest, CustomEventType) {
  21000. auto msgs = parse("event: update\ndata: payload\n\n");
  21001. ASSERT_EQ(msgs.size(), 1u);
  21002. EXPECT_EQ(msgs[0].event, "update");
  21003. EXPECT_EQ(msgs[0].data, "payload");
  21004. }
  21005. TEST_F(SSEParsingTest, EventIdHandling) {
  21006. auto msgs = parse("id: 12345\ndata: test\n\n");
  21007. ASSERT_EQ(msgs.size(), 1u);
  21008. EXPECT_EQ(msgs[0].id, "12345");
  21009. }
  21010. TEST_F(SSEParsingTest, EmptyEventId) {
  21011. auto msgs = parse("id:\ndata: test\n\n");
  21012. ASSERT_EQ(msgs.size(), 1u);
  21013. EXPECT_EQ(msgs[0].id, "");
  21014. }
  21015. TEST_F(SSEParsingTest, CommentsIgnored) {
  21016. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21017. ASSERT_EQ(msgs.size(), 1u);
  21018. EXPECT_EQ(msgs[0].data, "hello");
  21019. EXPECT_EQ(msgs[0].event, "message");
  21020. }
  21021. TEST_F(SSEParsingTest, ColonInValue) {
  21022. auto msgs = parse("data: hello:world:test\n\n");
  21023. ASSERT_EQ(msgs.size(), 1u);
  21024. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21025. }
  21026. TEST_F(SSEParsingTest, FieldNameOnly) {
  21027. // A line without a colon is a field name with an empty value
  21028. auto msgs = parse("data\n\n");
  21029. ASSERT_EQ(msgs.size(), 1u);
  21030. EXPECT_EQ(msgs[0].data, "");
  21031. }
  21032. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21033. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21034. ASSERT_EQ(msgs.size(), 1u);
  21035. EXPECT_EQ(msgs[0].event, "update");
  21036. EXPECT_EQ(msgs[0].data, "hello");
  21037. }
  21038. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21039. auto msgs = parse("data\r\n\r\n");
  21040. ASSERT_EQ(msgs.size(), 1u);
  21041. EXPECT_EQ(msgs[0].data, "");
  21042. }
  21043. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21044. auto msgs = parse("event: update\rdata: hello\r\r");
  21045. ASSERT_EQ(msgs.size(), 1u);
  21046. EXPECT_EQ(msgs[0].event, "update");
  21047. EXPECT_EQ(msgs[0].data, "hello");
  21048. }
  21049. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21050. // Chunk boundaries fall inside every \r\n and right before the first one
  21051. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21052. "\n\r", "\nevent: end\ndata: end\n\n"};
  21053. server_->Get("/split", [chunks](const Request &, Response &res) {
  21054. auto i = std::make_shared<size_t>(0);
  21055. res.set_chunked_content_provider(
  21056. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21057. if (*i == chunks.size()) {
  21058. sink.done();
  21059. } else {
  21060. sink.write(chunks[*i].data(), chunks[*i].size());
  21061. (*i)++;
  21062. }
  21063. return true;
  21064. });
  21065. });
  21066. auto msgs = collect("/split");
  21067. ASSERT_EQ(msgs.size(), 1u);
  21068. EXPECT_EQ(msgs[0].event, "update");
  21069. EXPECT_EQ(msgs[0].data, "hello");
  21070. }
  21071. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21072. // Only a BOM at the start of the stream is ignored
  21073. auto msgs = parse("\xEF\xBB\xBF"
  21074. "data: first\n\n"
  21075. "\xEF\xBB\xBF"
  21076. "data: second\n\n");
  21077. ASSERT_EQ(msgs.size(), 1u);
  21078. EXPECT_EQ(msgs[0].data, "first");
  21079. }
  21080. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21081. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21082. ASSERT_EQ(msgs.size(), 1u);
  21083. EXPECT_EQ(msgs[0].data, "hello");
  21084. EXPECT_EQ(msgs[0].event, "message");
  21085. }
  21086. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21087. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21088. ASSERT_EQ(msgs.size(), 2u);
  21089. EXPECT_EQ(msgs[0].data, "hello");
  21090. EXPECT_EQ(msgs[1].data, "hello");
  21091. }
  21092. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21093. // An event without data is not dispatched, and its type must not leak
  21094. // into the next event
  21095. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21096. ASSERT_EQ(msgs.size(), 1u);
  21097. EXPECT_EQ(msgs[0].event, "message");
  21098. EXPECT_EQ(msgs[0].data, "hello");
  21099. }
  21100. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21101. // The first connection sends only an id; the second echoes back the
  21102. // Last-Event-ID it was reconnected with
  21103. std::atomic<int> connection_count{0};
  21104. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21105. if (connection_count++ == 0) {
  21106. res.set_content("id: 42\n\n", "text/event-stream");
  21107. } else {
  21108. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21109. "\n\nevent: end\ndata: end\n\n",
  21110. "text/event-stream");
  21111. }
  21112. });
  21113. auto msgs = collect("/id-only");
  21114. ASSERT_EQ(msgs.size(), 1u);
  21115. EXPECT_EQ(msgs[0].data, "42");
  21116. }
  21117. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21118. // The first connection sets an id and then clears it with an empty one; the
  21119. // second reports whether it was reconnected with a Last-Event-ID
  21120. std::atomic<int> connection_count{0};
  21121. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21122. if (connection_count++ == 0) {
  21123. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21124. "text/event-stream");
  21125. } else {
  21126. res.set_content(
  21127. std::string("data: ") +
  21128. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21129. "\n\nevent: end\ndata: end\n\n",
  21130. "text/event-stream");
  21131. }
  21132. });
  21133. auto msgs = collect("/id-clear");
  21134. ASSERT_EQ(msgs.size(), 3u);
  21135. EXPECT_EQ(msgs[0].id, "1");
  21136. EXPECT_EQ(msgs[1].id, "");
  21137. EXPECT_EQ(msgs[2].data, "not sent");
  21138. }
  21139. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21140. // The first connection sets an id and then sends ids that cannot be carried
  21141. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21142. // with
  21143. std::atomic<int> connection_count{0};
  21144. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21145. if (connection_count++ == 0) {
  21146. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21147. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21148. "text/event-stream");
  21149. } else {
  21150. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21151. "\n\nevent: end\ndata: end\n\n",
  21152. "text/event-stream");
  21153. }
  21154. });
  21155. auto msgs = collect("/id-unsendable");
  21156. ASSERT_EQ(msgs.size(), 1u);
  21157. EXPECT_EQ(msgs[0].data, "42");
  21158. }
  21159. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21160. auto msgs = parse("event: notification\nid: evt-42\n"
  21161. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21162. ASSERT_EQ(msgs.size(), 1u);
  21163. EXPECT_EQ(msgs[0].event, "notification");
  21164. EXPECT_EQ(msgs[0].id, "evt-42");
  21165. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21166. }
  21167. TEST(SSEMessageTest, Clear) {
  21168. sse::SSEMessage msg;
  21169. msg.event = "custom";
  21170. msg.data = "some data";
  21171. msg.id = "123";
  21172. msg.clear();
  21173. EXPECT_EQ(msg.event, "message");
  21174. EXPECT_EQ(msg.data, "");
  21175. EXPECT_EQ(msg.id, "");
  21176. }
  21177. //==============================================================================
  21178. // SSE Integration Tests
  21179. //==============================================================================
  21180. // Test: Successful connection and on_open callback
  21181. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21182. // Add a simple endpoint that sends one event and closes
  21183. server_->Get("/simple-event", [](const Request &, Response &res) {
  21184. res.set_chunked_content_provider(
  21185. "text/event-stream", [](size_t offset, DataSink &sink) {
  21186. if (offset == 0) {
  21187. std::string event = "data: hello\n\n";
  21188. sink.write(event.data(), event.size());
  21189. }
  21190. return false; // Close stream after sending
  21191. });
  21192. });
  21193. Client client("localhost", get_port());
  21194. sse::SSEClient sse(client, "/simple-event");
  21195. std::atomic<bool> open_called{false};
  21196. std::atomic<bool> message_received{false};
  21197. sse.on_open([&open_called]() { open_called.store(true); });
  21198. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21199. if (msg.data == "hello") { message_received.store(true); }
  21200. });
  21201. sse.set_reconnect_interval(100);
  21202. sse.set_max_reconnect_attempts(1);
  21203. // Start async
  21204. sse.start_async();
  21205. // Wait for message to be processed
  21206. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21207. sse.stop();
  21208. EXPECT_TRUE(open_called.load());
  21209. EXPECT_TRUE(message_received.load());
  21210. }
  21211. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21212. // A data line that never ends.
  21213. server_->Get("/endless-line", [](const Request &, Response &res) {
  21214. res.set_chunked_content_provider(
  21215. "text/event-stream", [](size_t offset, DataSink &sink) {
  21216. if (offset == 0) { sink.write("data: ", 6); }
  21217. std::string chunk(64 * 1024, 'A');
  21218. return sink.write(chunk.data(), chunk.size());
  21219. });
  21220. });
  21221. Client client("localhost", get_port());
  21222. sse::SSEClient sse(client, "/endless-line");
  21223. std::atomic<bool> too_long{false};
  21224. sse.on_error([&](Error err) {
  21225. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21226. });
  21227. sse.set_max_reconnect_attempts(1);
  21228. sse.start_async();
  21229. for (int i = 0; i < 500 && !too_long; i++) {
  21230. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21231. }
  21232. sse.stop();
  21233. EXPECT_TRUE(too_long);
  21234. }
  21235. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21236. // Far more in all than the client's payload limit below.
  21237. server_->Get("/many-events", [](const Request &, Response &res) {
  21238. res.set_chunked_content_provider(
  21239. "text/event-stream", [](size_t offset, DataSink &sink) {
  21240. if (offset == 0) {
  21241. std::string events;
  21242. for (int i = 0; i < 1000; i++) {
  21243. events += "data: message\n\n";
  21244. }
  21245. sink.write(events.data(), events.size());
  21246. }
  21247. return false;
  21248. });
  21249. });
  21250. Client client("localhost", get_port());
  21251. client.set_payload_max_length(1024);
  21252. sse::SSEClient sse(client, "/many-events");
  21253. std::atomic<int> messages{0};
  21254. std::atomic<bool> too_large{false};
  21255. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21256. sse.on_error([&](Error err) {
  21257. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21258. });
  21259. sse.set_max_reconnect_attempts(1);
  21260. sse.start_async();
  21261. for (int i = 0; i < 500 && messages < 1000; i++) {
  21262. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21263. }
  21264. sse.stop();
  21265. EXPECT_GE(messages.load(), 1000);
  21266. EXPECT_FALSE(too_large);
  21267. }
  21268. // Test: on_message callback
  21269. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21270. // Endpoint that sends multiple events then closes
  21271. server_->Get("/multi-event", [](const Request &, Response &res) {
  21272. res.set_chunked_content_provider(
  21273. "text/event-stream", [](size_t offset, DataSink &sink) {
  21274. if (offset == 0) {
  21275. std::string events = "data: message1\n\ndata: message2\n\n";
  21276. sink.write(events.data(), events.size());
  21277. }
  21278. return false;
  21279. });
  21280. });
  21281. Client client("localhost", get_port());
  21282. sse::SSEClient sse(client, "/multi-event");
  21283. std::vector<std::string> received_messages;
  21284. std::mutex messages_mutex;
  21285. sse.on_message([&](const sse::SSEMessage &msg) {
  21286. std::lock_guard<std::mutex> lock(messages_mutex);
  21287. received_messages.push_back(msg.data);
  21288. });
  21289. sse.set_reconnect_interval(100);
  21290. sse.set_max_reconnect_attempts(1);
  21291. sse.start_async();
  21292. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21293. sse.stop();
  21294. std::lock_guard<std::mutex> lock(messages_mutex);
  21295. EXPECT_GE(received_messages.size(), 2u);
  21296. if (received_messages.size() >= 2) {
  21297. EXPECT_EQ(received_messages[0], "message1");
  21298. EXPECT_EQ(received_messages[1], "message2");
  21299. }
  21300. }
  21301. // Test: on_event for specific types
  21302. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21303. Client client("localhost", get_port());
  21304. sse::SSEClient sse(client, "/custom-events");
  21305. std::atomic<bool> update_received{false};
  21306. std::atomic<bool> delete_received{false};
  21307. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21308. if (msg.data == "updated") { update_received.store(true); }
  21309. });
  21310. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21311. if (msg.data == "deleted") { delete_received.store(true); }
  21312. });
  21313. sse.set_max_reconnect_attempts(1);
  21314. sse.start_async();
  21315. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21316. sse.stop();
  21317. EXPECT_TRUE(update_received.load());
  21318. EXPECT_TRUE(delete_received.load());
  21319. }
  21320. // Test: on_error callback on connection failure
  21321. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21322. // Connect to a non-existent port
  21323. Client client("localhost", 59999);
  21324. sse::SSEClient sse(client, "/events");
  21325. std::atomic<bool> error_called{false};
  21326. Error received_error = Error::Success;
  21327. sse.on_error([&](Error err) {
  21328. error_called.store(true);
  21329. received_error = err;
  21330. });
  21331. sse.set_reconnect_interval(50);
  21332. sse.set_max_reconnect_attempts(1);
  21333. sse.start_async();
  21334. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21335. sse.stop();
  21336. EXPECT_TRUE(error_called.load());
  21337. EXPECT_NE(received_error, Error::Success);
  21338. }
  21339. // Test: Last-Event-ID header sent on reconnect
  21340. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21341. // Endpoint that sends event with ID
  21342. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21343. res.set_chunked_content_provider(
  21344. "text/event-stream", [](size_t offset, DataSink &sink) {
  21345. if (offset == 0) {
  21346. std::string event = "id: evt-123\ndata: test\n\n";
  21347. sink.write(event.data(), event.size());
  21348. }
  21349. return false;
  21350. });
  21351. });
  21352. Client client("localhost", get_port());
  21353. sse::SSEClient sse(client, "/event-with-id");
  21354. std::atomic<bool> id_received{false};
  21355. sse.on_message([&](const sse::SSEMessage &msg) {
  21356. if (!msg.id.empty()) { id_received.store(true); }
  21357. });
  21358. sse.set_reconnect_interval(100);
  21359. sse.set_max_reconnect_attempts(1);
  21360. sse.start_async();
  21361. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21362. sse.stop();
  21363. EXPECT_TRUE(id_received.load());
  21364. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21365. }
  21366. // Test: Manual stop
  21367. TEST_F(SSEIntegrationTest, ManualStop) {
  21368. // Endpoint that sends one event and stays open briefly
  21369. std::atomic<bool> handler_running{true};
  21370. server_->Get("/stay-open", [&handler_running](const Request &,
  21371. Response &res) {
  21372. res.set_chunked_content_provider(
  21373. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  21374. if (offset == 0) {
  21375. std::string event = "data: connected\n\n";
  21376. sink.write(event.data(), event.size());
  21377. }
  21378. // Keep connection open while handler_running is true
  21379. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  21380. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21381. }
  21382. return false;
  21383. });
  21384. });
  21385. Client client("localhost", get_port());
  21386. sse::SSEClient sse(client, "/stay-open");
  21387. std::atomic<bool> connected{false};
  21388. sse.on_open([&connected]() { connected.store(true); });
  21389. sse.set_reconnect_interval(100);
  21390. sse.set_max_reconnect_attempts(1);
  21391. sse.start_async();
  21392. // Wait for connection to establish
  21393. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21394. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21395. }
  21396. EXPECT_TRUE(connected.load());
  21397. EXPECT_TRUE(sse.is_connected());
  21398. // Signal handler to stop
  21399. handler_running.store(false);
  21400. // Stop SSE client
  21401. sse.stop();
  21402. EXPECT_FALSE(sse.is_connected());
  21403. }
  21404. // Test: SSEClient with custom headers
  21405. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21406. // Setup a server endpoint that checks for custom header
  21407. std::atomic<bool> header_received{false};
  21408. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21409. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21410. header_received.store(true);
  21411. }
  21412. res.set_chunked_content_provider("text/event-stream",
  21413. [](size_t, DataSink &) { return false; });
  21414. });
  21415. Client client("localhost", get_port());
  21416. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21417. sse::SSEClient sse(client, "/header-check", headers);
  21418. sse.set_max_reconnect_attempts(1);
  21419. sse.start_async();
  21420. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21421. sse.stop();
  21422. EXPECT_TRUE(header_received.load());
  21423. }
  21424. // Test: Reconnect interval configuration
  21425. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21426. Client client("localhost", get_port());
  21427. sse::SSEClient sse(client, "/events");
  21428. auto &result = sse.set_reconnect_interval(500);
  21429. // Builder pattern should return reference to self
  21430. EXPECT_EQ(&result, &sse);
  21431. }
  21432. // Test: Max reconnect attempts
  21433. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21434. // Connect to non-existent port to force reconnects
  21435. Client client("localhost", 59998);
  21436. sse::SSEClient sse(client, "/events");
  21437. std::atomic<int> error_count{0};
  21438. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21439. sse.set_reconnect_interval(50);
  21440. sse.set_max_reconnect_attempts(2);
  21441. auto start = std::chrono::steady_clock::now();
  21442. sse.start(); // Blocking call
  21443. auto end = std::chrono::steady_clock::now();
  21444. // Should have stopped after 2 failed attempts
  21445. EXPECT_GE(error_count.load(), 2);
  21446. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21447. auto duration =
  21448. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21449. #ifdef _WIN32
  21450. // Windows is much slower for socket connection failures
  21451. EXPECT_LT(duration.count(), 7000);
  21452. #else
  21453. EXPECT_LT(duration.count(), 1000);
  21454. #endif
  21455. }
  21456. // Test: Multi-line data in integration
  21457. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21458. // Endpoint with multi-line data
  21459. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21460. res.set_chunked_content_provider(
  21461. "text/event-stream", [](size_t offset, DataSink &sink) {
  21462. if (offset == 0) {
  21463. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21464. sink.write(event.data(), event.size());
  21465. }
  21466. return false;
  21467. });
  21468. });
  21469. Client client("localhost", get_port());
  21470. sse::SSEClient sse(client, "/multiline-data");
  21471. std::string received_data;
  21472. std::mutex data_mutex;
  21473. sse.on_message([&](const sse::SSEMessage &msg) {
  21474. std::lock_guard<std::mutex> lock(data_mutex);
  21475. received_data = msg.data;
  21476. });
  21477. sse.set_reconnect_interval(100);
  21478. sse.set_max_reconnect_attempts(1);
  21479. sse.start_async();
  21480. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21481. sse.stop();
  21482. std::lock_guard<std::mutex> lock(data_mutex);
  21483. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21484. }
  21485. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21486. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21487. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21488. DataSink &sink) {
  21489. if (offset == 0) {
  21490. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21491. sink.write(events.data(), events.size());
  21492. }
  21493. return false;
  21494. });
  21495. });
  21496. Client client("localhost", get_port());
  21497. sse::SSEClient sse(client, "/empty-data-lines");
  21498. std::mutex mutex;
  21499. std::condition_variable cv;
  21500. std::vector<std::string> received;
  21501. sse.on_message([&](const sse::SSEMessage &msg) {
  21502. std::lock_guard<std::mutex> lock(mutex);
  21503. received.push_back(msg.data);
  21504. cv.notify_all();
  21505. });
  21506. sse.set_max_reconnect_attempts(1);
  21507. sse.start_async();
  21508. {
  21509. std::unique_lock<std::mutex> lock(mutex);
  21510. cv.wait_for(lock, std::chrono::seconds(2),
  21511. [&] { return received.size() >= 3; });
  21512. }
  21513. sse.stop();
  21514. ASSERT_GE(received.size(), 3u);
  21515. EXPECT_EQ(received[0], "");
  21516. EXPECT_EQ(received[1], "\nhello");
  21517. EXPECT_EQ(received[2], "");
  21518. }
  21519. // Test: Auto-reconnect after server disconnection
  21520. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21521. std::atomic<int> connection_count{0};
  21522. std::atomic<int> message_count{0};
  21523. // Endpoint that sends one event and closes, forcing reconnect
  21524. server_->Get("/reconnect-test",
  21525. [&connection_count](const Request &, Response &res) {
  21526. connection_count.fetch_add(1);
  21527. res.set_chunked_content_provider(
  21528. "text/event-stream", [](size_t offset, DataSink &sink) {
  21529. if (offset == 0) {
  21530. std::string event = "data: hello\n\n";
  21531. sink.write(event.data(), event.size());
  21532. }
  21533. return false; // Close connection after sending
  21534. });
  21535. });
  21536. Client client("localhost", get_port());
  21537. sse::SSEClient sse(client, "/reconnect-test");
  21538. sse.on_message([&message_count](const sse::SSEMessage &) {
  21539. message_count.fetch_add(1);
  21540. });
  21541. sse.set_reconnect_interval(100);
  21542. sse.set_max_reconnect_attempts(3);
  21543. sse.start_async();
  21544. // Wait long enough for multiple reconnects
  21545. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21546. sse.stop();
  21547. // Should have connected multiple times (initial + reconnects)
  21548. EXPECT_GE(connection_count.load(), 2);
  21549. // Should have received messages from multiple connections
  21550. EXPECT_GE(message_count.load(), 2);
  21551. }
  21552. // Test: A retry field that is not all ASCII digits is ignored
  21553. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21554. std::atomic<int> connection_count{0};
  21555. server_->Get("/bad-retry",
  21556. [&connection_count](const Request &, Response &res) {
  21557. connection_count.fetch_add(1);
  21558. res.set_chunked_content_provider(
  21559. "text/event-stream", [](size_t offset, DataSink &sink) {
  21560. if (offset == 0) {
  21561. std::string event = "retry: -1\ndata: hello\n\n";
  21562. sink.write(event.data(), event.size());
  21563. }
  21564. return false;
  21565. });
  21566. });
  21567. Client client("localhost", get_port());
  21568. sse::SSEClient sse(client, "/bad-retry");
  21569. sse.set_reconnect_interval(10000);
  21570. sse.start_async();
  21571. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21572. sse.stop();
  21573. EXPECT_EQ(connection_count.load(), 1);
  21574. }
  21575. // Test: A retry field of all ASCII digits sets the reconnection time
  21576. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21577. std::mutex mutex;
  21578. std::condition_variable cv;
  21579. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21580. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21581. {
  21582. std::lock_guard<std::mutex> lock(mutex);
  21583. connected_at.push_back(std::chrono::steady_clock::now());
  21584. cv.notify_all();
  21585. }
  21586. res.set_chunked_content_provider(
  21587. "text/event-stream", [](size_t offset, DataSink &sink) {
  21588. if (offset == 0) {
  21589. std::string event = "retry: 0\ndata: hello\n\n";
  21590. sink.write(event.data(), event.size());
  21591. }
  21592. return false;
  21593. });
  21594. });
  21595. Client client("localhost", get_port());
  21596. sse::SSEClient sse(client, "/zero-retry");
  21597. sse.set_reconnect_interval(10000);
  21598. sse.start_async();
  21599. {
  21600. std::unique_lock<std::mutex> lock(mutex);
  21601. cv.wait_for(lock, std::chrono::seconds(5),
  21602. [&] { return connected_at.size() >= 2; });
  21603. }
  21604. sse.stop();
  21605. // The server-supplied interval is applied, but never below 100ms, so
  21606. // "retry: 0" does not cause a busy reconnect loop
  21607. std::lock_guard<std::mutex> lock(mutex);
  21608. ASSERT_GE(connected_at.size(), 2u);
  21609. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21610. connected_at[1] - connected_at[0])
  21611. .count();
  21612. EXPECT_GE(interval_ms, 100);
  21613. }
  21614. // Test: Last-Event-ID sent on reconnect
  21615. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21616. std::atomic<int> connection_count{0};
  21617. std::vector<std::string> received_last_event_ids;
  21618. std::mutex id_mutex;
  21619. // Endpoint that checks Last-Event-ID header and sends event with ID
  21620. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21621. int conn = connection_count.fetch_add(1);
  21622. // Capture the Last-Event-ID header from each connection
  21623. {
  21624. std::lock_guard<std::mutex> lock(id_mutex);
  21625. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21626. }
  21627. res.set_chunked_content_provider(
  21628. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21629. if (offset == 0) {
  21630. std::string event =
  21631. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21632. sink.write(event.data(), event.size());
  21633. }
  21634. return false;
  21635. });
  21636. });
  21637. Client client("localhost", get_port());
  21638. sse::SSEClient sse(client, "/reconnect-with-id");
  21639. sse.set_reconnect_interval(100);
  21640. sse.set_max_reconnect_attempts(3);
  21641. sse.start_async();
  21642. // Wait for at least 2 connections
  21643. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21644. sse.stop();
  21645. // Verify behavior
  21646. std::lock_guard<std::mutex> lock(id_mutex);
  21647. EXPECT_GE(received_last_event_ids.size(), 2u);
  21648. // First connection should have no Last-Event-ID
  21649. if (!received_last_event_ids.empty()) {
  21650. EXPECT_EQ(received_last_event_ids[0], "");
  21651. }
  21652. // Second connection should have Last-Event-ID from first connection
  21653. if (received_last_event_ids.size() >= 2) {
  21654. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21655. }
  21656. }
  21657. // Test: set_headers updates headers used on reconnect
  21658. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21659. std::vector<std::string> received_tokens;
  21660. std::mutex token_mutex;
  21661. // Endpoint that captures Authorization header
  21662. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21663. {
  21664. std::lock_guard<std::mutex> lock(token_mutex);
  21665. received_tokens.push_back(req.get_header_value("Authorization"));
  21666. }
  21667. res.set_chunked_content_provider(
  21668. "text/event-stream", [](size_t offset, DataSink &sink) {
  21669. if (offset == 0) {
  21670. std::string event = "data: hello\n\n";
  21671. sink.write(event.data(), event.size());
  21672. }
  21673. return false; // Close connection to trigger reconnect
  21674. });
  21675. });
  21676. Client client("localhost", get_port());
  21677. Headers headers = {{"Authorization", "Bearer old-token"}};
  21678. sse::SSEClient sse(client, "/auth-check", headers);
  21679. // Update headers on each successful connection
  21680. sse.on_open(
  21681. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21682. sse.set_reconnect_interval(100);
  21683. sse.set_max_reconnect_attempts(3);
  21684. sse.start_async();
  21685. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21686. sse.stop();
  21687. std::lock_guard<std::mutex> lock(token_mutex);
  21688. ASSERT_GE(received_tokens.size(), 2u);
  21689. // First connection uses original header
  21690. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21691. // Second connection uses updated header from set_headers
  21692. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21693. }
  21694. // Test: 401 allows reconnection (so on_error can refresh headers)
  21695. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21696. std::atomic<int> connection_count{0};
  21697. // Endpoint: returns 401 on first attempt, 200 on second
  21698. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21699. int conn = connection_count.fetch_add(1);
  21700. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21701. res.status = StatusCode::Unauthorized_401;
  21702. res.set_content("Unauthorized", "text/plain");
  21703. return;
  21704. }
  21705. res.set_chunked_content_provider(
  21706. "text/event-stream", [](size_t offset, DataSink &sink) {
  21707. if (offset == 0) {
  21708. std::string event = "data: authenticated\n\n";
  21709. sink.write(event.data(), event.size());
  21710. }
  21711. return false;
  21712. });
  21713. });
  21714. Client client("localhost", get_port());
  21715. Headers headers = {{"Authorization", "Bearer expired"}};
  21716. sse::SSEClient sse(client, "/auth-retry", headers);
  21717. std::atomic<bool> message_received{false};
  21718. // Refresh token on error
  21719. sse.on_error(
  21720. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21721. sse.on_message([&](const sse::SSEMessage &msg) {
  21722. if (msg.data == "authenticated") { message_received.store(true); }
  21723. });
  21724. sse.set_reconnect_interval(100);
  21725. sse.set_max_reconnect_attempts(3);
  21726. sse.start_async();
  21727. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21728. sse.stop();
  21729. // Should have reconnected after 401 and succeeded with new token
  21730. EXPECT_GE(connection_count.load(), 2);
  21731. EXPECT_TRUE(message_received.load());
  21732. }
  21733. TEST(Issue2318Test, EmptyHostString) {
  21734. {
  21735. httplib::Client cli_empty("", PORT);
  21736. auto res = cli_empty.Get("/");
  21737. ASSERT_FALSE(res);
  21738. EXPECT_EQ(httplib::Error::Connection, res.error());
  21739. }
  21740. {
  21741. httplib::Client cli(" ", PORT);
  21742. auto res = cli.Get("/");
  21743. ASSERT_FALSE(res);
  21744. EXPECT_EQ(httplib::Error::Connection, res.error());
  21745. }
  21746. }
  21747. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21748. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21749. Server svr;
  21750. // Set a small payload limit (1KB)
  21751. svr.set_payload_max_length(1024);
  21752. svr.Post("/test", [&](const Request &req, Response &res) {
  21753. res.set_content("Body size: " + std::to_string(req.body.size()),
  21754. "text/plain");
  21755. });
  21756. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21757. auto se = detail::scope_exit([&] {
  21758. svr.stop();
  21759. listen_thread.join();
  21760. });
  21761. svr.wait_until_ready();
  21762. // Create data that compresses well but exceeds limit when decompressed
  21763. // 8KB of repeated null bytes compresses to a very small size
  21764. std::string original_data(8 * 1024, '\0');
  21765. // Compress the data using gzip
  21766. std::string compressed_data;
  21767. detail::gzip_compressor compressor;
  21768. compressor.compress(original_data.data(), original_data.size(), true,
  21769. [&](const char *data, size_t size) {
  21770. compressed_data.append(data, size);
  21771. return true;
  21772. });
  21773. // Verify compression worked (compressed should be much smaller)
  21774. ASSERT_LT(compressed_data.size(), original_data.size());
  21775. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21776. // Send compressed data with Content-Encoding: gzip
  21777. Client cli(HOST, PORT);
  21778. Headers headers = {{"Content-Encoding", "gzip"}};
  21779. auto res =
  21780. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21781. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21783. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21784. }
  21785. #endif
  21786. // ============================================================================
  21787. // OpenSSL-Specific Tests
  21788. // ============================================================================
  21789. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21790. X509 *readCertificate(const std::string &strFileName) {
  21791. std::ifstream inStream(strFileName);
  21792. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21793. std::istreambuf_iterator<char>());
  21794. if (strCertPEM.empty()) return (nullptr);
  21795. BIO *pbCert = BIO_new(BIO_s_mem());
  21796. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21797. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21798. BIO_free(pbCert);
  21799. return (pCert);
  21800. }
  21801. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21802. std::ifstream inStream(strFileName);
  21803. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21804. std::istreambuf_iterator<char>());
  21805. if (strPrivateKeyPEM.empty()) return (nullptr);
  21806. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21807. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21808. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21809. BIO_free(pbPrivKey);
  21810. return (pPrivateKey);
  21811. }
  21812. TEST(BindServerTest, UpdateCerts) {
  21813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21814. int port = svr.bind_to_any_port("0.0.0.0");
  21815. ASSERT_TRUE(svr.is_valid());
  21816. ASSERT_TRUE(port > 0);
  21817. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21818. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21819. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21820. ASSERT_TRUE(cert != nullptr);
  21821. ASSERT_TRUE(ca_cert != nullptr);
  21822. ASSERT_TRUE(key != nullptr);
  21823. X509_STORE *cert_store = X509_STORE_new();
  21824. X509_STORE_add_cert(cert_store, ca_cert);
  21825. // svr.update_certs(cert, key, cert_store); // deprecated
  21826. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21827. CLIENT_CA_CERT_FILE);
  21828. ASSERT_TRUE(svr.is_valid());
  21829. svr.stop();
  21830. X509_STORE_free(cert_store);
  21831. X509_free(cert);
  21832. X509_free(ca_cert);
  21833. EVP_PKEY_free(key);
  21834. }
  21835. // Test that update_certs() updates client CA list correctly
  21836. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21837. // Start with file-based constructor
  21838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21839. ASSERT_TRUE(svr.is_valid());
  21840. // Initially no client CA list should be set
  21841. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21842. ASSERT_TRUE(ssl_ctx != nullptr);
  21843. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21844. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21845. EXPECT_EQ(0, count_before);
  21846. // Now update with client CA (PEM string)
  21847. std::string cert_pem, key_pem, ca_pem;
  21848. read_file(SERVER_CERT_FILE, cert_pem);
  21849. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21850. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21851. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21852. ASSERT_TRUE(svr.is_valid());
  21853. // Now client CA list should be set
  21854. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21855. ASSERT_TRUE(ca_list_after != nullptr);
  21856. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21857. }
  21858. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21859. // Test that the file-path SSLServer constructor properly sets the client CA
  21860. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21862. ASSERT_TRUE(svr.is_valid());
  21863. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21864. ASSERT_TRUE(ssl_ctx != nullptr);
  21865. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21866. ASSERT_TRUE(ca_list != nullptr);
  21867. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21868. }
  21869. #endif
  21870. // ============================================================================
  21871. // MbedTLS-Specific Tests
  21872. // ============================================================================
  21873. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21874. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21875. using namespace httplib::tls;
  21876. // Track if callback was invoked
  21877. bool callback_invoked = false;
  21878. // The callback receives void* ctx which is actually MbedTlsContext*
  21879. // We can access the mbedtls_ssl_config via the context
  21880. auto setup_callback = [&callback_invoked](void *ctx) {
  21881. callback_invoked = true;
  21882. // Cast to MbedTlsContext* to access the ssl config
  21883. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21884. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21885. // Use static variables to hold certificate data (simplified for test)
  21886. static mbedtls_x509_crt own_cert;
  21887. static mbedtls_pk_context own_key;
  21888. static mbedtls_x509_crt ca_chain;
  21889. static bool initialized = false;
  21890. if (!initialized) {
  21891. mbedtls_x509_crt_init(&own_cert);
  21892. mbedtls_pk_init(&own_key);
  21893. mbedtls_x509_crt_init(&ca_chain);
  21894. // Load server certificate
  21895. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21896. return false;
  21897. }
  21898. // Load server private key.
  21899. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21900. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21901. #if MBEDTLS_VERSION_MAJOR == 3
  21902. ,
  21903. mbedtls_ctr_drbg_random, nullptr
  21904. #endif
  21905. ) != 0) {
  21906. return false;
  21907. }
  21908. // Load CA chain for client verification
  21909. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21910. return false;
  21911. }
  21912. initialized = true;
  21913. }
  21914. // Configure the SSL config
  21915. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21916. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21917. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21918. // Set minimum TLS version using mbedTLS native API
  21919. #if MBEDTLS_VERSION_MAJOR >= 3
  21920. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21921. #else
  21922. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21923. MBEDTLS_SSL_MINOR_VERSION_3);
  21924. #endif
  21925. return true;
  21926. };
  21927. SSLServer svr(setup_callback);
  21928. ASSERT_TRUE(svr.is_valid());
  21929. ASSERT_TRUE(callback_invoked);
  21930. svr.Get("/test", [&](const Request &req, Response &res) {
  21931. res.set_content("test", "text/plain");
  21932. auto cert = req.peer_cert();
  21933. ASSERT_TRUE(static_cast<bool>(cert));
  21934. auto common_name = cert.subject_cn();
  21935. EXPECT_EQ("Common Name", common_name);
  21936. });
  21937. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21938. auto se = detail::scope_exit([&] {
  21939. svr.stop();
  21940. t.join();
  21941. ASSERT_FALSE(svr.is_running());
  21942. });
  21943. svr.wait_until_ready();
  21944. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21945. cli.enable_server_certificate_verification(false);
  21946. cli.set_connection_timeout(30);
  21947. auto res = cli.Get("/test");
  21948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21949. ASSERT_EQ(StatusCode::OK_200, res->status);
  21950. }
  21951. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21952. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21953. // keep-alive SSL session, which reads through that config in
  21954. // mbedtls_ssl_close_notify.
  21955. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21956. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21957. ASSERT_TRUE(svr.is_valid());
  21958. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21959. res.set_content("test", "text/plain");
  21960. });
  21961. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21962. auto se = detail::scope_exit([&] {
  21963. svr.stop();
  21964. t.join();
  21965. ASSERT_FALSE(svr.is_running());
  21966. });
  21967. svr.wait_until_ready();
  21968. {
  21969. SSLClient cli(HOST, PORT);
  21970. cli.enable_server_certificate_verification(false);
  21971. cli.set_keep_alive(true);
  21972. auto res = cli.Get("/test");
  21973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21974. ASSERT_EQ(StatusCode::OK_200, res->status);
  21975. // cli is destructed here with the keep-alive SSL session still open.
  21976. }
  21977. }
  21978. #endif
  21979. // WebSocket Tests
  21980. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21981. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21982. // defining the meaning of these bits has been negotiated.
  21983. auto make_frame = [](uint8_t first_byte) {
  21984. std::string frame;
  21985. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21986. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21987. frame += "Hello";
  21988. return frame;
  21989. };
  21990. // RSV1 set (0x40)
  21991. {
  21992. detail::BufferStream strm;
  21993. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21994. ws::Opcode opcode;
  21995. std::string payload;
  21996. bool fin;
  21997. EXPECT_EQ(
  21998. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21999. ws::impl::FrameRead::Fail);
  22000. }
  22001. // RSV2 set (0x20)
  22002. {
  22003. detail::BufferStream strm;
  22004. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22005. ws::Opcode opcode;
  22006. std::string payload;
  22007. bool fin;
  22008. EXPECT_EQ(
  22009. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22010. ws::impl::FrameRead::Fail);
  22011. }
  22012. // RSV3 set (0x10)
  22013. {
  22014. detail::BufferStream strm;
  22015. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22016. ws::Opcode opcode;
  22017. std::string payload;
  22018. bool fin;
  22019. EXPECT_EQ(
  22020. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22021. ws::impl::FrameRead::Fail);
  22022. }
  22023. // No RSV bits set - should succeed
  22024. {
  22025. detail::BufferStream strm;
  22026. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22027. ws::Opcode opcode;
  22028. std::string payload;
  22029. bool fin;
  22030. EXPECT_EQ(
  22031. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22032. ws::impl::FrameRead::Ok);
  22033. EXPECT_EQ(ws::Opcode::Text, opcode);
  22034. EXPECT_EQ("Hello", payload);
  22035. EXPECT_TRUE(fin);
  22036. }
  22037. }
  22038. TEST(WebSocketTest, ControlFrameValidation) {
  22039. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22040. // payload length <= 125.
  22041. // Ping with FIN=0 - must be rejected
  22042. {
  22043. detail::BufferStream strm;
  22044. std::string frame;
  22045. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22046. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22047. strm.write(frame.data(), frame.size());
  22048. ws::Opcode opcode;
  22049. std::string payload;
  22050. bool fin;
  22051. EXPECT_EQ(
  22052. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22053. ws::impl::FrameRead::Fail);
  22054. }
  22055. // Close with FIN=0 - must be rejected
  22056. {
  22057. detail::BufferStream strm;
  22058. std::string frame;
  22059. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22060. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22061. strm.write(frame.data(), frame.size());
  22062. ws::Opcode opcode;
  22063. std::string payload;
  22064. bool fin;
  22065. EXPECT_EQ(
  22066. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22067. ws::impl::FrameRead::Fail);
  22068. }
  22069. // Ping with payload_len=126 (extended length) - must be rejected
  22070. {
  22071. detail::BufferStream strm;
  22072. std::string frame;
  22073. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22074. frame += static_cast<char>(126); // payload_len=126 (>125)
  22075. frame += static_cast<char>(0x00); // extended length high byte
  22076. frame += static_cast<char>(126); // extended length low byte
  22077. frame += std::string(126, 'x');
  22078. strm.write(frame.data(), frame.size());
  22079. ws::Opcode opcode;
  22080. std::string payload;
  22081. bool fin;
  22082. EXPECT_EQ(
  22083. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22084. ws::impl::FrameRead::Fail);
  22085. }
  22086. // Ping with FIN=1 and payload_len=125 - should succeed
  22087. {
  22088. detail::BufferStream strm;
  22089. std::string frame;
  22090. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22091. frame += static_cast<char>(125); // payload_len=125
  22092. frame += std::string(125, 'x');
  22093. strm.write(frame.data(), frame.size());
  22094. ws::Opcode opcode;
  22095. std::string payload;
  22096. bool fin;
  22097. EXPECT_EQ(
  22098. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22099. ws::impl::FrameRead::Ok);
  22100. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22101. EXPECT_EQ(125u, payload.size());
  22102. EXPECT_TRUE(fin);
  22103. }
  22104. }
  22105. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22106. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22107. // length MUST be 0.
  22108. // MSB set - must be rejected
  22109. {
  22110. detail::BufferStream strm;
  22111. std::string frame;
  22112. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22113. frame += static_cast<char>(127); // 64-bit extended length
  22114. frame += static_cast<char>(0x80); // MSB set (invalid)
  22115. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22116. strm.write(frame.data(), frame.size());
  22117. ws::Opcode opcode;
  22118. std::string payload;
  22119. bool fin;
  22120. EXPECT_EQ(
  22121. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22122. ws::impl::FrameRead::Fail);
  22123. }
  22124. // MSB clear - should pass length parsing (will be rejected by max_len,
  22125. // but that's a different check; use a small length to verify)
  22126. {
  22127. detail::BufferStream strm;
  22128. std::string frame;
  22129. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22130. frame += static_cast<char>(127); // 64-bit extended length
  22131. frame += std::string(7, '\0'); // high bytes = 0
  22132. frame += static_cast<char>(0x03); // length = 3
  22133. frame += "abc";
  22134. strm.write(frame.data(), frame.size());
  22135. ws::Opcode opcode;
  22136. std::string payload;
  22137. bool fin;
  22138. EXPECT_EQ(
  22139. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22140. ws::impl::FrameRead::Ok);
  22141. EXPECT_EQ(ws::Opcode::Text, opcode);
  22142. EXPECT_EQ("abc", payload);
  22143. }
  22144. }
  22145. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22146. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22147. // Valid UTF-8
  22148. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22149. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22150. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22151. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22152. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22153. // Invalid UTF-8
  22154. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22155. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22156. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22157. EXPECT_FALSE(
  22158. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22159. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22160. }
  22161. TEST(WebSocketTest, ConnectAndDisconnect) {
  22162. Server svr;
  22163. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22164. std::string msg;
  22165. while (ws.read(msg)) {}
  22166. });
  22167. auto port = svr.bind_to_any_port(HOST);
  22168. std::thread t([&]() { svr.listen_after_bind(); });
  22169. svr.wait_until_ready();
  22170. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22171. auto res = client.connect();
  22172. ASSERT_TRUE(res);
  22173. EXPECT_EQ(Error::Success, res.error());
  22174. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22175. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22176. EXPECT_TRUE(client.is_open());
  22177. client.close();
  22178. EXPECT_FALSE(client.is_open());
  22179. svr.stop();
  22180. t.join();
  22181. }
  22182. TEST(WebSocketTest, ValidURL) {
  22183. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22184. EXPECT_TRUE(ws1.is_valid());
  22185. ws::WebSocketClient ws2("ws://example.com/path");
  22186. EXPECT_TRUE(ws2.is_valid());
  22187. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22188. EXPECT_TRUE(ws3.is_valid());
  22189. #ifdef CPPHTTPLIB_SSL_ENABLED
  22190. ws::WebSocketClient wss1("wss://example.com/path");
  22191. EXPECT_TRUE(wss1.is_valid());
  22192. ws::WebSocketClient wss2("wss://example.com:443/path");
  22193. EXPECT_TRUE(wss2.is_valid());
  22194. #endif
  22195. }
  22196. TEST(WebSocketTest, InvalidURL) {
  22197. // No scheme
  22198. ws::WebSocketClient ws1("localhost:8080/path");
  22199. EXPECT_FALSE(ws1.is_valid());
  22200. // No path
  22201. ws::WebSocketClient ws2("ws://localhost:8080");
  22202. EXPECT_FALSE(ws2.is_valid());
  22203. // Empty string
  22204. ws::WebSocketClient ws3("");
  22205. EXPECT_FALSE(ws3.is_valid());
  22206. // Missing host
  22207. ws::WebSocketClient ws4("ws://:8080/path");
  22208. EXPECT_FALSE(ws4.is_valid());
  22209. // Port number overflow — should not crash
  22210. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22211. EXPECT_FALSE(ws5.is_valid());
  22212. // Port out of range
  22213. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22214. EXPECT_FALSE(ws6.is_valid());
  22215. }
  22216. TEST(WebSocketTest, UnsupportedScheme) {
  22217. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22218. ws::WebSocketClient ws1("http://localhost:8080/path");
  22219. EXPECT_FALSE(ws1.is_valid());
  22220. ws::WebSocketClient ws2("https://localhost:8080/path");
  22221. EXPECT_FALSE(ws2.is_valid());
  22222. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22223. EXPECT_FALSE(ws3.is_valid());
  22224. #else
  22225. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22226. std::invalid_argument);
  22227. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22228. std::invalid_argument);
  22229. #endif
  22230. }
  22231. TEST(WebSocketTest, ConnectWhenInvalid) {
  22232. ws::WebSocketClient ws("not a valid url");
  22233. EXPECT_FALSE(ws.is_valid());
  22234. auto res = ws.connect();
  22235. EXPECT_FALSE(res);
  22236. EXPECT_EQ(Error::Connection, res.error());
  22237. EXPECT_EQ(-1, res.status());
  22238. }
  22239. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22240. // Grab a port that is free, then close it again so nothing listens there
  22241. Server svr;
  22242. auto port = svr.bind_to_any_port(HOST);
  22243. svr.stop();
  22244. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22245. auto res = client.connect();
  22246. ASSERT_FALSE(res);
  22247. EXPECT_EQ(Error::Connection, res.error());
  22248. EXPECT_EQ(-1, res.status());
  22249. }
  22250. TEST(WebSocketTest, DefaultPort) {
  22251. ws::WebSocketClient ws1("ws://example.com/path");
  22252. EXPECT_TRUE(ws1.is_valid());
  22253. // ws:// defaults to port 80 (verified by successful parse)
  22254. #ifdef CPPHTTPLIB_SSL_ENABLED
  22255. ws::WebSocketClient ws2("wss://example.com/path");
  22256. EXPECT_TRUE(ws2.is_valid());
  22257. // wss:// defaults to port 443 (verified by successful parse)
  22258. #endif
  22259. }
  22260. TEST(WebSocketTest, IPv6LiteralAddress) {
  22261. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22262. EXPECT_TRUE(ws1.is_valid());
  22263. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22264. EXPECT_TRUE(ws2.is_valid());
  22265. }
  22266. TEST(WebSocketTest, ComplexPath) {
  22267. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22268. EXPECT_TRUE(ws1.is_valid());
  22269. ws::WebSocketClient ws2("ws://localhost:8080/");
  22270. EXPECT_TRUE(ws2.is_valid());
  22271. }
  22272. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22273. Server svr;
  22274. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22275. std::string msg;
  22276. while (ws.read(msg)) {}
  22277. });
  22278. auto port = svr.bind_to_any_port(HOST);
  22279. std::thread t([&]() { svr.listen_after_bind(); });
  22280. svr.wait_until_ready();
  22281. auto another_host = "example.com";
  22282. auto wrong_ip = "192.0.2.1";
  22283. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22284. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22285. ASSERT_TRUE(client.connect());
  22286. EXPECT_TRUE(client.is_open());
  22287. client.close();
  22288. svr.stop();
  22289. t.join();
  22290. }
  22291. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22292. Server svr;
  22293. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22294. std::string msg;
  22295. while (ws.read(msg)) {}
  22296. });
  22297. auto port = svr.bind_to_any_port(HOST);
  22298. std::thread t([&]() { svr.listen_after_bind(); });
  22299. svr.wait_until_ready();
  22300. auto wrong_ip = "192.0.2.1";
  22301. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22302. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22303. client.set_connection_timeout(1);
  22304. client.set_read_timeout(1);
  22305. client.set_write_timeout(1);
  22306. EXPECT_FALSE(client.connect());
  22307. EXPECT_FALSE(client.is_open());
  22308. svr.stop();
  22309. t.join();
  22310. }
  22311. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22312. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22313. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22314. // (RFC 6761) is only a map key and the Host header value.
  22315. auto host = "target.invalid";
  22316. Server svr;
  22317. std::string received_host;
  22318. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22319. received_host = req.get_header_value("Host");
  22320. std::string msg;
  22321. while (ws.read(msg)) {}
  22322. });
  22323. auto port = svr.bind_to_any_port(HOST);
  22324. std::thread t([&]() { svr.listen_after_bind(); });
  22325. // ASSERT_* below returns from the test body, which would leave t joinable
  22326. // and make ~thread call std::terminate.
  22327. auto se = detail::scope_exit([&] {
  22328. svr.stop();
  22329. if (t.joinable()) { t.join(); }
  22330. });
  22331. svr.wait_until_ready();
  22332. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22333. std::to_string(port) + "/ws");
  22334. client.set_hostname_addr_map({{host, HOST}});
  22335. ASSERT_TRUE(client.connect());
  22336. EXPECT_TRUE(client.is_open());
  22337. client.close();
  22338. svr.stop();
  22339. t.join();
  22340. // The mapping only redirects the connection; the identity stays host_.
  22341. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22342. }
  22343. class WebSocketIntegrationTest : public ::testing::Test {
  22344. protected:
  22345. void SetUp() override {
  22346. server_ = httplib::detail::make_unique<Server>();
  22347. setup_server();
  22348. start_server();
  22349. }
  22350. void TearDown() override {
  22351. server_->stop();
  22352. if (server_thread_.joinable()) { server_thread_.join(); }
  22353. }
  22354. void setup_server() {
  22355. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22356. std::string msg;
  22357. ws::ReadResult ret;
  22358. while ((ret = ws.read(msg))) {
  22359. if (ret == ws::Binary) {
  22360. ws.send(msg.data(), msg.size());
  22361. } else {
  22362. ws.send(msg);
  22363. }
  22364. }
  22365. });
  22366. server_->WebSocket("/ws-echo-string",
  22367. [](const Request &, ws::WebSocket &ws) {
  22368. std::string msg;
  22369. while (ws.read(msg)) {
  22370. ws.send("echo: " + msg);
  22371. }
  22372. });
  22373. server_->WebSocket(
  22374. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22375. // Echo back request metadata
  22376. ws.send("path:" + req.path);
  22377. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22378. std::string msg;
  22379. while (ws.read(msg)) {}
  22380. });
  22381. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22382. std::string msg;
  22383. ws.read(msg); // wait for a message
  22384. ws.close();
  22385. });
  22386. server_->WebSocket("/ws-close-status",
  22387. [](const Request &, ws::WebSocket &ws) {
  22388. std::string msg;
  22389. ws.read(msg); // wait for a message
  22390. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22391. });
  22392. server_->WebSocket(
  22393. "/ws-subprotocol",
  22394. [](const Request &, ws::WebSocket &ws) {
  22395. std::string msg;
  22396. while (ws.read(msg)) {
  22397. ws.send(msg);
  22398. }
  22399. },
  22400. [](const std::vector<std::string> &protocols) -> std::string {
  22401. for (const auto &p : protocols) {
  22402. if (p == "graphql-ws") { return p; }
  22403. }
  22404. return "";
  22405. });
  22406. server_->WebSocket(
  22407. "/ws-subprotocol-unoffered",
  22408. [](const Request &, ws::WebSocket &ws) {
  22409. std::string msg;
  22410. while (ws.read(msg)) {
  22411. ws.send(msg);
  22412. }
  22413. },
  22414. [](const std::vector<std::string> &) -> std::string {
  22415. return "admin";
  22416. });
  22417. }
  22418. void start_server() {
  22419. port_ = server_->bind_to_any_port(HOST);
  22420. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22421. server_->wait_until_ready();
  22422. }
  22423. std::unique_ptr<Server> server_;
  22424. std::thread server_thread_;
  22425. int port_ = 0;
  22426. };
  22427. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22428. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22429. "/ws-echo");
  22430. ASSERT_TRUE(client.connect());
  22431. ASSERT_TRUE(client.is_open());
  22432. ASSERT_TRUE(client.send("Hello WebSocket"));
  22433. std::string msg;
  22434. EXPECT_EQ(ws::Text, client.read(msg));
  22435. EXPECT_EQ("Hello WebSocket", msg);
  22436. client.close();
  22437. }
  22438. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22439. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22440. "/ws-echo");
  22441. ASSERT_TRUE(client.connect());
  22442. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22443. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22444. std::string msg;
  22445. EXPECT_EQ(ws::Binary, client.read(msg));
  22446. EXPECT_EQ(binary_data, msg);
  22447. client.close();
  22448. }
  22449. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22450. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22451. "/ws-echo");
  22452. ASSERT_TRUE(client.connect());
  22453. for (int i = 0; i < 10; i++) {
  22454. auto text = "message " + std::to_string(i);
  22455. ASSERT_TRUE(client.send(text));
  22456. std::string msg;
  22457. ASSERT_TRUE(client.read(msg));
  22458. EXPECT_EQ(text, msg);
  22459. }
  22460. client.close();
  22461. }
  22462. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22463. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22464. "/ws-close");
  22465. ASSERT_TRUE(client.connect());
  22466. // Send a message to trigger the server to close
  22467. ASSERT_TRUE(client.send("trigger close"));
  22468. // The server will close, so read should return false
  22469. std::string msg;
  22470. EXPECT_FALSE(client.read(msg));
  22471. EXPECT_FALSE(client.is_open());
  22472. }
  22473. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22474. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22475. "/ws-echo");
  22476. ASSERT_TRUE(client.connect());
  22477. // 128KB message
  22478. std::string large_data(128 * 1024, 'X');
  22479. ASSERT_TRUE(client.send(large_data));
  22480. std::string msg;
  22481. ASSERT_TRUE(client.read(msg));
  22482. EXPECT_EQ(large_data, msg);
  22483. client.close();
  22484. }
  22485. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22486. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22487. "/ws-echo");
  22488. ASSERT_TRUE(client.connect());
  22489. const int num_threads = 4;
  22490. std::vector<std::thread> threads;
  22491. std::atomic<int> send_count{0};
  22492. for (int t = 0; t < num_threads; t++) {
  22493. threads.emplace_back([&client, &send_count, t]() {
  22494. for (int i = 0; i < 5; i++) {
  22495. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22496. if (client.send(text)) { send_count++; }
  22497. }
  22498. });
  22499. }
  22500. for (auto &th : threads) {
  22501. th.join();
  22502. }
  22503. int received = 0;
  22504. std::string msg;
  22505. while (received < send_count.load()) {
  22506. if (!client.read(msg)) { break; }
  22507. received++;
  22508. }
  22509. EXPECT_EQ(send_count.load(), received);
  22510. client.close();
  22511. }
  22512. TEST_F(WebSocketIntegrationTest, ReadString) {
  22513. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22514. "/ws-echo-string");
  22515. ASSERT_TRUE(client.connect());
  22516. ASSERT_TRUE(client.send("hello"));
  22517. std::string msg;
  22518. ASSERT_TRUE(client.read(msg));
  22519. EXPECT_EQ("echo: hello", msg);
  22520. ASSERT_TRUE(client.send("world"));
  22521. ASSERT_TRUE(client.read(msg));
  22522. EXPECT_EQ("echo: world", msg);
  22523. client.close();
  22524. }
  22525. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22526. Headers headers = {{"X-Test-Header", "test-value"}};
  22527. ws::WebSocketClient client(
  22528. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22529. ASSERT_TRUE(client.connect());
  22530. std::string msg;
  22531. ASSERT_TRUE(client.read(msg));
  22532. EXPECT_EQ("path:/ws-request-info", msg);
  22533. ASSERT_TRUE(client.read(msg));
  22534. EXPECT_EQ("header:test-value", msg);
  22535. client.close();
  22536. }
  22537. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22538. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22539. "/ws-echo");
  22540. client.set_read_timeout(1, 0); // 1 second
  22541. ASSERT_TRUE(client.connect());
  22542. // Don't send anything — server echo handler waits for a message, so read()
  22543. // should time out. The connection survives it: nothing was consumed.
  22544. std::string msg;
  22545. EXPECT_EQ(client.read(msg), ws::Timeout);
  22546. EXPECT_TRUE(client.is_open());
  22547. // And it is still usable afterwards.
  22548. EXPECT_TRUE(client.send("after timeout"));
  22549. EXPECT_EQ(client.read(msg), ws::Text);
  22550. EXPECT_EQ(msg, "after timeout");
  22551. }
  22552. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22553. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22554. "/ws-echo");
  22555. client.set_read_timeout(1, 0);
  22556. ASSERT_TRUE(client.connect());
  22557. ASSERT_TRUE(client.send("first"));
  22558. std::string msg;
  22559. ASSERT_EQ(client.read(msg), ws::Text);
  22560. ASSERT_EQ(msg, "first");
  22561. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22562. // not be used with a read timeout: it would reprocess the previous message.
  22563. EXPECT_EQ(client.read(msg), ws::Timeout);
  22564. EXPECT_EQ(msg, "first");
  22565. }
  22566. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22567. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22568. "/ws-echo");
  22569. ASSERT_TRUE(client.connect());
  22570. // Setting it once the connection is open reaches the live stream, not just
  22571. // the seed for the next connect().
  22572. client.set_read_timeout(1, 0);
  22573. std::string msg;
  22574. EXPECT_EQ(client.read(msg), ws::Timeout);
  22575. EXPECT_TRUE(client.is_open());
  22576. }
  22577. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22578. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22579. "/ws-echo");
  22580. client.set_read_timeout(5, 0);
  22581. ASSERT_TRUE(client.connect());
  22582. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22583. // The server should reject it and close the connection.
  22584. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22585. client.send(oversized);
  22586. // The server's read() should have failed due to payload limit,
  22587. // so our read() should return false (connection closed).
  22588. std::string msg;
  22589. EXPECT_FALSE(client.read(msg));
  22590. }
  22591. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22592. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22593. "/ws-echo");
  22594. client.set_read_timeout(10, 0);
  22595. ASSERT_TRUE(client.connect());
  22596. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22597. // This should succeed.
  22598. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22599. ASSERT_TRUE(client.send(at_limit));
  22600. std::string msg;
  22601. ASSERT_TRUE(client.read(msg));
  22602. EXPECT_EQ(at_limit.size(), msg.size());
  22603. client.close();
  22604. }
  22605. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22606. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22607. "/nonexistent");
  22608. auto res = client.connect();
  22609. EXPECT_FALSE(res);
  22610. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22611. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22612. EXPECT_FALSE(client.is_open());
  22613. }
  22614. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22615. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22616. "/ws-echo");
  22617. ASSERT_TRUE(client.connect());
  22618. ASSERT_TRUE(client.send(""));
  22619. std::string msg;
  22620. EXPECT_EQ(ws::Text, client.read(msg));
  22621. EXPECT_EQ("", msg);
  22622. client.close();
  22623. }
  22624. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22625. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22626. "/ws-echo");
  22627. // First connection
  22628. ASSERT_TRUE(client.connect());
  22629. ASSERT_TRUE(client.send("first"));
  22630. std::string msg;
  22631. ASSERT_TRUE(client.read(msg));
  22632. EXPECT_EQ("first", msg);
  22633. client.close();
  22634. EXPECT_FALSE(client.is_open());
  22635. // Reconnect using the same client object
  22636. ASSERT_TRUE(client.connect());
  22637. ASSERT_TRUE(client.is_open());
  22638. ASSERT_TRUE(client.send("second"));
  22639. ASSERT_TRUE(client.read(msg));
  22640. EXPECT_EQ("second", msg);
  22641. client.close();
  22642. }
  22643. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22644. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22645. "/ws-close-status");
  22646. ASSERT_TRUE(client.connect());
  22647. // Trigger the server to close with GoingAway status
  22648. ASSERT_TRUE(client.send("trigger"));
  22649. // read() should return false after receiving the close frame
  22650. std::string msg;
  22651. EXPECT_FALSE(client.read(msg));
  22652. EXPECT_FALSE(client.is_open());
  22653. }
  22654. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22655. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22656. "/ws-echo");
  22657. ASSERT_TRUE(client.connect());
  22658. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22659. EXPECT_FALSE(client.is_open());
  22660. }
  22661. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22662. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22663. ws::WebSocketClient client(
  22664. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22665. ASSERT_TRUE(client.connect());
  22666. // Server should have selected graphql-ws
  22667. EXPECT_EQ("graphql-ws", client.subprotocol());
  22668. client.close();
  22669. }
  22670. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22671. Headers headers;
  22672. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22673. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22674. ws::WebSocketClient client(
  22675. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22676. ASSERT_TRUE(client.connect());
  22677. // The offer on the second field line counts too, so graphql-ws is selected
  22678. EXPECT_EQ("graphql-ws", client.subprotocol());
  22679. client.close();
  22680. }
  22681. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22682. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22683. ws::WebSocketClient client(
  22684. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22685. ASSERT_TRUE(client.connect());
  22686. // Server should not have selected any subprotocol
  22687. EXPECT_TRUE(client.subprotocol().empty());
  22688. client.close();
  22689. }
  22690. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22691. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22692. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22693. "/ws-subprotocol-unoffered",
  22694. headers);
  22695. ASSERT_TRUE(client.connect());
  22696. EXPECT_TRUE(client.subprotocol().empty());
  22697. client.close();
  22698. }
  22699. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22700. // Connect without requesting any subprotocol
  22701. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22702. "/ws-subprotocol");
  22703. ASSERT_TRUE(client.connect());
  22704. EXPECT_TRUE(client.subprotocol().empty());
  22705. client.close();
  22706. }
  22707. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22708. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22709. "/ws-echo");
  22710. client.set_tcp_nodelay(true);
  22711. client.set_connection_timeout(3, 0);
  22712. bool socket_options_called = false;
  22713. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22714. ASSERT_TRUE(client.connect());
  22715. ASSERT_TRUE(client.is_open());
  22716. EXPECT_TRUE(socket_options_called);
  22717. ASSERT_TRUE(client.send("hello"));
  22718. std::string msg;
  22719. auto result = client.read(msg);
  22720. EXPECT_EQ(result, ws::ReadResult::Text);
  22721. EXPECT_EQ(msg, "hello");
  22722. client.close();
  22723. }
  22724. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22725. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22726. "/ws-echo");
  22727. client.set_connection_timeout(std::chrono::seconds(3));
  22728. client.set_write_timeout(std::chrono::seconds(3));
  22729. // A sub-second remainder exercises the seconds/microseconds split.
  22730. client.set_read_timeout(std::chrono::milliseconds(1500));
  22731. ASSERT_TRUE(client.connect());
  22732. auto start = std::chrono::steady_clock::now();
  22733. std::string msg;
  22734. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22735. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22736. std::chrono::steady_clock::now() - start)
  22737. .count();
  22738. // Above 1s so that dropping the microseconds half of the split fails here.
  22739. // Ignoring the setter altogether would not reach this line at all: a client
  22740. // waits forever by default.
  22741. EXPECT_GE(elapsed, 1400);
  22742. EXPECT_LT(elapsed, 30000);
  22743. }
  22744. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22745. Server svr;
  22746. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22747. if (!req.has_header("Authorization")) {
  22748. res.status = StatusCode::Unauthorized_401;
  22749. res.set_content("Unauthorized", "text/plain");
  22750. return Server::HandlerResponse::Handled;
  22751. }
  22752. return Server::HandlerResponse::Unhandled;
  22753. });
  22754. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22755. std::string msg;
  22756. while (ws.read(msg)) {
  22757. ws.send(msg);
  22758. }
  22759. });
  22760. auto port = svr.bind_to_any_port("localhost");
  22761. std::thread t([&]() { svr.listen_after_bind(); });
  22762. svr.wait_until_ready();
  22763. // Without Authorization header - should be rejected before upgrade
  22764. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22765. EXPECT_FALSE(client1.connect());
  22766. // The rejection is framed like any other HTTP response
  22767. {
  22768. Client cli("localhost", port);
  22769. Headers headers = {{"Upgrade", "websocket"},
  22770. {"Connection", "Upgrade"},
  22771. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22772. {"Sec-WebSocket-Version", "13"}};
  22773. auto res = cli.Get("/ws", headers);
  22774. ASSERT_TRUE(res);
  22775. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22776. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22777. EXPECT_EQ("Unauthorized", res->body);
  22778. }
  22779. // With Authorization header - should succeed
  22780. Headers headers = {{"Authorization", "Bearer token123"}};
  22781. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22782. headers);
  22783. ASSERT_TRUE(client2.connect());
  22784. ASSERT_TRUE(client2.send("hello"));
  22785. std::string msg;
  22786. ASSERT_TRUE(client2.read(msg));
  22787. EXPECT_EQ("hello", msg);
  22788. client2.close();
  22789. svr.stop();
  22790. t.join();
  22791. }
  22792. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22793. Server svr;
  22794. std::atomic<int> pre_request_calls{0};
  22795. std::atomic<bool> route_matched{false};
  22796. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22797. pre_request_calls++;
  22798. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22799. if (req.get_header_value("Authorization") != "Bearer token123") {
  22800. res.status = StatusCode::Unauthorized_401;
  22801. res.set_content("Unauthorized", "text/plain");
  22802. return Server::HandlerResponse::Handled;
  22803. }
  22804. return Server::HandlerResponse::Unhandled;
  22805. });
  22806. std::atomic<bool> handler_called{false};
  22807. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22808. handler_called = true;
  22809. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22810. });
  22811. auto port = svr.bind_to_any_port("localhost");
  22812. std::thread t([&]() { svr.listen_after_bind(); });
  22813. svr.wait_until_ready();
  22814. // Without Authorization header - should be rejected before upgrade
  22815. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22816. "/ws/1");
  22817. EXPECT_FALSE(client1.connect());
  22818. EXPECT_FALSE(handler_called);
  22819. EXPECT_EQ(1, pre_request_calls);
  22820. EXPECT_TRUE(route_matched);
  22821. // The rejection is an ordinary HTTP response, not a protocol switch
  22822. {
  22823. Client cli("localhost", port);
  22824. Headers headers = {{"Upgrade", "websocket"},
  22825. {"Connection", "Upgrade"},
  22826. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22827. {"Sec-WebSocket-Version", "13"}};
  22828. auto res = cli.Get("/ws/1", headers);
  22829. ASSERT_TRUE(res);
  22830. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22831. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22832. EXPECT_EQ("Unauthorized", res->body);
  22833. }
  22834. EXPECT_FALSE(handler_called);
  22835. // With Authorization header - should succeed
  22836. Headers headers = {{"Authorization", "Bearer token123"}};
  22837. ws::WebSocketClient client2(
  22838. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22839. ASSERT_TRUE(client2.connect());
  22840. std::string msg;
  22841. ASSERT_TRUE(client2.read(msg));
  22842. EXPECT_EQ("/ws/:id 2", msg);
  22843. EXPECT_TRUE(handler_called);
  22844. client2.close();
  22845. svr.stop();
  22846. t.join();
  22847. }
  22848. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22849. Server svr;
  22850. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22851. // A read timeout is how a handler gets control back. Without it, a handler
  22852. // parked in read() can never write on the connection it is reading.
  22853. ws.set_read_timeout(std::chrono::milliseconds(100));
  22854. std::string msg;
  22855. while (ws.is_open()) {
  22856. auto r = ws.read(msg);
  22857. if (r == httplib::ws::Timeout) {
  22858. ws.send("tick");
  22859. continue;
  22860. }
  22861. if (r == httplib::ws::Fail) { break; }
  22862. ws.send(msg);
  22863. }
  22864. });
  22865. auto port = svr.bind_to_any_port("localhost");
  22866. std::thread t([&]() { svr.listen_after_bind(); });
  22867. svr.wait_until_ready();
  22868. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22869. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22870. ASSERT_TRUE(client.connect());
  22871. // The client sends nothing, so anything it receives came out of the
  22872. // handler's timeout path.
  22873. std::string msg;
  22874. ASSERT_EQ(client.read(msg), ws::Text);
  22875. EXPECT_EQ("tick", msg);
  22876. client.close();
  22877. svr.stop();
  22878. t.join();
  22879. }
  22880. // Stream::read may return fewer bytes than asked for. This is that contract at
  22881. // its worst -- one byte per call -- which is what a frame header straddling a
  22882. // read buffer's boundary looks like to the frame parser.
  22883. class WsByteAtATimeStream : public Stream {
  22884. public:
  22885. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22886. bool is_readable() const override { return true; }
  22887. bool wait_readable() const override { return true; }
  22888. bool wait_writable() const override { return true; }
  22889. ssize_t read(char *ptr, size_t size) override {
  22890. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22891. *ptr = data_[pos_++];
  22892. return 1;
  22893. }
  22894. ssize_t write(const char *, size_t size) override {
  22895. return static_cast<ssize_t>(size);
  22896. }
  22897. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22898. ip = "127.0.0.1";
  22899. port = 0;
  22900. }
  22901. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22902. ip = "127.0.0.1";
  22903. port = 0;
  22904. }
  22905. socket_t socket() const override { return INVALID_SOCKET; }
  22906. time_t duration() const override { return 0; }
  22907. private:
  22908. std::string data_;
  22909. size_t pos_ = 0;
  22910. };
  22911. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22912. // The payload uses the 16-bit extended length, so the header, the length
  22913. // and the mask key are all multi-byte fields here. Each used to be read
  22914. // with a single read() call, which fails as soon as one is split. The
  22915. // payload is also a little over one read chunk, so it is read in two.
  22916. std::string body;
  22917. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22918. body += static_cast<char>(i % 251);
  22919. }
  22920. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22921. std::string frame;
  22922. frame += static_cast<char>(0x81); // FIN + Text
  22923. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22924. frame += static_cast<char>(body.size() >> 8);
  22925. frame += static_cast<char>(body.size() & 0xff);
  22926. for (size_t i = 0; i < 4; i++) {
  22927. frame += static_cast<char>(mask[i]);
  22928. }
  22929. for (size_t i = 0; i < body.size(); i++) {
  22930. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22931. }
  22932. WsByteAtATimeStream strm(frame);
  22933. ws::Opcode opcode;
  22934. std::string payload;
  22935. bool fin = false;
  22936. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22937. /*expect_masked=*/true, body.size()),
  22938. ws::impl::FrameRead::Ok);
  22939. EXPECT_TRUE(fin);
  22940. EXPECT_EQ(opcode, ws::Opcode::Text);
  22941. EXPECT_EQ(payload, body);
  22942. }
  22943. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22944. std::string body(2000, 'x');
  22945. std::string frame;
  22946. frame += static_cast<char>(0x82); // FIN + Binary
  22947. frame += static_cast<char>(126); // 16-bit length follows
  22948. frame += static_cast<char>(body.size() >> 8);
  22949. frame += static_cast<char>(body.size() & 0xff);
  22950. frame += body;
  22951. detail::BufferStream strm;
  22952. strm.write(frame.data(), frame.size());
  22953. ws::Opcode opcode;
  22954. std::string payload;
  22955. bool fin;
  22956. EXPECT_EQ(
  22957. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22958. ws::impl::FrameRead::Ok);
  22959. EXPECT_EQ(body, payload);
  22960. }
  22961. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22962. // The header announces the largest payload allowed, and only 3 bytes of it
  22963. // ever arrive.
  22964. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22965. std::string frame;
  22966. frame += static_cast<char>(0x82); // FIN + Binary
  22967. frame += static_cast<char>(127); // 64-bit length follows
  22968. for (int shift = 56; shift >= 0; shift -= 8) {
  22969. frame += static_cast<char>((len >> shift) & 0xff);
  22970. }
  22971. frame += "abc";
  22972. detail::BufferStream strm;
  22973. strm.write(frame.data(), frame.size());
  22974. ws::Opcode opcode;
  22975. std::string payload;
  22976. bool fin;
  22977. EXPECT_EQ(
  22978. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22979. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22980. ws::impl::FrameRead::Fail);
  22981. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22982. }
  22983. TEST(WebSocketTest, QueryStringInHandshake) {
  22984. Server svr;
  22985. std::mutex mtx;
  22986. std::string received_target;
  22987. std::string received_token;
  22988. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22989. {
  22990. std::lock_guard<std::mutex> lock(mtx);
  22991. received_target = req.target;
  22992. if (req.has_param("token")) {
  22993. received_token = req.get_param_value("token");
  22994. }
  22995. }
  22996. std::string msg;
  22997. while (ws.read(msg)) {
  22998. ws.send(msg);
  22999. }
  23000. });
  23001. auto port = svr.bind_to_any_port("localhost");
  23002. std::thread t([&]() { svr.listen_after_bind(); });
  23003. svr.wait_until_ready();
  23004. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23005. "/ws?token=ABC&session=123");
  23006. ASSERT_TRUE(client.connect());
  23007. // Round-trip ensures the handler has run and captured the request.
  23008. ASSERT_TRUE(client.send("hello"));
  23009. std::string msg;
  23010. ASSERT_TRUE(client.read(msg));
  23011. EXPECT_EQ("hello", msg);
  23012. client.close();
  23013. {
  23014. std::lock_guard<std::mutex> lock(mtx);
  23015. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23016. EXPECT_EQ("ABC", received_token);
  23017. }
  23018. svr.stop();
  23019. t.join();
  23020. }
  23021. // Run a handshake against a throwaway server and hand the request the server
  23022. // received back to the caller, so tests can assert on the headers the client
  23023. // actually put on the wire.
  23024. static void capture_websocket_handshake_request(
  23025. const Headers &client_headers,
  23026. std::function<void(const Request &, int port)> verify) {
  23027. Server svr;
  23028. std::mutex mtx;
  23029. Request received;
  23030. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23031. {
  23032. std::lock_guard<std::mutex> lock(mtx);
  23033. received = req;
  23034. }
  23035. std::string msg;
  23036. while (ws.read(msg)) {
  23037. ws.send(msg);
  23038. }
  23039. });
  23040. auto port = svr.bind_to_any_port("localhost");
  23041. std::thread t([&]() { svr.listen_after_bind(); });
  23042. auto se = detail::scope_exit([&] {
  23043. svr.stop();
  23044. t.join();
  23045. });
  23046. svr.wait_until_ready();
  23047. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23048. client_headers);
  23049. ASSERT_TRUE(client.connect());
  23050. ASSERT_TRUE(client.send("hello"));
  23051. std::string msg;
  23052. ASSERT_TRUE(client.read(msg));
  23053. client.close();
  23054. {
  23055. std::lock_guard<std::mutex> lock(mtx);
  23056. verify(received, port);
  23057. }
  23058. }
  23059. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23060. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23061. // Non-default port must be present in the Host header. Default ports
  23062. // (80/443) are omitted; that logic is covered by
  23063. // MakeHostAndPortStringTest.
  23064. EXPECT_EQ("localhost:" + std::to_string(port),
  23065. req.get_header_value("Host"));
  23066. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23067. req.get_header_value("User-Agent"));
  23068. EXPECT_FALSE(req.has_header("Accept"));
  23069. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23070. EXPECT_FALSE(req.has_header("Content-Length"));
  23071. });
  23072. }
  23073. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23074. capture_websocket_handshake_request(
  23075. {{"Host", "example.com"},
  23076. {"User-Agent", "custom-agent"},
  23077. {"X-Custom", "value"}},
  23078. [](const Request &req, int) {
  23079. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23080. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23081. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23082. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23083. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23084. });
  23085. }
  23086. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23087. capture_websocket_handshake_request(
  23088. {{"Upgrade", "bogus"},
  23089. {"Connection", "close"},
  23090. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23091. {"Sec-WebSocket-Version", "8"}},
  23092. [](const Request &req, int) {
  23093. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23094. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23095. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23096. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23097. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23098. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23099. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23100. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23101. req.get_header_value("Sec-WebSocket-Key"));
  23102. });
  23103. }
  23104. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23105. // A header the client refuses to send must abort the handshake before any
  23106. // part of it reaches the wire; a lone request line would otherwise sit in
  23107. // the peer's buffer as a truncated request.
  23108. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23109. ASSERT_NE(INVALID_SOCKET, srv);
  23110. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23111. sockaddr_in addr{};
  23112. addr.sin_family = AF_INET;
  23113. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23114. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23115. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23116. ASSERT_EQ(0, ::listen(srv, 1));
  23117. sockaddr_in bound{};
  23118. socklen_t bound_len = sizeof(bound);
  23119. ASSERT_EQ(
  23120. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23121. auto port = ntohs(bound.sin_port);
  23122. ssize_t received = -1;
  23123. std::thread t([&] {
  23124. // Bound every blocking call so a regression fails the test with a bad
  23125. // value instead of hanging the suite.
  23126. fd_set rfds;
  23127. FD_ZERO(&rfds);
  23128. FD_SET(srv, &rfds);
  23129. timeval tv{5, 0};
  23130. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23131. 0) {
  23132. return;
  23133. }
  23134. sockaddr_in cli_addr{};
  23135. socklen_t cli_len = sizeof(cli_addr);
  23136. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23137. if (cli == INVALID_SOCKET) { return; }
  23138. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23139. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23140. char buf[4096];
  23141. received = ::recv(cli, buf, sizeof(buf), 0);
  23142. });
  23143. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23144. // connect() has already shut the socket down by the time it returns false,
  23145. // so the peer sees EOF without waiting for the client to be destroyed.
  23146. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23147. {{"X-Bad", "a\r\nInjected: 1"}});
  23148. EXPECT_FALSE(client.connect());
  23149. t.join();
  23150. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23151. EXPECT_EQ(0, received);
  23152. }
  23153. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23154. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23155. // contains "upgrade" as a substring is a different token and must not
  23156. // start a WebSocket handshake.
  23157. auto make_request = [](const std::vector<std::string> &connection_values) {
  23158. Request req;
  23159. req.method = "GET";
  23160. req.headers.emplace("Upgrade", "websocket");
  23161. for (const auto &value : connection_values) {
  23162. req.headers.emplace("Connection", value);
  23163. }
  23164. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23165. req.headers.emplace("Sec-WebSocket-Version", "13");
  23166. return req;
  23167. };
  23168. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23169. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23170. EXPECT_TRUE(
  23171. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23172. EXPECT_TRUE(
  23173. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23174. EXPECT_TRUE(
  23175. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23176. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23177. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23178. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23179. EXPECT_FALSE(
  23180. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23181. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23182. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23183. }
  23184. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23185. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23186. // asks recipients to match each protocol-name case-insensitively, and RFC
  23187. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23188. // client naming websocket alongside another protocol, or on a second field
  23189. // line, is offering websocket; a value that merely contains "websocket" as a
  23190. // substring is a different protocol name and is not.
  23191. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23192. Request req;
  23193. req.method = "GET";
  23194. for (const auto &value : upgrade_values) {
  23195. req.headers.emplace("Upgrade", value);
  23196. }
  23197. req.headers.emplace("Connection", "Upgrade");
  23198. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23199. req.headers.emplace("Sec-WebSocket-Version", "13");
  23200. return req;
  23201. };
  23202. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23203. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23204. EXPECT_TRUE(
  23205. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23206. EXPECT_TRUE(
  23207. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23208. EXPECT_TRUE(
  23209. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23210. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23211. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23212. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23213. EXPECT_FALSE(
  23214. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23215. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23216. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23217. }
  23218. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23219. Server svr;
  23220. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23221. auto port = svr.bind_to_any_port("localhost");
  23222. std::thread t([&]() { svr.listen_after_bind(); });
  23223. auto se = detail::scope_exit([&] {
  23224. svr.stop();
  23225. t.join();
  23226. });
  23227. svr.wait_until_ready();
  23228. Headers headers = {{"Upgrade", "websocket"},
  23229. {"Connection", "notupgrade"},
  23230. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23231. {"Sec-WebSocket-Version", "13"}};
  23232. Client cli("localhost", port);
  23233. auto res = cli.Get("/ws", headers);
  23234. // The route exists only as a WebSocket route, so a request that fails the
  23235. // handshake check falls through to ordinary routing.
  23236. ASSERT_TRUE(res);
  23237. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23238. }
  23239. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  23240. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  23241. // Connection value is the only thing left for the client to reject.
  23242. Server svr;
  23243. svr.Get("/ws", [](const Request &req, Response &res) {
  23244. res.status = StatusCode::SwitchingProtocol_101;
  23245. res.set_header("Upgrade", "websocket");
  23246. res.set_header("Connection", "notupgrade");
  23247. res.set_header("Sec-WebSocket-Accept",
  23248. detail::websocket_accept_key(
  23249. req.get_header_value("Sec-WebSocket-Key")));
  23250. });
  23251. auto port = svr.bind_to_any_port("localhost");
  23252. std::thread t([&]() { svr.listen_after_bind(); });
  23253. auto se = detail::scope_exit([&] {
  23254. svr.stop();
  23255. t.join();
  23256. });
  23257. svr.wait_until_ready();
  23258. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23259. auto res = client.connect();
  23260. EXPECT_FALSE(res);
  23261. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23262. EXPECT_FALSE(client.is_open());
  23263. }
  23264. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  23265. Server svr;
  23266. svr.Get("/ws", [](const Request &req, Response &res) {
  23267. res.status = StatusCode::SwitchingProtocol_101;
  23268. res.set_header("Upgrade", "websocket");
  23269. res.set_header("Connection", "Upgrade");
  23270. res.set_header("Sec-WebSocket-Accept",
  23271. detail::websocket_accept_key(
  23272. req.get_header_value("Sec-WebSocket-Key")));
  23273. res.set_header("Sec-WebSocket-Protocol", "admin");
  23274. });
  23275. auto port = svr.bind_to_any_port("localhost");
  23276. std::thread t([&]() { svr.listen_after_bind(); });
  23277. auto se = detail::scope_exit([&] {
  23278. svr.stop();
  23279. t.join();
  23280. });
  23281. svr.wait_until_ready();
  23282. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23283. // Server selects a subprotocol the client never offered
  23284. {
  23285. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23286. ws::WebSocketClient client(url, headers);
  23287. auto res = client.connect();
  23288. EXPECT_FALSE(res);
  23289. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23290. EXPECT_FALSE(client.is_open());
  23291. EXPECT_TRUE(client.subprotocol().empty());
  23292. }
  23293. // Client offered none but the server named one anyway
  23294. {
  23295. ws::WebSocketClient client(url);
  23296. auto res = client.connect();
  23297. EXPECT_FALSE(res);
  23298. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23299. EXPECT_FALSE(client.is_open());
  23300. EXPECT_TRUE(client.subprotocol().empty());
  23301. }
  23302. }
  23303. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23304. // The socket path doubles as the URL host, so it must not contain '/'.
  23305. const char *shard = getenv("GTEST_SHARD_INDEX");
  23306. const std::string sock_path =
  23307. shard ? std::string("httplib-ws-") + shard + ".sock"
  23308. : std::string("httplib-ws.sock");
  23309. std::remove(sock_path.c_str());
  23310. Server svr;
  23311. std::mutex mtx;
  23312. std::string received_host;
  23313. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23314. {
  23315. std::lock_guard<std::mutex> lock(mtx);
  23316. received_host = req.get_header_value("Host");
  23317. }
  23318. std::string msg;
  23319. while (ws.read(msg)) {
  23320. ws.send(msg);
  23321. }
  23322. });
  23323. svr.set_address_family(AF_UNIX);
  23324. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  23325. auto se = detail::scope_exit([&] {
  23326. svr.stop();
  23327. t.join();
  23328. std::remove(sock_path.c_str());
  23329. });
  23330. svr.wait_until_ready();
  23331. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  23332. client.set_address_family(AF_UNIX);
  23333. ASSERT_TRUE(client.connect());
  23334. ASSERT_TRUE(client.send("hello"));
  23335. std::string msg;
  23336. ASSERT_TRUE(client.read(msg));
  23337. client.close();
  23338. {
  23339. std::lock_guard<std::mutex> lock(mtx);
  23340. // There is no host:port for a Unix socket, so the same "localhost"
  23341. // placeholder the HTTP client uses is expected.
  23342. EXPECT_EQ("localhost", received_host);
  23343. }
  23344. }
  23345. // Two threads must never parse WebSocket frames from the same stream.
  23346. // close() used to read the peer's Close reply with its own frame read, so it
  23347. // raced a reader thread that was in the middle of a payload: the payload loop
  23348. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  23349. // so bytes taken by close() were replaced with bytes from further along the
  23350. // stream. The message kept its length and silently changed content.
  23351. //
  23352. // The raw peer below sends a frame header plus part of the payload, waits for
  23353. // the handler to call close(), and only then sends the rest. Whichever thread
  23354. // would win the race for those bytes, the message must arrive intact, because
  23355. // close() must not touch the stream while read() owns it.
  23356. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23357. #ifndef _WIN32
  23358. signal(SIGPIPE, SIG_IGN);
  23359. #endif
  23360. const size_t payload_len = 120; // fits the 7-bit length field
  23361. const size_t prefix_len = 8;
  23362. const int attempts = 8;
  23363. std::string expected(payload_len, '\0');
  23364. for (size_t i = 0; i < payload_len; i++) {
  23365. expected[i] = static_cast<char>('a' + i % 26);
  23366. }
  23367. std::atomic<bool> peer_stalled{false};
  23368. std::atomic<bool> handler_done{false};
  23369. std::mutex received_mutex;
  23370. std::vector<std::string> received;
  23371. // Bound every wait, so a regression fails the test instead of hanging the
  23372. // suite.
  23373. auto wait_for = [](const std::atomic<bool> &flag) {
  23374. for (int i = 0; i < 500 && !flag; i++) {
  23375. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23376. }
  23377. };
  23378. Server svr;
  23379. svr.set_websocket_ping_interval(0);
  23380. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23381. std::thread reader([&]() {
  23382. std::string msg;
  23383. while (ws.read(msg)) {
  23384. std::lock_guard<std::mutex> guard(received_mutex);
  23385. received.push_back(msg);
  23386. }
  23387. });
  23388. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23389. // inside read_websocket_frame() when close() runs.
  23390. wait_for(peer_stalled);
  23391. ws.close();
  23392. reader.join();
  23393. handler_done = true;
  23394. });
  23395. auto port = svr.bind_to_any_port("127.0.0.1");
  23396. std::thread t([&]() { svr.listen_after_bind(); });
  23397. auto se = detail::scope_exit([&] {
  23398. svr.stop();
  23399. t.join();
  23400. });
  23401. svr.wait_until_ready();
  23402. auto send_bytes = [](socket_t s, const std::string &data) {
  23403. #ifdef _WIN32
  23404. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23405. #else
  23406. auto n = ::send(s, data.data(), data.size(), 0);
  23407. #endif
  23408. return n == static_cast<decltype(n)>(data.size());
  23409. };
  23410. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23411. // Every length used here fits the 7-bit length field.
  23412. auto masked_header = [](uint8_t first_byte, size_t len) {
  23413. std::string h;
  23414. h += static_cast<char>(first_byte);
  23415. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23416. h.append(4, '\0'); // mask key
  23417. return h;
  23418. };
  23419. for (int attempt = 0; attempt < attempts; attempt++) {
  23420. peer_stalled = false;
  23421. handler_done = false;
  23422. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23423. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23424. auto se_sock = detail::scope_exit([&] {
  23425. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23426. });
  23427. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23428. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23429. sockaddr_in addr{};
  23430. addr.sin_family = AF_INET;
  23431. addr.sin_port = htons(static_cast<uint16_t>(port));
  23432. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23433. ASSERT_EQ(
  23434. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23435. << "attempt " << attempt;
  23436. ASSERT_TRUE(send_bytes(sock,
  23437. "GET /ws HTTP/1.1\r\n"
  23438. "Host: 127.0.0.1\r\n"
  23439. "Upgrade: websocket\r\n"
  23440. "Connection: Upgrade\r\n"
  23441. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23442. "Sec-WebSocket-Version: 13\r\n"
  23443. "\r\n"))
  23444. << "attempt " << attempt;
  23445. std::string response;
  23446. while (response.find("\r\n\r\n") == std::string::npos) {
  23447. char buf[512];
  23448. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23449. if (n <= 0) { break; }
  23450. response.append(buf, static_cast<size_t>(n));
  23451. }
  23452. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23453. << "attempt " << attempt;
  23454. // Send the header of a Binary message but only the first prefix_len bytes
  23455. // of its payload, leaving the reader thread stalled inside the payload.
  23456. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23457. expected.substr(0, prefix_len)))
  23458. << "attempt " << attempt;
  23459. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23460. peer_stalled = true;
  23461. // Let close() send its Close frame and park in its own read before the
  23462. // rest of the payload arrives, so both threads are waiting for it.
  23463. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23464. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23465. close_frame += static_cast<char>(0x03); // status 1000
  23466. close_frame += static_cast<char>(0xE8);
  23467. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23468. << "attempt " << attempt;
  23469. // Closing the peer releases the reader thread even on the buggy path,
  23470. // where it waits for bytes another thread already consumed.
  23471. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23472. detail::close_socket(sock);
  23473. sock = INVALID_SOCKET;
  23474. wait_for(handler_done);
  23475. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23476. }
  23477. std::lock_guard<std::mutex> guard(received_mutex);
  23478. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23479. << "a message in flight when close() ran was dropped";
  23480. for (size_t i = 0; i < received.size(); i++) {
  23481. EXPECT_EQ(expected, received[i]) << "message " << i;
  23482. }
  23483. }
  23484. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23485. // returning the socket, or INVALID_SOCKET.
  23486. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23487. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23488. if (sock == INVALID_SOCKET) { return sock; }
  23489. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23490. sockaddr_in addr{};
  23491. addr.sin_family = AF_INET;
  23492. addr.sin_port = htons(static_cast<uint16_t>(port));
  23493. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23494. std::string req = "GET " + path +
  23495. " HTTP/1.1\r\n"
  23496. "Host: 127.0.0.1\r\n"
  23497. "Upgrade: websocket\r\n"
  23498. "Connection: Upgrade\r\n"
  23499. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23500. "Sec-WebSocket-Version: 13\r\n"
  23501. "\r\n";
  23502. std::string res;
  23503. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23504. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23505. static_cast<int>(req.size())) {
  23506. char c;
  23507. while (res.find("\r\n\r\n") == std::string::npos &&
  23508. ::recv(sock, &c, 1, 0) == 1) {
  23509. res += c;
  23510. }
  23511. }
  23512. if (res.find(" 101 ") == std::string::npos) {
  23513. detail::close_socket(sock);
  23514. return INVALID_SOCKET;
  23515. }
  23516. return sock;
  23517. }
  23518. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23519. // The payload must fit the 7-bit length field.
  23520. static std::string masked_frame(uint8_t first_byte,
  23521. const std::string &payload) {
  23522. std::string f;
  23523. f += static_cast<char>(first_byte);
  23524. f += static_cast<char>(0x80 | payload.size());
  23525. f.append(4, '\0');
  23526. return f + payload;
  23527. }
  23528. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23529. std::atomic<bool> done{false};
  23530. std::string received;
  23531. Server svr;
  23532. svr.set_websocket_ping_interval(0);
  23533. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23534. std::string msg;
  23535. if (ws.read(msg) == ws::Binary) { received = msg; }
  23536. done = true;
  23537. });
  23538. auto port = svr.bind_to_any_port("127.0.0.1");
  23539. std::thread t([&]() { svr.listen_after_bind(); });
  23540. auto se = detail::scope_exit([&] {
  23541. svr.stop();
  23542. t.join();
  23543. });
  23544. svr.wait_until_ready();
  23545. auto sock = connect_raw_websocket(port, "/ws");
  23546. ASSERT_NE(INVALID_SOCKET, sock);
  23547. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23548. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23549. masked_frame(0x89, "p") + // FIN + Ping
  23550. masked_frame(0x80, "lo"); // FIN + Continuation
  23551. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23552. for (int i = 0; i < 500 && !done; i++) {
  23553. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23554. }
  23555. ASSERT_TRUE(done);
  23556. EXPECT_EQ("Hello", received);
  23557. // The Ping between the fragments is answered with a Pong.
  23558. char pong[3];
  23559. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23560. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23561. }
  23562. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23563. Server svr;
  23564. svr.set_websocket_ping_interval(-1);
  23565. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23566. std::string msg;
  23567. while (ws.read(msg)) {}
  23568. });
  23569. auto port = svr.bind_to_any_port("127.0.0.1");
  23570. std::thread t([&]() { svr.listen_after_bind(); });
  23571. auto se = detail::scope_exit([&] {
  23572. svr.stop();
  23573. t.join();
  23574. });
  23575. svr.wait_until_ready();
  23576. auto sock = connect_raw_websocket(port, "/ws");
  23577. ASSERT_NE(INVALID_SOCKET, sock);
  23578. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23579. // Nothing comes while the client stays quiet.
  23580. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23581. char c;
  23582. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23583. }
  23584. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23585. Server svr;
  23586. svr.set_websocket_ping_interval(0);
  23587. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23588. std::string msg;
  23589. while (ws.read(msg)) {}
  23590. });
  23591. auto port = svr.bind_to_any_port("127.0.0.1");
  23592. std::thread t([&]() { svr.listen_after_bind(); });
  23593. auto se = detail::scope_exit([&] {
  23594. svr.stop();
  23595. t.join();
  23596. });
  23597. svr.wait_until_ready();
  23598. // Each Close payload and the reply it should get: an echo when valid, 1002
  23599. // otherwise.
  23600. std::vector<std::pair<std::string, std::string>> cases = {
  23601. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23602. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23603. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23604. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23605. };
  23606. // Also between the fragments of a message.
  23607. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23608. for (const auto &c : cases) {
  23609. auto sock = connect_raw_websocket(port, "/ws");
  23610. ASSERT_NE(INVALID_SOCKET, sock);
  23611. auto frames = prefix + masked_frame(0x88, c.first);
  23612. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23613. std::string reply;
  23614. char buf[256];
  23615. while (reply.size() < 2 + c.second.size()) {
  23616. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23617. if (n <= 0) { break; }
  23618. reply.append(buf, static_cast<size_t>(n));
  23619. }
  23620. detail::close_socket(sock);
  23621. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23622. c.second,
  23623. reply);
  23624. }
  23625. }
  23626. }
  23627. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23628. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23629. protected:
  23630. void SetUp() override {
  23631. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23632. SERVER_PRIVATE_KEY_FILE);
  23633. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23634. std::string msg;
  23635. ws::ReadResult ret;
  23636. while ((ret = ws.read(msg))) {
  23637. if (ret == ws::Binary) {
  23638. ws.send(msg.data(), msg.size());
  23639. } else {
  23640. ws.send(msg);
  23641. }
  23642. }
  23643. });
  23644. port_ = server_->bind_to_any_port(HOST);
  23645. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23646. server_->wait_until_ready();
  23647. }
  23648. void TearDown() override {
  23649. server_->stop();
  23650. if (server_thread_.joinable()) { server_thread_.join(); }
  23651. }
  23652. std::unique_ptr<SSLServer> server_;
  23653. std::thread server_thread_;
  23654. int port_ = 0;
  23655. };
  23656. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23657. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23658. {
  23659. ws::WebSocketClient client(url);
  23660. client.enable_server_certificate_verification(false);
  23661. auto calls = 0;
  23662. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23663. calls++;
  23664. return false;
  23665. });
  23666. EXPECT_FALSE(client.connect());
  23667. EXPECT_GT(calls, 0);
  23668. }
  23669. {
  23670. ws::WebSocketClient client(url);
  23671. client.enable_server_certificate_verification(false);
  23672. client.set_session_verifier([](tls::session_t) {
  23673. return SSLVerifierResponse::CertificateRejected;
  23674. });
  23675. EXPECT_FALSE(client.connect());
  23676. }
  23677. {
  23678. ws::WebSocketClient client(url);
  23679. client.enable_server_certificate_verification(false);
  23680. client.set_session_verifier([](tls::session_t) {
  23681. return SSLVerifierResponse::CertificateAccepted;
  23682. });
  23683. EXPECT_TRUE(client.connect());
  23684. }
  23685. }
  23686. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23687. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23688. "/ws-echo");
  23689. client.enable_server_certificate_verification(false);
  23690. ASSERT_TRUE(client.connect());
  23691. ASSERT_TRUE(client.is_open());
  23692. ASSERT_TRUE(client.send("Hello WSS"));
  23693. std::string msg;
  23694. EXPECT_EQ(ws::Text, client.read(msg));
  23695. EXPECT_EQ("Hello WSS", msg);
  23696. client.close();
  23697. }
  23698. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23699. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23700. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23701. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23702. // client (without calling close() first) is the only path that runs
  23703. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23704. // bug exactly.
  23705. //
  23706. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23707. // when linked against an instrumented libssl; run under Valgrind to catch it
  23708. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23709. // suite (the freed session otherwise stalls on the close handshake) — this test
  23710. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23711. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23712. {
  23713. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23714. "/ws-echo");
  23715. client.enable_server_certificate_verification(false);
  23716. client.set_read_timeout(2, 0);
  23717. client.set_write_timeout(2, 0);
  23718. ASSERT_TRUE(client.connect());
  23719. ASSERT_TRUE(client.is_open());
  23720. ASSERT_TRUE(client.send("still open"));
  23721. // Intentionally do NOT call client.close(): leaving scope runs
  23722. // shutdown_and_close() with the WebSocket still open, which must send the
  23723. // close frame while the TLS session is still alive.
  23724. }
  23725. }
  23726. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23727. // shutdown_and_close() at the start of connect(), reproducing the same
  23728. // use-after-free within the test body rather than at scope exit. The second
  23729. // connect must succeed and echo, proving the close handshake ran over a live
  23730. // session. See the note above about memory-tool requirements.
  23731. TEST_F(WebSocketSSLIntegrationTest,
  23732. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23733. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23734. "/ws-echo");
  23735. client.enable_server_certificate_verification(false);
  23736. client.set_read_timeout(2, 0);
  23737. client.set_write_timeout(2, 0);
  23738. ASSERT_TRUE(client.connect());
  23739. ASSERT_TRUE(client.is_open());
  23740. ASSERT_TRUE(client.send("still open"));
  23741. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23742. // the still-open connection, which must not touch a freed TLS session.
  23743. ASSERT_TRUE(client.connect());
  23744. ASSERT_TRUE(client.is_open());
  23745. ASSERT_TRUE(client.send("after reconnect"));
  23746. std::string msg;
  23747. EXPECT_EQ(ws::Text, client.read(msg));
  23748. EXPECT_EQ("after reconnect", msg);
  23749. client.close();
  23750. }
  23751. #endif
  23752. #ifdef CPPHTTPLIB_SSL_ENABLED
  23753. class WebSocketSSLCATest : public ::testing::Test {
  23754. protected:
  23755. void SetUp() override {
  23756. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23757. SERVER_PRIVATE_KEY_FILE);
  23758. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23759. std::string msg;
  23760. while (ws.read(msg)) {
  23761. ws.send(msg);
  23762. }
  23763. });
  23764. port_ = server_->bind_to_any_port("127.0.0.1");
  23765. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23766. server_->wait_until_ready();
  23767. }
  23768. void TearDown() override {
  23769. server_->stop();
  23770. if (server_thread_.joinable()) { server_thread_.join(); }
  23771. }
  23772. std::string url() const {
  23773. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23774. }
  23775. std::unique_ptr<SSLServer> server_;
  23776. std::thread server_thread_;
  23777. int port_ = 0;
  23778. };
  23779. // A custom CA loaded as PEM verifies the server with full certificate
  23780. // verification enabled
  23781. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23782. ws::WebSocketClient client(url());
  23783. std::string cert;
  23784. read_file(SERVER_CERT2_FILE, cert);
  23785. client.load_ca_cert_store(cert.c_str(), cert.size());
  23786. ASSERT_TRUE(client.connect());
  23787. ASSERT_TRUE(client.send("hello"));
  23788. std::string msg;
  23789. EXPECT_EQ(ws::Text, client.read(msg));
  23790. EXPECT_EQ("hello", msg);
  23791. client.close();
  23792. }
  23793. // A custom CA that does not cover the server must fail verification (the
  23794. // custom CA is exclusive; system certs are not loaded alongside it)
  23795. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23796. ws::WebSocketClient client(url());
  23797. std::string cert;
  23798. read_file(CLIENT_CA_CERT_FILE, cert);
  23799. client.load_ca_cert_store(cert.c_str(), cert.size());
  23800. auto res = client.connect();
  23801. ASSERT_FALSE(res);
  23802. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23803. EXPECT_EQ(-1, res.status());
  23804. EXPECT_NE(0u, res.ssl_backend_error());
  23805. }
  23806. // The same CA as a file path rather than PEM in memory
  23807. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23808. ws::WebSocketClient client(url());
  23809. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23810. ASSERT_TRUE(client.connect());
  23811. ASSERT_TRUE(client.send("hello"));
  23812. std::string msg;
  23813. EXPECT_EQ(ws::Text, client.read(msg));
  23814. EXPECT_EQ("hello", msg);
  23815. client.close();
  23816. }
  23817. // ...and a CA file that does not cover the server still fails, so it is the
  23818. // path above that decides the outcome
  23819. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23820. ws::WebSocketClient client(url());
  23821. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23822. ASSERT_FALSE(client.connect());
  23823. }
  23824. // Regression test: reconnecting with a native custom CA store used to reuse
  23825. // a store handle the previous TLS context had already freed (use-after-free
  23826. // under the OpenSSL backend). The context now lives as long as the client.
  23827. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23828. ws::WebSocketClient client(url());
  23829. std::string cert;
  23830. read_file(SERVER_CERT2_FILE, cert);
  23831. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23832. ASSERT_TRUE(client.connect());
  23833. client.close();
  23834. ASSERT_TRUE(client.connect());
  23835. ASSERT_TRUE(client.send("again"));
  23836. std::string msg;
  23837. EXPECT_EQ(ws::Text, client.read(msg));
  23838. EXPECT_EQ("again", msg);
  23839. client.close();
  23840. }
  23841. // Regression test: a certificate with a trusted chain but no identity match
  23842. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23843. // verification entirely for IP hosts, so this connection succeeded there.
  23844. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23845. // chain verification while the identity check must still fail.
  23846. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23848. ASSERT_TRUE(svr.is_valid());
  23849. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23850. std::string msg;
  23851. while (ws.read(msg)) {
  23852. ws.send(msg);
  23853. }
  23854. });
  23855. auto port = svr.bind_to_any_port("127.0.0.1");
  23856. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23857. auto se = detail::scope_exit([&] {
  23858. svr.stop();
  23859. t.join();
  23860. });
  23861. svr.wait_until_ready();
  23862. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23863. "/echo");
  23864. std::string cert;
  23865. read_file(SERVER_CERT_FILE, cert);
  23866. client.load_ca_cert_store(cert.c_str(), cert.size());
  23867. ASSERT_FALSE(client.connect());
  23868. }
  23869. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23870. // SNI, so nothing binds the host name to the TLS session. These bind the
  23871. // server to "localhost" instead, the only shape that exercises the SNI and
  23872. // hostname-verification path with certificate verification left enabled.
  23873. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23874. protected:
  23875. void Start(const char *cert_file) {
  23876. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23877. SERVER_PRIVATE_KEY_FILE);
  23878. ASSERT_TRUE(server_->is_valid());
  23879. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23880. std::string msg;
  23881. while (ws.read(msg)) {
  23882. ws.send(msg);
  23883. }
  23884. });
  23885. port_ = server_->bind_to_any_port("localhost");
  23886. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23887. server_->wait_until_ready();
  23888. }
  23889. void TearDown() override {
  23890. if (server_) { server_->stop(); }
  23891. if (server_thread_.joinable()) { server_thread_.join(); }
  23892. }
  23893. std::string url() const {
  23894. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23895. }
  23896. std::unique_ptr<SSLServer> server_;
  23897. std::thread server_thread_;
  23898. int port_ = 0;
  23899. };
  23900. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23901. // out and the connection is usable
  23902. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23903. Start(SERVER_CERT2_FILE);
  23904. ws::WebSocketClient client(url());
  23905. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23906. ASSERT_TRUE(client.connect());
  23907. ASSERT_TRUE(client.send("hello"));
  23908. std::string msg;
  23909. EXPECT_EQ(ws::Text, client.read(msg));
  23910. EXPECT_EQ("hello", msg);
  23911. client.close();
  23912. }
  23913. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23914. // while the identity check must still reject "localhost"
  23915. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23916. Start(SERVER_CERT_FILE);
  23917. ws::WebSocketClient client(url());
  23918. client.set_ca_cert_path(SERVER_CERT_FILE);
  23919. auto res = client.connect();
  23920. ASSERT_FALSE(res);
  23921. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23922. EXPECT_EQ(-1, res.status());
  23923. }
  23924. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23925. // disabled: the chain is still checked, only the identity check is skipped
  23926. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23927. Start(SERVER_CERT_FILE);
  23928. ws::WebSocketClient client(url());
  23929. client.set_ca_cert_path(SERVER_CERT_FILE);
  23930. client.enable_server_hostname_verification(false);
  23931. ASSERT_TRUE(client.connect());
  23932. ASSERT_TRUE(client.send("hello"));
  23933. std::string msg;
  23934. EXPECT_EQ(ws::Text, client.read(msg));
  23935. EXPECT_EQ("hello", msg);
  23936. client.close();
  23937. }
  23938. // A CA that did not sign the server certificate fails the chain, even though
  23939. // the name would match
  23940. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23941. Start(SERVER_CERT2_FILE);
  23942. ws::WebSocketClient client(url());
  23943. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23944. ASSERT_FALSE(client.connect());
  23945. }
  23946. // With verification disabled, neither the chain nor the name is checked
  23947. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23948. Start(SERVER_CERT_FILE);
  23949. ws::WebSocketClient client(url());
  23950. client.enable_server_certificate_verification(false);
  23951. ASSERT_TRUE(client.connect());
  23952. ASSERT_TRUE(client.send("hello"));
  23953. std::string msg;
  23954. EXPECT_EQ(ws::Text, client.read(msg));
  23955. EXPECT_EQ("hello", msg);
  23956. client.close();
  23957. }
  23958. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23959. protected:
  23960. void SetUp() override {
  23961. server_ = httplib::detail::make_unique<SSLServer>(
  23962. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23963. ASSERT_TRUE(server_->is_valid());
  23964. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23965. std::string msg;
  23966. while (ws.read(msg)) {
  23967. ws.send(msg);
  23968. }
  23969. });
  23970. port_ = server_->bind_to_any_port("localhost");
  23971. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23972. server_->wait_until_ready();
  23973. }
  23974. void TearDown() override {
  23975. server_->stop();
  23976. if (server_thread_.joinable()) { server_thread_.join(); }
  23977. }
  23978. std::string url() const {
  23979. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23980. }
  23981. void ConnectWithClientCert(const std::string &client_cert_file,
  23982. const std::string &client_private_key_file,
  23983. const char *private_key_password) {
  23984. std::string cert_pem, key_pem;
  23985. read_file(client_cert_file, cert_pem);
  23986. read_file(client_private_key_file, key_pem);
  23987. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23988. key_pem.c_str(), key_pem.size(),
  23989. private_key_password};
  23990. ws::WebSocketClient client(url(), pem);
  23991. ASSERT_TRUE(client.is_valid());
  23992. client.enable_server_certificate_verification(false);
  23993. ASSERT_TRUE(client.connect());
  23994. ASSERT_TRUE(client.send("hello"));
  23995. std::string msg;
  23996. EXPECT_EQ(ws::Text, client.read(msg));
  23997. EXPECT_EQ("hello", msg);
  23998. client.close();
  23999. }
  24000. std::unique_ptr<SSLServer> server_;
  24001. std::thread server_thread_;
  24002. int port_ = 0;
  24003. };
  24004. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24005. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24006. }
  24007. // Control for the tests above: the fixture's server really does require a
  24008. // client certificate, so it is the PEM the constructor installed that decides
  24009. // the outcome.
  24010. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24011. ws::WebSocketClient client(url());
  24012. ASSERT_TRUE(client.is_valid());
  24013. client.enable_server_certificate_verification(false);
  24014. EXPECT_FALSE(client.connect());
  24015. }
  24016. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24017. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24018. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24019. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24020. }
  24021. #endif
  24022. #if !defined(_WIN32)
  24023. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24024. auto secret_dir = std::string("./symlink_test_secret");
  24025. auto served_dir = std::string("./symlink_test_served");
  24026. auto secret_file = secret_dir + "/secret.txt";
  24027. auto symlink_path = served_dir + "/escape";
  24028. // Setup: create directories and files
  24029. mkdir(secret_dir.c_str(), 0755);
  24030. mkdir(served_dir.c_str(), 0755);
  24031. {
  24032. std::ofstream ofs(secret_file);
  24033. ofs << "SECRET_DATA";
  24034. }
  24035. // Create symlink using absolute path so it resolves correctly
  24036. #ifdef PATH_MAX
  24037. char abs_secret[PATH_MAX];
  24038. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24039. #else
  24040. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24041. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24042. ASSERT_NE(nullptr, abs_secret);
  24043. #endif
  24044. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24045. auto se = detail::scope_exit([&] {
  24046. unlink(symlink_path.c_str());
  24047. unlink(secret_file.c_str());
  24048. rmdir(served_dir.c_str());
  24049. rmdir(secret_dir.c_str());
  24050. });
  24051. Server svr;
  24052. svr.set_mount_point("/", served_dir);
  24053. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24054. auto se2 = detail::scope_exit([&] {
  24055. svr.stop();
  24056. listen_thread.join();
  24057. });
  24058. svr.wait_until_ready();
  24059. Client cli("localhost", PORT);
  24060. // Symlink pointing outside base dir should be blocked
  24061. auto res = cli.Get("/escape/secret.txt");
  24062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24063. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24064. }
  24065. #endif
  24066. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24067. // "GET /smuggled" request), reads the first response, and only then sends the
  24068. // embedded request as the body. Returns how many times /smuggled ran.
  24069. //
  24070. // The body is sent AFTER receiving the first response (as in the original
  24071. // PoC) so that the stream_line_reader cannot buffer it together with the
  24072. // headers of the first request.
  24073. static int count_smuggled_requests(const std::string &outer_head,
  24074. std::string &first_response) {
  24075. Server svr;
  24076. svr.set_mount_point("/", "./www");
  24077. std::atomic<int> smuggled_count(0);
  24078. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24079. smuggled_count++;
  24080. res.set_content("oops", "text/plain");
  24081. });
  24082. svr.Post("/post", [&](const Request &req, Response &res) {
  24083. res.set_content(req.body, "text/plain");
  24084. });
  24085. auto port = svr.bind_to_any_port("localhost");
  24086. thread t = thread([&] { svr.listen_after_bind(); });
  24087. auto se = detail::scope_exit([&] {
  24088. svr.stop();
  24089. t.join();
  24090. });
  24091. svr.wait_until_ready();
  24092. auto error = Error::Success;
  24093. auto sock = detail::create_client_socket(
  24094. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24095. /*connection_timeout_sec=*/2, 0,
  24096. /*read_timeout_sec=*/2, 0,
  24097. /*write_timeout_sec=*/2, 0, std::string(), error);
  24098. EXPECT_NE(INVALID_SOCKET, sock);
  24099. if (sock == INVALID_SOCKET) { return -1; }
  24100. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24101. // The "smuggled" request will be sent as the body of the outer request
  24102. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24103. "Host: localhost\r\n"
  24104. "Connection: close\r\n"
  24105. "\r\n";
  24106. auto head = outer_head;
  24107. auto len = std::to_string(smuggled.size());
  24108. for (auto pos = head.find("{len}"); pos != std::string::npos;
  24109. pos = head.find("{len}", pos + len.size())) {
  24110. head.replace(pos, 5, len);
  24111. }
  24112. // Step 1: Send only the outer request headers (no body yet)
  24113. auto sent = send(sock, head.data(), head.size(), 0);
  24114. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  24115. // Step 2: Read the first response
  24116. char buf[4096];
  24117. for (;;) {
  24118. auto n = recv(sock, buf, sizeof(buf), 0);
  24119. if (n <= 0) break;
  24120. first_response.append(buf, static_cast<size_t>(n));
  24121. // Stop once we have a complete response (headers + body)
  24122. auto hdr_end = first_response.find("\r\n\r\n");
  24123. if (hdr_end != std::string::npos) {
  24124. // Check for Content-Length to know when the body is complete
  24125. auto cl_pos = first_response.find("Content-Length:");
  24126. if (cl_pos != std::string::npos) {
  24127. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  24128. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  24129. auto cl = std::stoul(
  24130. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  24131. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  24132. } else {
  24133. break; // No Content-Length, assume headers-only response
  24134. }
  24135. }
  24136. }
  24137. // Step 3: Now send the body, which looks like a new HTTP request. On a
  24138. // vulnerable server the keep-alive loop reads this as a second request. The
  24139. // server may already have closed the connection, so the result is ignored.
  24140. send(sock, smuggled.data(), smuggled.size(), 0);
  24141. // Half-close so that a server which drained the body sees EOF and closes,
  24142. // instead of the read below waiting for the read timeout.
  24143. #ifdef _WIN32
  24144. ::shutdown(sock, SD_SEND);
  24145. #else
  24146. ::shutdown(sock, SHUT_WR);
  24147. #endif
  24148. // Step 4: Read until the server closes the connection
  24149. for (;;) {
  24150. auto n = recv(sock, buf, sizeof(buf), 0);
  24151. if (n <= 0) break;
  24152. }
  24153. return smuggled_count.load();
  24154. }
  24155. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  24156. // A GET request with Content-Length to a static file handler must have its
  24157. // body drained before the keep-alive connection is reused. Otherwise the
  24158. // unread body bytes are interpreted as the next HTTP request.
  24159. std::string first_response;
  24160. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24161. "Host: localhost\r\n"
  24162. "Content-Length: {len}\r\n"
  24163. "\r\n",
  24164. first_response));
  24165. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  24166. }
  24167. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  24168. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  24169. // be answered with 400 and the connection closed. Treating it as "no body"
  24170. // leaves the body to be parsed as the next request.
  24171. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  24172. const char *targets[] = {
  24173. "GET /file", // handler that never reads the body
  24174. "GET /not-found", // no handler matches (404)
  24175. "POST /post", // handler that reads the body
  24176. };
  24177. for (auto target : targets) {
  24178. for (auto value : values) {
  24179. std::string first_response;
  24180. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  24181. " HTTP/1.1\r\n"
  24182. "Host: localhost\r\n"
  24183. "Content-Length: " +
  24184. value + "\r\n\r\n",
  24185. first_response))
  24186. << target << " with Content-Length: " << value;
  24187. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  24188. << target << " with Content-Length: " << value;
  24189. }
  24190. }
  24191. }
  24192. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  24193. // A 400 for an unparseable request line leaves the rest of the message
  24194. // unread, so the connection must be closed rather than reused.
  24195. std::string first_response;
  24196. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  24197. "Host: localhost\r\n"
  24198. "Content-Length: {len}\r\n"
  24199. "\r\n",
  24200. first_response));
  24201. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24202. }
  24203. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  24204. // Same as above for a header block that fails to parse.
  24205. std::string first_response;
  24206. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24207. "Host: localhost\r\n"
  24208. "Bad Header\r\n"
  24209. "Content-Length: {len}\r\n"
  24210. "\r\n",
  24211. first_response));
  24212. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24213. }
  24214. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  24215. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  24216. // server must not read another request on that connection, even when the
  24217. // request had no body to drain.
  24218. std::string first_response;
  24219. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  24220. "Host: localhost\r\n"
  24221. "\r\n",
  24222. first_response));
  24223. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  24224. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  24225. }
  24226. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  24227. // A content reader that stops early leaves the stream inside the body.
  24228. // Draining the whole Content-Length from there, or reading the body again,
  24229. // reads into the next request, and whatever follows is parsed as a request
  24230. // of its own.
  24231. Server svr;
  24232. std::atomic<int> smuggled_count(0);
  24233. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  24234. svr.Post("/upload", [](const Request &req, Response &res,
  24235. const ContentReader &content_reader) {
  24236. // Stop at the last chunk, so the whole body has been read however it
  24237. // arrives.
  24238. auto length = req.get_header_value_u64("Content-Length");
  24239. size_t total = 0;
  24240. auto consumed = content_reader([&](const char *, size_t n) {
  24241. total += n;
  24242. return total < length;
  24243. });
  24244. EXPECT_FALSE(consumed);
  24245. if (req.has_param("retry")) {
  24246. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  24247. }
  24248. // Replace the 400 the aborted read set, which would close the connection.
  24249. res.set_redirect("/done");
  24250. });
  24251. auto port = svr.bind_to_any_port(HOST);
  24252. thread t = thread([&] { svr.listen_after_bind(); });
  24253. auto se = detail::scope_exit([&] {
  24254. svr.stop();
  24255. t.join();
  24256. });
  24257. svr.wait_until_ready();
  24258. // A front end sees the second request as a POST whose body is the GET. The
  24259. // first body is as long as the POST's headers, so draining it again reads
  24260. // exactly those and leaves the GET to be parsed next.
  24261. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  24262. "Host: localhost\r\n"
  24263. "\r\n";
  24264. std::string second_head = "POST /post HTTP/1.1\r\n"
  24265. "Host: localhost\r\n"
  24266. "Content-Length: " +
  24267. std::to_string(inner.size()) +
  24268. "\r\n"
  24269. "\r\n";
  24270. for (auto target : {"/upload", "/upload?retry"}) {
  24271. smuggled_count = 0;
  24272. std::string request = "POST " + std::string(target) +
  24273. " HTTP/1.1\r\n"
  24274. "Host: localhost\r\n"
  24275. "Content-Length: " +
  24276. std::to_string(second_head.size()) +
  24277. "\r\n"
  24278. "\r\n" +
  24279. std::string(second_head.size(), 'A') + second_head +
  24280. inner;
  24281. std::string response;
  24282. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  24283. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  24284. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  24285. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  24286. EXPECT_EQ(0, smuggled_count.load()) << target;
  24287. }
  24288. }
  24289. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  24290. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  24291. // must be rejected with 400 Bad Request.
  24292. Server svr;
  24293. svr.Post("/test", [&](const Request &, Response &res) {
  24294. res.set_content("ok", "text/plain");
  24295. });
  24296. thread t = thread([&] { svr.listen(HOST, PORT); });
  24297. auto se = detail::scope_exit([&] {
  24298. svr.stop();
  24299. t.join();
  24300. ASSERT_FALSE(svr.is_running());
  24301. });
  24302. svr.wait_until_ready();
  24303. // Exact "chunked"
  24304. {
  24305. auto req = "POST /test HTTP/1.1\r\n"
  24306. "Host: localhost\r\n"
  24307. "Content-Length: 5\r\n"
  24308. "Transfer-Encoding: chunked\r\n"
  24309. "Connection: close\r\n"
  24310. "\r\n"
  24311. "hello";
  24312. std::string response;
  24313. ASSERT_TRUE(send_request(1, req, &response));
  24314. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24315. response.substr(0, response.find("\r\n")));
  24316. }
  24317. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  24318. {
  24319. auto req = "POST /test HTTP/1.1\r\n"
  24320. "Host: localhost\r\n"
  24321. "Content-Length: 5\r\n"
  24322. "Transfer-Encoding: gzip, chunked\r\n"
  24323. "Connection: close\r\n"
  24324. "\r\n"
  24325. "hello";
  24326. std::string response;
  24327. ASSERT_TRUE(send_request(1, req, &response));
  24328. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24329. response.substr(0, response.find("\r\n")));
  24330. }
  24331. }
  24332. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  24333. Server svr;
  24334. svr.Post("/test", [&](const Request &, Response &res) {
  24335. res.set_content("ok", "text/plain");
  24336. });
  24337. thread t = thread([&] { svr.listen(HOST, PORT); });
  24338. auto se = detail::scope_exit([&] {
  24339. svr.stop();
  24340. t.join();
  24341. ASSERT_FALSE(svr.is_running());
  24342. });
  24343. svr.wait_until_ready();
  24344. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  24345. // length cannot be determined, so the server must answer 400 and close
  24346. // rather than treat the request as bodyless and leave the body in the
  24347. // socket for the next request to pick up.
  24348. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  24349. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  24350. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  24351. std::string response;
  24352. ASSERT_TRUE(send_request(1, req, &response));
  24353. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24354. response.substr(0, response.find("\r\n")))
  24355. << transfer_encoding;
  24356. }
  24357. // RFC 9110 5.3: the codings may also be split across several
  24358. // Transfer-Encoding lines, which combine in the order they were received.
  24359. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24360. // just like the single-line "chunked, gzip" above.
  24361. {
  24362. auto req = "POST /test HTTP/1.1\r\n"
  24363. "Host: localhost\r\n"
  24364. "Transfer-Encoding: chunked\r\n"
  24365. "Transfer-Encoding: gzip\r\n"
  24366. "\r\n"
  24367. "0\r\n\r\n";
  24368. std::string response;
  24369. ASSERT_TRUE(send_request(1, req, &response));
  24370. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24371. response.substr(0, response.find("\r\n")));
  24372. }
  24373. // A sequence ending in chunked stays valid.
  24374. auto req = "POST /test HTTP/1.1\r\n"
  24375. "Host: localhost\r\n"
  24376. "Transfer-Encoding: gzip, chunked\r\n"
  24377. "Connection: close\r\n"
  24378. "\r\n"
  24379. "0\r\n\r\n";
  24380. std::string response;
  24381. ASSERT_TRUE(send_request(1, req, &response));
  24382. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24383. // ...including when it is spread over several lines.
  24384. auto split_req = "POST /test HTTP/1.1\r\n"
  24385. "Host: localhost\r\n"
  24386. "Transfer-Encoding: gzip\r\n"
  24387. "Transfer-Encoding: chunked\r\n"
  24388. "Connection: close\r\n"
  24389. "\r\n"
  24390. "0\r\n\r\n";
  24391. std::string split_response;
  24392. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24393. EXPECT_EQ("HTTP/1.1 200 OK",
  24394. split_response.substr(0, split_response.find("\r\n")));
  24395. }
  24396. // Regression for issue #2450: a DELETE without Content-Length on a
  24397. // keep-alive connection must not let the post-response drain consume the
  24398. // next request's bytes.
  24399. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24400. Server svr;
  24401. std::atomic<int> delete_count(0);
  24402. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24403. delete_count++;
  24404. res.status = StatusCode::NoContent_204;
  24405. });
  24406. auto port = svr.bind_to_any_port(HOST);
  24407. thread t = thread([&] { svr.listen_after_bind(); });
  24408. auto se = detail::scope_exit([&] {
  24409. svr.stop();
  24410. t.join();
  24411. });
  24412. svr.wait_until_ready();
  24413. auto error = Error::Success;
  24414. auto sock = detail::create_client_socket(
  24415. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24416. /*connection_timeout_sec=*/2, 0,
  24417. /*read_timeout_sec=*/2, 0,
  24418. /*write_timeout_sec=*/2, 0, std::string(), error);
  24419. ASSERT_NE(INVALID_SOCKET, sock);
  24420. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24421. auto send_request_and_read_response = [&](const std::string &req,
  24422. std::string &out) -> bool {
  24423. auto sent = send(sock, req.data(), req.size(), 0);
  24424. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24425. char buf[4096];
  24426. for (;;) {
  24427. auto n = recv(sock, buf, sizeof(buf), 0);
  24428. if (n <= 0) { return !out.empty(); }
  24429. out.append(buf, static_cast<size_t>(n));
  24430. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24431. }
  24432. };
  24433. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24434. "Host: localhost\r\n"
  24435. "\r\n";
  24436. std::string resp1;
  24437. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24438. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24439. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24440. "Host: localhost\r\n"
  24441. "Connection: close\r\n"
  24442. "\r\n";
  24443. std::string resp2;
  24444. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24445. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24446. EXPECT_EQ(2, delete_count.load());
  24447. }
  24448. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24449. Server svr;
  24450. svr.Post("/ingest", [&](const Request &, Response &res,
  24451. const ContentReader &content_reader) {
  24452. auto consumed = content_reader([](const char *, size_t) { return false; });
  24453. EXPECT_FALSE(consumed);
  24454. res.status = StatusCode::Conflict_409;
  24455. res.set_header("Connection", "close");
  24456. });
  24457. auto port = svr.bind_to_any_port(HOST);
  24458. thread t = thread([&] { svr.listen_after_bind(); });
  24459. auto se = detail::scope_exit([&] {
  24460. svr.stop();
  24461. t.join();
  24462. });
  24463. svr.wait_until_ready();
  24464. auto error = Error::Success;
  24465. auto sock = detail::create_client_socket(
  24466. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24467. /*connection_timeout_sec=*/2, 0,
  24468. /*read_timeout_sec=*/1, 0,
  24469. /*write_timeout_sec=*/2, 0, std::string(), error);
  24470. ASSERT_NE(INVALID_SOCKET, sock);
  24471. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24472. std::string request = "POST /ingest HTTP/1.1\r\n"
  24473. "Host: localhost\r\n"
  24474. "Transfer-Encoding: chunked\r\n"
  24475. "\r\n"
  24476. "4\r\n"
  24477. "data\r\n";
  24478. auto sent = send(sock, request.data(), request.size(), 0);
  24479. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24480. std::string response;
  24481. ssize_t received = 0;
  24482. do {
  24483. char buf[4096];
  24484. received = recv(sock, buf, sizeof(buf), 0);
  24485. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24486. } while (received > 0);
  24487. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24488. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24489. EXPECT_EQ(0, received);
  24490. }
  24491. namespace no_proxy_test {
  24492. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24493. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24494. // calling listen().
  24495. class ScopedServer {
  24496. public:
  24497. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24498. ~ScopedServer() {
  24499. svr_.stop();
  24500. if (th_.joinable()) { th_.join(); }
  24501. }
  24502. Server &svr() { return svr_; }
  24503. int port() const { return port_; }
  24504. void listen() {
  24505. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24506. svr_.wait_until_ready();
  24507. }
  24508. private:
  24509. Server svr_;
  24510. std::thread th_;
  24511. int port_ = 0;
  24512. };
  24513. class ProxyAndTargetServers {
  24514. public:
  24515. ProxyAndTargetServers() {
  24516. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24517. proxy_hits_++;
  24518. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24519. res.set_content("via-proxy", "text/plain");
  24520. });
  24521. target_.Get(".*", [this](const Request &req, Response &res) {
  24522. target_hits_++;
  24523. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24524. res.set_content("direct", "text/plain");
  24525. });
  24526. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24527. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24528. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24529. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24530. proxy_mock_.wait_until_ready();
  24531. target_.wait_until_ready();
  24532. }
  24533. ~ProxyAndTargetServers() {
  24534. proxy_mock_.stop();
  24535. target_.stop();
  24536. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24537. if (target_thread_.joinable()) { target_thread_.join(); }
  24538. }
  24539. Server &proxy_mock() { return proxy_mock_; }
  24540. Server &target() { return target_; }
  24541. int proxy_port() const { return proxy_port_; }
  24542. int target_port() const { return target_port_; }
  24543. int proxy_hits() const { return proxy_hits_.load(); }
  24544. int target_hits() const { return target_hits_.load(); }
  24545. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24546. void reset_counters() {
  24547. proxy_hits_ = 0;
  24548. target_hits_ = 0;
  24549. last_had_proxy_authz_ = false;
  24550. }
  24551. private:
  24552. Server proxy_mock_;
  24553. Server target_;
  24554. std::thread proxy_thread_;
  24555. std::thread target_thread_;
  24556. int proxy_port_ = 0;
  24557. int target_port_ = 0;
  24558. std::atomic<int> proxy_hits_{0};
  24559. std::atomic<int> target_hits_{0};
  24560. std::atomic<bool> last_had_proxy_authz_{false};
  24561. };
  24562. inline std::unique_ptr<Client> make_client(const std::string &host,
  24563. ProxyAndTargetServers &s) {
  24564. auto cli = detail::make_unique<Client>(host, s.target_port());
  24565. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24566. cli->set_proxy("127.0.0.1", s.proxy_port());
  24567. return cli;
  24568. }
  24569. } // namespace no_proxy_test
  24570. using no_proxy_test::make_client;
  24571. using no_proxy_test::ProxyAndTargetServers;
  24572. TEST(NoProxyTest, ExactHostnameBypasses) {
  24573. ProxyAndTargetServers s;
  24574. auto cli = make_client("example.com", s);
  24575. cli->set_no_proxy({"example.com"});
  24576. auto res = cli->Get("/");
  24577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24578. EXPECT_EQ(0, s.proxy_hits());
  24579. EXPECT_EQ(1, s.target_hits());
  24580. }
  24581. TEST(NoProxyTest, SubdomainBypasses) {
  24582. ProxyAndTargetServers s;
  24583. auto cli = make_client("foo.example.com", s);
  24584. cli->set_no_proxy({"example.com"});
  24585. auto res = cli->Get("/");
  24586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24587. EXPECT_EQ(0, s.proxy_hits());
  24588. EXPECT_EQ(1, s.target_hits());
  24589. }
  24590. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24591. // Regression guard: "evilexample.com" must not be considered a subdomain
  24592. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24593. // check would let traffic bypass the proxy and leak credentials direct
  24594. // to the attacker host.
  24595. ProxyAndTargetServers s;
  24596. auto cli = make_client("evilexample.com", s);
  24597. cli->set_no_proxy({"example.com"});
  24598. auto res = cli->Get("/");
  24599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24600. EXPECT_GE(s.proxy_hits(), 1);
  24601. EXPECT_EQ(0, s.target_hits());
  24602. }
  24603. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24604. ProxyAndTargetServers s;
  24605. auto cli = make_client("example.com.evil.com", s);
  24606. cli->set_no_proxy({"example.com"});
  24607. auto res = cli->Get("/");
  24608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24609. EXPECT_GE(s.proxy_hits(), 1);
  24610. EXPECT_EQ(0, s.target_hits());
  24611. }
  24612. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24613. ProxyAndTargetServers s;
  24614. auto cli = make_client("example.com", s);
  24615. cli->set_no_proxy({".example.com"});
  24616. auto res = cli->Get("/");
  24617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24618. EXPECT_EQ(0, s.proxy_hits());
  24619. EXPECT_EQ(1, s.target_hits());
  24620. }
  24621. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24622. ProxyAndTargetServers s;
  24623. auto cli = make_client("Example.COM", s);
  24624. cli->set_no_proxy({"EXAMPLE.com"});
  24625. auto res = cli->Get("/");
  24626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24627. EXPECT_EQ(0, s.proxy_hits());
  24628. EXPECT_EQ(1, s.target_hits());
  24629. }
  24630. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24631. ProxyAndTargetServers s;
  24632. auto cli = make_client("example.com.", s);
  24633. cli->set_no_proxy({"example.com"});
  24634. auto res = cli->Get("/");
  24635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24636. EXPECT_EQ(0, s.proxy_hits());
  24637. EXPECT_EQ(1, s.target_hits());
  24638. }
  24639. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24640. // Trailing dots must be normalized on BOTH sides — host and entry.
  24641. // An implementation that only strips the host-side trailing dot would
  24642. // fail to match host "example.com" against entry "example.com." because
  24643. // a literal substring search would compare 11 chars against 12.
  24644. ProxyAndTargetServers s;
  24645. auto cli = make_client("example.com", s);
  24646. cli->set_no_proxy({"example.com."});
  24647. auto res = cli->Get("/");
  24648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24649. EXPECT_EQ(0, s.proxy_hits());
  24650. EXPECT_EQ(1, s.target_hits());
  24651. }
  24652. TEST(NoProxyTest, WildcardBypassesEverything) {
  24653. ProxyAndTargetServers s;
  24654. auto cli = make_client("anything.invalid.test", s);
  24655. cli->set_no_proxy({"*"});
  24656. auto res = cli->Get("/");
  24657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24658. EXPECT_EQ(0, s.proxy_hits());
  24659. EXPECT_EQ(1, s.target_hits());
  24660. }
  24661. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24662. ProxyAndTargetServers s;
  24663. Client cli("127.0.0.1", s.target_port());
  24664. cli.set_proxy("127.0.0.1", s.proxy_port());
  24665. cli.set_no_proxy({"127.0.0.1"});
  24666. auto res = cli.Get("/");
  24667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24668. EXPECT_EQ(0, s.proxy_hits());
  24669. EXPECT_EQ(1, s.target_hits());
  24670. }
  24671. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24672. ProxyAndTargetServers s;
  24673. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24674. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24675. cli.set_proxy("127.0.0.1", s.proxy_port());
  24676. cli.set_no_proxy({"::1"});
  24677. auto res = cli.Get("/");
  24678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24679. EXPECT_EQ(0, s.proxy_hits());
  24680. EXPECT_EQ(1, s.target_hits());
  24681. }
  24682. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24683. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24684. // must still be recognized as IPv6 for CIDR matching. Implementations
  24685. // that detect IPv6 only when the host begins with '[' would parse the
  24686. // host as a hostname and miss the match.
  24687. ProxyAndTargetServers s;
  24688. Client cli("fe80::1", s.target_port());
  24689. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24690. cli.set_proxy("127.0.0.1", s.proxy_port());
  24691. cli.set_no_proxy({"fe80::/10"});
  24692. auto res = cli.Get("/");
  24693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24694. EXPECT_EQ(0, s.proxy_hits());
  24695. EXPECT_EQ(1, s.target_hits());
  24696. }
  24697. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24698. ProxyAndTargetServers s;
  24699. Client cli("::1", s.target_port());
  24700. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24701. cli.set_proxy("127.0.0.1", s.proxy_port());
  24702. cli.set_no_proxy({"[::1]"});
  24703. auto res = cli.Get("/");
  24704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24705. EXPECT_EQ(0, s.proxy_hits());
  24706. EXPECT_EQ(1, s.target_hits());
  24707. }
  24708. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24709. ProxyAndTargetServers s;
  24710. Client cli("fe80::1", s.target_port());
  24711. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24712. cli.set_proxy("127.0.0.1", s.proxy_port());
  24713. cli.set_no_proxy({"[fe80::]/10"});
  24714. auto res = cli.Get("/");
  24715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24716. EXPECT_EQ(0, s.proxy_hits());
  24717. EXPECT_EQ(1, s.target_hits());
  24718. }
  24719. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24720. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24721. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24722. // tricks via address-family conversion.
  24723. ProxyAndTargetServers s;
  24724. Client cli("::ffff:127.0.0.1", s.target_port());
  24725. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24726. cli.set_proxy("127.0.0.1", s.proxy_port());
  24727. cli.set_no_proxy({"127.0.0.1"});
  24728. auto res = cli.Get("/");
  24729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24730. EXPECT_GE(s.proxy_hits(), 1);
  24731. EXPECT_EQ(0, s.target_hits());
  24732. }
  24733. TEST(NoProxyTest, IPv4CidrMatch) {
  24734. ProxyAndTargetServers s;
  24735. Client cli("127.0.0.1", s.target_port());
  24736. cli.set_proxy("127.0.0.1", s.proxy_port());
  24737. cli.set_no_proxy({"127.0.0.0/8"});
  24738. auto res = cli.Get("/");
  24739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24740. EXPECT_EQ(0, s.proxy_hits());
  24741. EXPECT_EQ(1, s.target_hits());
  24742. }
  24743. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24744. ProxyAndTargetServers s;
  24745. Client cli("127.0.0.1", s.target_port());
  24746. cli.set_proxy("127.0.0.1", s.proxy_port());
  24747. cli.set_no_proxy({"10.0.0.0/8"});
  24748. auto res = cli.Get("/");
  24749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24750. EXPECT_GE(s.proxy_hits(), 1);
  24751. EXPECT_EQ(0, s.target_hits());
  24752. }
  24753. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24754. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24755. // IPv4 target matches.
  24756. ProxyAndTargetServers s;
  24757. Client cli("127.0.0.1", s.target_port());
  24758. cli.set_proxy("127.0.0.1", s.proxy_port());
  24759. cli.set_no_proxy({"0.0.0.0/0"});
  24760. auto res = cli.Get("/");
  24761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24762. EXPECT_EQ(0, s.proxy_hits());
  24763. EXPECT_EQ(1, s.target_hits());
  24764. }
  24765. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24766. ProxyAndTargetServers s;
  24767. Client cli("127.0.0.1", s.target_port());
  24768. cli.set_proxy("127.0.0.1", s.proxy_port());
  24769. cli.set_no_proxy({"127.0.0.1"});
  24770. auto res = cli.Get("/");
  24771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24772. EXPECT_EQ(0, s.proxy_hits());
  24773. EXPECT_EQ(1, s.target_hits());
  24774. }
  24775. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24776. ProxyAndTargetServers s;
  24777. Client cli("127.0.0.1", s.target_port());
  24778. cli.set_proxy("127.0.0.1", s.proxy_port());
  24779. cli.set_no_proxy({"127.0.0.0/33"});
  24780. auto res = cli.Get("/");
  24781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24782. EXPECT_GE(s.proxy_hits(), 1);
  24783. EXPECT_EQ(0, s.target_hits());
  24784. }
  24785. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24786. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24787. ProxyAndTargetServers s;
  24788. Client cli("127.0.0.1", s.target_port());
  24789. cli.set_proxy("127.0.0.1", s.proxy_port());
  24790. cli.set_no_proxy({"127.0.0.1/"});
  24791. auto res = cli.Get("/");
  24792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24793. EXPECT_GE(s.proxy_hits(), 1);
  24794. EXPECT_EQ(0, s.target_hits());
  24795. }
  24796. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24797. ProxyAndTargetServers s;
  24798. auto cli = make_client("internal.corp", s);
  24799. cli->set_proxy_basic_auth("u", "p");
  24800. cli->set_no_proxy({"internal.corp"});
  24801. auto res = cli->Get("/");
  24802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24803. EXPECT_EQ(1, s.target_hits());
  24804. EXPECT_EQ(0, s.proxy_hits());
  24805. EXPECT_FALSE(s.last_had_proxy_authz())
  24806. << "Proxy-Authorization must not be sent direct to the target";
  24807. }
  24808. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24809. ProxyAndTargetServers s;
  24810. auto cli = make_client("public.example", s);
  24811. cli->set_proxy_basic_auth("u", "p");
  24812. cli->set_no_proxy({"internal.corp"}); // does not match
  24813. auto res = cli->Get("/");
  24814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24815. EXPECT_GE(s.proxy_hits(), 1);
  24816. EXPECT_TRUE(s.last_had_proxy_authz());
  24817. }
  24818. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24819. std::atomic<int> hits{0};
  24820. std::atomic<int> hits_with_authz{0};
  24821. no_proxy_test::ScopedServer proxy_mock;
  24822. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24823. hits++;
  24824. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24825. if (req.target.find("/redir") != std::string::npos) {
  24826. res.set_redirect("http://other.example/landed");
  24827. } else {
  24828. res.set_content("via-proxy", "text/plain");
  24829. }
  24830. });
  24831. proxy_mock.listen();
  24832. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24833. hits = 0;
  24834. hits_with_authz = 0;
  24835. Client cli("public.example", 80);
  24836. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24837. cli.set_proxy_basic_auth(c.first, c.second);
  24838. cli.set_follow_location(true);
  24839. // The redirect to another host goes through the proxy as well
  24840. auto res = cli.Get("/redir");
  24841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24842. EXPECT_EQ(2, hits.load());
  24843. EXPECT_EQ(2, hits_with_authz.load());
  24844. }
  24845. }
  24846. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24847. ProxyAndTargetServers s;
  24848. auto cli = make_client("anything.test", s);
  24849. auto res = cli->Get("/");
  24850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24851. EXPECT_GE(s.proxy_hits(), 1);
  24852. EXPECT_EQ(0, s.target_hits());
  24853. }
  24854. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24855. ProxyAndTargetServers s;
  24856. auto cli = make_client("example.com", s);
  24857. cli->set_no_proxy({"example.com:8080"});
  24858. auto res = cli->Get("/");
  24859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24860. EXPECT_GE(s.proxy_hits(), 1);
  24861. EXPECT_EQ(0, s.target_hits());
  24862. }
  24863. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24864. ProxyAndTargetServers s;
  24865. auto cli = make_client("anything.test", s);
  24866. cli->set_no_proxy({"", " ", "\t"});
  24867. auto res = cli->Get("/");
  24868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24869. EXPECT_GE(s.proxy_hits(), 1);
  24870. EXPECT_EQ(0, s.target_hits());
  24871. }
  24872. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24873. // An entry with leading/trailing whitespace must still match — env-style
  24874. // values are commonly pasted with stray spaces and an implementation
  24875. // that feeds the raw token directly to inet_pton would fail to match
  24876. // valid CIDRs because of the spaces.
  24877. ProxyAndTargetServers s;
  24878. Client cli("127.0.0.1", s.target_port());
  24879. cli.set_proxy("127.0.0.1", s.proxy_port());
  24880. cli.set_no_proxy({" 127.0.0.0/8 "});
  24881. auto res = cli.Get("/");
  24882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24883. EXPECT_EQ(0, s.proxy_hits());
  24884. EXPECT_EQ(1, s.target_hits());
  24885. }
  24886. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24887. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24888. // go direct and must NOT carry Proxy-Authorization.
  24889. std::atomic<int> proxy_hits{0};
  24890. std::atomic<int> target_hits{0};
  24891. std::atomic<bool> target_saw_authz{false};
  24892. no_proxy_test::ScopedServer proxy_mock, target;
  24893. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24894. proxy_hits++;
  24895. res.status = 302;
  24896. res.set_header("Location", "http://127.0.0.1:" +
  24897. std::to_string(target.port()) + "/landed");
  24898. });
  24899. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24900. target_hits++;
  24901. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24902. res.set_content("direct", "text/plain");
  24903. });
  24904. proxy_mock.listen();
  24905. target.listen();
  24906. Client cli("public.example", target.port());
  24907. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24908. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24909. cli.set_proxy_basic_auth("u", "p");
  24910. cli.set_no_proxy({"127.0.0.1"});
  24911. cli.set_follow_location(true);
  24912. auto res = cli.Get("/redir");
  24913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24914. EXPECT_GE(proxy_hits.load(), 1);
  24915. EXPECT_GE(target_hits.load(), 1);
  24916. EXPECT_FALSE(target_saw_authz.load());
  24917. }
  24918. #ifdef CPPHTTPLIB_SSL_ENABLED
  24919. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24920. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24921. // proxy creds would be sent to the (possibly hostile) origin.
  24922. std::atomic<int> target_hits{0};
  24923. std::atomic<bool> target_saw_proxy_authz{false};
  24924. no_proxy_test::ScopedServer target;
  24925. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24926. target_hits++;
  24927. if (req.has_header("Proxy-Authorization")) {
  24928. target_saw_proxy_authz = true;
  24929. }
  24930. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24931. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24932. "nonce=\"abc\", algorithm=MD5");
  24933. });
  24934. target.listen();
  24935. // The proxy address is set to the target's port: the bypass MUST kick in;
  24936. // if it doesn't, the test still routes "via proxy" to the same server and
  24937. // the Proxy-Authorization assertion below catches the leak.
  24938. Client cli("evil.example", target.port());
  24939. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24940. cli.set_proxy("127.0.0.1", target.port());
  24941. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24942. cli.set_no_proxy({"evil.example"});
  24943. auto res = cli.Get("/x");
  24944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24945. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24946. EXPECT_EQ(1, target_hits.load());
  24947. EXPECT_FALSE(target_saw_proxy_authz.load());
  24948. }
  24949. #endif
  24950. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24951. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24952. std::atomic<int> proxy_hits{0};
  24953. std::atomic<int> bypass_hits{0};
  24954. std::atomic<bool> proxy_saw_c_url{false};
  24955. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24956. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24957. proxy_hits++;
  24958. if (req.path.find("/start") != std::string::npos) {
  24959. res.status = 302;
  24960. res.set_header("Location", "http://127.0.0.1:" +
  24961. std::to_string(bypass_server.port()) +
  24962. "/middle");
  24963. return;
  24964. }
  24965. if (req.path.find("/end") != std::string::npos) {
  24966. proxy_saw_c_url = true;
  24967. res.set_content("c-via-proxy", "text/plain");
  24968. return;
  24969. }
  24970. res.set_content("unexpected", "text/plain");
  24971. });
  24972. // public.example's "advertised" port is arbitrary (the request never lands
  24973. // there — it goes through the proxy), but use a dynamic value to stay
  24974. // friendly with sharded parallel runs.
  24975. int public_port = bypass_server.port();
  24976. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24977. bypass_hits++;
  24978. res.status = 302;
  24979. res.set_header("Location", "http://public.example:" +
  24980. std::to_string(public_port) + "/end");
  24981. });
  24982. proxy_mock.listen();
  24983. bypass_server.listen();
  24984. Client cli("public.example", public_port);
  24985. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24986. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24987. cli.set_no_proxy({"127.0.0.1"});
  24988. cli.set_follow_location(true);
  24989. auto res = cli.Get("/start");
  24990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24991. EXPECT_EQ(StatusCode::OK_200, res->status);
  24992. EXPECT_EQ("c-via-proxy", res->body);
  24993. EXPECT_GE(proxy_hits.load(), 2);
  24994. EXPECT_GE(bypass_hits.load(), 1);
  24995. EXPECT_TRUE(proxy_saw_c_url.load());
  24996. }
  24997. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24998. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24999. // request reconnects to the correct endpoint.
  25000. std::atomic<int> proxy_hits{0};
  25001. std::atomic<int> target_hits{0};
  25002. no_proxy_test::ScopedServer proxy_mock, target;
  25003. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25004. proxy_hits++;
  25005. res.set_content("via-proxy", "text/plain");
  25006. });
  25007. target.svr().Get(".*", [&](const Request &, Response &res) {
  25008. target_hits++;
  25009. res.set_content("direct", "text/plain");
  25010. });
  25011. proxy_mock.listen();
  25012. target.listen();
  25013. Client cli("public.example", target.port());
  25014. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25015. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25016. cli.set_keep_alive(true);
  25017. auto res1 = cli.Get("/a");
  25018. ASSERT_TRUE(res1);
  25019. EXPECT_EQ("via-proxy", res1->body);
  25020. EXPECT_EQ(1, proxy_hits.load());
  25021. EXPECT_EQ(0, target_hits.load());
  25022. cli.set_no_proxy({"public.example"});
  25023. auto res2 = cli.Get("/b");
  25024. ASSERT_TRUE(res2);
  25025. EXPECT_EQ("direct", res2->body);
  25026. EXPECT_EQ(1, proxy_hits.load());
  25027. EXPECT_EQ(1, target_hits.load());
  25028. }
  25029. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  25030. namespace proxy_tunnel_test {
  25031. // SSLServer counterpart to no_proxy_test::ScopedServer.
  25032. class ScopedSSLServer {
  25033. public:
  25034. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  25035. port_ = svr_.bind_to_any_port("127.0.0.1");
  25036. }
  25037. ~ScopedSSLServer() {
  25038. svr_.stop();
  25039. if (th_.joinable()) { th_.join(); }
  25040. }
  25041. SSLServer &svr() { return svr_; }
  25042. int port() const { return port_; }
  25043. void listen() {
  25044. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25045. svr_.wait_until_ready();
  25046. }
  25047. private:
  25048. SSLServer svr_;
  25049. std::thread th_;
  25050. int port_ = 0;
  25051. };
  25052. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  25053. class ScopedConnectProxy {
  25054. public:
  25055. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  25056. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25057. if (listen_fd_ < 0) { return; }
  25058. int yes = 1;
  25059. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  25060. sockaddr_in a{};
  25061. a.sin_family = AF_INET;
  25062. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25063. a.sin_port = 0;
  25064. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  25065. return;
  25066. }
  25067. socklen_t alen = sizeof(a);
  25068. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  25069. 0) {
  25070. return;
  25071. }
  25072. port_ = ntohs(a.sin_port);
  25073. if (::listen(listen_fd_, 1) != 0) { return; }
  25074. th_ = std::thread([this] { run(); });
  25075. }
  25076. ~ScopedConnectProxy() {
  25077. stop_ = true;
  25078. if (listen_fd_ >= 0) {
  25079. ::shutdown(listen_fd_, SHUT_RDWR);
  25080. ::close(listen_fd_);
  25081. }
  25082. if (th_.joinable()) { th_.join(); }
  25083. }
  25084. int port() const { return port_; }
  25085. int connect_hits() const { return connect_hits_.load(); }
  25086. // Head of the last CONNECT request, as the proxy saw it on the wire.
  25087. std::string connect_request() const {
  25088. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25089. return connect_request_;
  25090. }
  25091. private:
  25092. void run() {
  25093. while (!stop_.load()) {
  25094. fd_set rfds;
  25095. FD_ZERO(&rfds);
  25096. FD_SET(listen_fd_, &rfds);
  25097. timeval tv{0, 100 * 1000};
  25098. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  25099. if (sel <= 0) { continue; }
  25100. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  25101. if (client_fd < 0) { continue; }
  25102. std::string req;
  25103. char buf[2048];
  25104. while (req.find("\r\n\r\n") == std::string::npos) {
  25105. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  25106. if (n <= 0) { break; }
  25107. req.append(buf, static_cast<size_t>(n));
  25108. }
  25109. if (req.compare(0, 7, "CONNECT") != 0) {
  25110. ::close(client_fd);
  25111. continue;
  25112. }
  25113. connect_hits_++;
  25114. {
  25115. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25116. connect_request_ = req;
  25117. }
  25118. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  25119. ::send(client_fd, ok, std::strlen(ok), 0);
  25120. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  25121. sockaddr_in o{};
  25122. o.sin_family = AF_INET;
  25123. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25124. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  25125. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  25126. 0) {
  25127. ::close(client_fd);
  25128. ::close(origin_fd);
  25129. continue;
  25130. }
  25131. auto forward = [](int from, int to) {
  25132. char b[8192];
  25133. for (;;) {
  25134. ssize_t n = ::recv(from, b, sizeof(b), 0);
  25135. if (n <= 0) { break; }
  25136. ssize_t off = 0;
  25137. while (off < n) {
  25138. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  25139. if (s <= 0) {
  25140. off = n;
  25141. break;
  25142. }
  25143. off += s;
  25144. }
  25145. }
  25146. ::shutdown(to, SHUT_WR);
  25147. };
  25148. std::thread t1([&] { forward(client_fd, origin_fd); });
  25149. std::thread t2([&] { forward(origin_fd, client_fd); });
  25150. t1.join();
  25151. t2.join();
  25152. ::close(client_fd);
  25153. ::close(origin_fd);
  25154. }
  25155. }
  25156. int forward_port_ = -1;
  25157. int listen_fd_ = -1;
  25158. int port_ = 0;
  25159. std::thread th_;
  25160. std::atomic<bool> stop_{false};
  25161. std::atomic<int> connect_hits_{0};
  25162. mutable std::mutex connect_request_mutex_;
  25163. std::string connect_request_;
  25164. };
  25165. // Sends one request through the CONNECT proxy to the TLS origin with a
  25166. // credential configured for each hop, and checks that each credential reaches
  25167. // only the hop it was configured for: the proxy's on the CONNECT request, the
  25168. // origin's (every header in origin_headers) on the tunnelled request.
  25169. void CredentialsStayWithTheirHop(
  25170. const std::function<void(SSLClient &)> &set_credentials,
  25171. const std::string &scheme,
  25172. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  25173. std::atomic<int> origin_hits{0};
  25174. std::atomic<bool> origin_saw_proxy_authz{false};
  25175. std::atomic<bool> origin_saw_headers{false};
  25176. ScopedSSLServer origin;
  25177. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25178. origin_hits++;
  25179. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  25180. origin_saw_headers =
  25181. std::all_of(origin_headers.begin(), origin_headers.end(),
  25182. [&](const std::string &h) { return req.has_header(h); });
  25183. res.set_content("ok", "text/plain");
  25184. });
  25185. origin.listen();
  25186. ScopedConnectProxy proxy(origin.port());
  25187. ASSERT_NE(0, proxy.port());
  25188. // Pinned to 127.0.0.1 for the same reason as the test below.
  25189. SSLClient cli("127.0.0.1", origin.port());
  25190. cli.enable_server_certificate_verification(false);
  25191. cli.set_proxy("127.0.0.1", proxy.port());
  25192. set_credentials(cli);
  25193. auto res = cli.Get("/x");
  25194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25195. EXPECT_EQ(StatusCode::OK_200, res->status);
  25196. EXPECT_EQ(1, origin_hits.load());
  25197. EXPECT_EQ(1, proxy.connect_hits());
  25198. EXPECT_TRUE(origin_saw_headers.load());
  25199. EXPECT_FALSE(origin_saw_proxy_authz.load())
  25200. << "Proxy-Authorization must not be sent inside the tunnel";
  25201. auto connect_req = proxy.connect_request();
  25202. EXPECT_NE(std::string::npos,
  25203. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  25204. for (const auto &h : origin_headers) {
  25205. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  25206. << h << " must not be sent to the proxy on CONNECT";
  25207. }
  25208. }
  25209. } // namespace proxy_tunnel_test
  25210. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  25211. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25212. [](SSLClient &cli) {
  25213. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25214. cli.set_basic_auth("origin-user", "origin-pass");
  25215. },
  25216. "Basic");
  25217. }
  25218. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  25219. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25220. [](SSLClient &cli) {
  25221. cli.set_proxy_bearer_token_auth("proxy-token");
  25222. cli.set_bearer_token_auth("origin-token");
  25223. },
  25224. "Bearer");
  25225. }
  25226. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  25227. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25228. [](SSLClient &cli) {
  25229. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25230. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  25231. {"Cookie", "sid=origin-session"},
  25232. {"X-Api-Key", "origin-key"}});
  25233. },
  25234. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  25235. }
  25236. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  25237. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  25238. // retry; otherwise proxy creds would be sent to the origin.
  25239. std::atomic<int> origin_hits{0};
  25240. std::atomic<bool> origin_saw_proxy_authz{false};
  25241. proxy_tunnel_test::ScopedSSLServer origin;
  25242. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25243. origin_hits++;
  25244. if (req.has_header("Proxy-Authorization")) {
  25245. origin_saw_proxy_authz = true;
  25246. }
  25247. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25248. res.set_header("Proxy-Authenticate",
  25249. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  25250. "algorithm=MD5");
  25251. });
  25252. origin.listen();
  25253. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25254. ASSERT_NE(0, proxy.port());
  25255. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  25256. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  25257. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  25258. // and answer with its own status, making this test flaky.
  25259. SSLClient cli("127.0.0.1", origin.port());
  25260. cli.enable_server_certificate_verification(false);
  25261. cli.set_proxy("127.0.0.1", proxy.port());
  25262. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25263. auto res = cli.Get("/x");
  25264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25265. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25266. EXPECT_EQ(1, origin_hits.load());
  25267. EXPECT_FALSE(origin_saw_proxy_authz.load());
  25268. EXPECT_EQ(1, proxy.connect_hits());
  25269. }
  25270. #endif