1
0

test.cc 949 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228
  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 definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  396. // neighbours)
  397. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  398. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  399. }
  400. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  401. // A sign or whitespace inside the two-character escape window must not be
  402. // accepted as a valid percent-encoding; the sequence is passed through
  403. // literally, matching decode_uri_component / decode_path_component.
  404. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  405. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  406. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  407. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  408. // Well-formed escapes still decode.
  409. EXPECT_EQ("-", decode_query_component("%2D", false));
  410. EXPECT_EQ("A", decode_query_component("%41", false));
  411. }
  412. TEST(SanitizeFilenameTest, VariousPatterns) {
  413. // Path traversal
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  416. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  417. // Normal and edge cases
  418. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  419. EXPECT_EQ("filename.txt",
  420. httplib::sanitize_filename("/path/to/filename.txt"));
  421. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  422. EXPECT_EQ("", httplib::sanitize_filename(".."));
  423. EXPECT_EQ("", httplib::sanitize_filename(""));
  424. // Null bytes stripped
  425. EXPECT_EQ("safe.txt",
  426. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  427. // Whitespace-only rejected
  428. EXPECT_EQ("", httplib::sanitize_filename(" "));
  429. }
  430. // Forward declaration (see the base64_encode note below): split builds move the
  431. // definition into httplib.cc, so re-declaring it here lets the test link.
  432. namespace httplib {
  433. namespace detail {
  434. bool is_chunked_transfer_encoding(const Headers &headers);
  435. } // namespace detail
  436. } // namespace httplib
  437. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  438. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  439. auto make = [](std::initializer_list<const char *> lines) {
  440. Headers h;
  441. for (auto te : lines) {
  442. if (te) { h.emplace("Transfer-Encoding", te); }
  443. }
  444. return h;
  445. };
  446. // Sole coding, matched case-insensitively.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  450. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  454. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  459. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  460. // were received, into one list. Headers preserves that order, so the answer
  461. // is decided by the last coding of the last line and the order the lines
  462. // arrived in is significant.
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  466. // The split can fall anywhere in the list.
  467. EXPECT_TRUE(
  468. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  469. EXPECT_FALSE(
  470. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  471. // A trailing line naming no coding leaves the list ending in nothing, so it
  472. // must not inherit the chunked from the line before it.
  473. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  474. }
  475. // Forward declarations (see the base64_encode note below).
  476. namespace httplib {
  477. namespace detail {
  478. bool parse_status_line(const char *line, std::string &version, int &status,
  479. std::string &reason);
  480. std::string file_extension(const std::string &path);
  481. std::string
  482. find_content_type(const std::string &path,
  483. const std::map<std::string, std::string> &user_data,
  484. const std::string &default_content_type);
  485. bool can_compress_content_type(const std::string &content_type);
  486. bool is_prohibited_header_name(const std::string &name);
  487. #ifdef CPPHTTPLIB_SSL_ENABLED
  488. bool match_hostname(const std::string &pattern, const std::string &hostname);
  489. #endif
  490. } // namespace detail
  491. } // namespace httplib
  492. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  493. struct {
  494. const char *line;
  495. const char *version;
  496. int status;
  497. const char *reason;
  498. } cases[] = {
  499. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  500. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  501. // The reason phrase may be empty, or left out along with its space.
  502. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  503. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  504. };
  505. for (const auto &c : cases) {
  506. std::string version;
  507. int status = 0;
  508. std::string reason = "unset";
  509. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  510. << c.line;
  511. EXPECT_EQ(c.version, version);
  512. EXPECT_EQ(c.status, status);
  513. EXPECT_EQ(c.reason, reason);
  514. }
  515. }
  516. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  517. const char *lines[] = {
  518. "HTTP/2 200 OK\r\n",
  519. "HTTP/1.2 200 OK\r\n",
  520. "HTTP/1.1 20 OK\r\n",
  521. "HTTP/1.1 2000 OK\r\n",
  522. "HTTP/1.1 2x0 OK\r\n",
  523. "HTTP/1.1 200 OK\r\n",
  524. "HTTP/1.1 200OK\r\n",
  525. "HTTP/1.1 200 O\rK\r\n",
  526. "HTTP/1.1 200 OK",
  527. "HTTP/1.1 200 OK\r\nX",
  528. "",
  529. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  530. "HTTP/1.1 200 OK\n",
  531. #endif
  532. };
  533. for (auto line : lines) {
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  538. << line;
  539. }
  540. }
  541. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  542. // Long enough to overflow the stack when matched with std::regex.
  543. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  544. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  545. std::string version;
  546. int status = 0;
  547. std::string reason;
  548. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  549. EXPECT_EQ(200, status);
  550. EXPECT_EQ(long_reason, reason);
  551. }
  552. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  553. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  554. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  555. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  556. EXPECT_EQ("", detail::file_extension("noext"));
  557. EXPECT_EQ("", detail::file_extension("a."));
  558. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  559. EXPECT_EQ("", detail::file_extension("a.b-c"));
  560. // Long enough to overflow the stack when matched with std::regex.
  561. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  562. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  563. }
  564. #ifdef CPPHTTPLIB_SSL_ENABLED
  565. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  566. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  567. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  569. // A wildcard needs two labels after it, in the leftmost label only
  570. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  571. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  572. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  573. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  574. EXPECT_FALSE(
  575. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  576. // No name may have an empty label
  577. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  578. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  579. }
  580. #endif
  581. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  582. detail::case_ignore::hash hash;
  583. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  584. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  585. // Long enough to overflow the stack if hashed one call per character.
  586. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  587. }
  588. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  589. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  590. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  591. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  592. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  593. // Same 26-bit hash as html, svg and js.
  594. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  595. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  597. }
  598. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  599. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  600. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  601. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  602. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  603. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  604. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  605. // Same 26-bit hash as application/json.
  606. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  607. }
  608. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  609. Request req;
  610. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  611. EXPECT_TRUE(req.is_multipart_form_data());
  612. std::string boundary;
  613. EXPECT_TRUE(detail::parse_multipart_boundary(
  614. req.get_header_value("Content-Type"), boundary));
  615. EXPECT_EQ("x", boundary);
  616. }
  617. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  618. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  619. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  620. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  621. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  622. // Same 26-bit hash as REMOTE_ADDR.
  623. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  624. }
  625. // Forward declaration: in split builds split.py strips `inline` and moves the
  626. // definition into httplib.cc, so detail::base64_encode is not visible from the
  627. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  628. // in both header-only and split builds.
  629. namespace httplib {
  630. namespace detail {
  631. std::string base64_encode(const std::string &in);
  632. } // namespace detail
  633. } // namespace httplib
  634. TEST(Base64EncodeTest, KnownAnswers) {
  635. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  636. // where the accumulator's top bit is already set before the next shift.
  637. EXPECT_EQ("", detail::base64_encode(""));
  638. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  639. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  640. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  641. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  642. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  643. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  644. // High bytes keep the top bit set across several rounds.
  645. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  646. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  647. }
  648. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  649. string unescapedCharacters = "-_.!~*'()";
  650. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  651. }
  652. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  653. string reservedCharacters = ";,/?:@&=+$";
  654. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  655. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  656. }
  657. TEST(ClientQueryOrder, PreserveOrder) {
  658. // This test reproduces Issue #2259: client may reorder query parameters
  659. // when sending a GET request. The expected behavior is that the client
  660. // preserves the original query string order when the caller supplied it
  661. // as part of the path.
  662. Server svr;
  663. svr.Get("/", [&](const Request &req, Response &res) {
  664. // Echo back the raw target so the test can assert ordering
  665. res.set_content(req.target, "text/plain");
  666. });
  667. std::thread t{[&] { svr.listen(HOST, PORT); }};
  668. auto se = detail::scope_exit([&] {
  669. svr.stop();
  670. t.join();
  671. ASSERT_FALSE(svr.is_running());
  672. });
  673. svr.wait_until_ready();
  674. Client cli(HOST, PORT);
  675. ASSERT_TRUE(cli.is_valid());
  676. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  677. auto res = cli.Get(original);
  678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  679. // Expect the echoed target to exactly match the original path (order
  680. // preserved)
  681. EXPECT_EQ(res->body, original);
  682. }
  683. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  684. string chineseCharacters = U8("中国語");
  685. string russianCharacters = U8("дом");
  686. string brazilianCharacters = U8("óculos");
  687. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  688. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  689. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  690. "%D0%B4%D0%BE%D0%BC");
  691. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  692. }
  693. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  694. string unescapedCharacters = "-_.!~*'()";
  695. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  696. }
  697. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  698. string reservedCharacters = ";,/?:@&=+$";
  699. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  700. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  701. }
  702. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  703. string chineseCharacters = U8("中国語");
  704. string russianCharacters = U8("дом");
  705. string brazilianCharacters = U8("óculos");
  706. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  707. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  708. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  709. "%D0%B4%D0%BE%D0%BC");
  710. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  711. }
  712. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  713. // Issue #2082 use case: encoding path component with ampersand
  714. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  715. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  716. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  717. }
  718. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  723. string reservedCharacters = ";,/?:@&=+$#";
  724. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  725. }
  726. TEST(EncodeUriTest, TestUTF8Characters) {
  727. string chineseCharacters = U8("中国語");
  728. string russianCharacters = U8("дом");
  729. string brazilianCharacters = U8("óculos");
  730. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  731. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  732. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  733. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  734. }
  735. TEST(EncodeUriTest, TestCompleteUri) {
  736. string uri =
  737. "https://example.com/path/to/resource?query=value&param=test#fragment";
  738. EXPECT_EQ(
  739. httplib::encode_uri(uri),
  740. "https://example.com/path/to/resource?query=value&param=test#fragment");
  741. }
  742. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  743. string uri =
  744. "https://example.com/path with spaces/file name.html?q=hello world";
  745. EXPECT_EQ(httplib::encode_uri(uri),
  746. "https://example.com/path%20with%20spaces/"
  747. "file%20name.html?q=hello%20world");
  748. }
  749. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  750. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  751. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  752. }
  753. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  754. string unescapedCharacters = "-_.!~*'()";
  755. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  756. }
  757. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  758. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  759. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  760. string encodedBrazilian = "%C3%B3culos";
  761. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  762. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  763. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  764. }
  765. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  766. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  767. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  768. "Piri Tommy Villiers - on & on");
  769. }
  770. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  771. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  772. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  773. }
  774. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  775. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  776. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  777. }
  778. TEST(DecodeUriTest, TestUTF8Characters) {
  779. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  780. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  781. string encodedBrazilian = "%C3%B3culos";
  782. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  783. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  784. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  785. }
  786. TEST(DecodeUriTest, TestCompleteUri) {
  787. string encodedUri = "https://example.com/path%20with%20spaces/"
  788. "file%20name.html?q=hello%20world";
  789. EXPECT_EQ(
  790. httplib::decode_uri(encodedUri),
  791. "https://example.com/path with spaces/file name.html?q=hello world");
  792. }
  793. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  794. string original =
  795. "https://example.com/path with spaces/file name.html?q=hello world";
  796. string encoded = httplib::encode_uri(original);
  797. string decoded = httplib::decode_uri(encoded);
  798. EXPECT_EQ(decoded, original);
  799. }
  800. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  801. // decode_uri is the inverse of encode_uri: an escaped reserved character
  802. // stays encoded so it is not promoted into a real delimiter, while
  803. // non-reserved escapes still decode (like JS decodeURI).
  804. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  805. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  806. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  807. "%3F%3A%40%26%3D%2B%24%2C%3B");
  808. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  809. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  810. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  811. "http://example.com/a%2Fb");
  812. // decode_uri_component still decodes the reserved character.
  813. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  814. }
  815. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  816. string original = "Piri Tommy Villiers - on & on";
  817. string encoded = httplib::encode_uri_component(original);
  818. string decoded = httplib::decode_uri_component(encoded);
  819. EXPECT_EQ(decoded, original);
  820. }
  821. TEST(TrimTests, TrimStringTests) {
  822. EXPECT_EQ("abc", detail::trim_copy("abc"));
  823. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  824. EXPECT_TRUE(detail::trim_copy("").empty());
  825. }
  826. TEST(AsciiTest, LocaleIndependentClassification) {
  827. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  828. // which consult the global C locale: std::isalnum(0xC5) can return true
  829. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  830. // helpers must classify every byte by the ASCII grammar alone.
  831. for (int i = 0; i < 256; i++) {
  832. auto c = static_cast<char>(i);
  833. auto is_digit = i >= '0' && i <= '9';
  834. auto is_upper = i >= 'A' && i <= 'Z';
  835. auto is_lower = i >= 'a' && i <= 'z';
  836. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  837. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  838. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  839. << "byte " << i;
  840. }
  841. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  842. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  843. // Non-ASCII bytes must be percent-encoded, never passed through as
  844. // alphanumeric.
  845. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  846. }
  847. TEST(FromCharsTest, Double) {
  848. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  849. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  850. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  851. auto parse = [](const std::string &s, double &v) {
  852. return detail::from_chars(s.data(), s.data() + s.size(), v);
  853. };
  854. double v = -1.0;
  855. // Representative quality values.
  856. EXPECT_EQ(parse("0", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 0.0);
  858. EXPECT_EQ(parse("1", v).ec, std::errc{});
  859. EXPECT_DOUBLE_EQ(v, 1.0);
  860. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.8);
  862. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 0.001);
  864. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 1.0);
  866. // A missing integer or fractional part is tolerated.
  867. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 0.5);
  869. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  870. EXPECT_DOUBLE_EQ(v, 5.0);
  871. // Values outside [0, 1] still parse; the caller range-checks them.
  872. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 123.456);
  874. // Stops at the first byte that is not part of the number and reports where.
  875. std::string trailing = "0.9, text/html";
  876. auto r = parse(trailing, v);
  877. EXPECT_EQ(r.ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.9);
  879. EXPECT_EQ(*r.ptr, ',');
  880. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  881. // outright, and an 'e'/'E' simply ends the number.
  882. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  883. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  884. std::string exp_input = "1.5e3";
  885. r = parse(exp_input, v);
  886. EXPECT_EQ(r.ec, std::errc{});
  887. EXPECT_DOUBLE_EQ(v, 1.5);
  888. EXPECT_EQ(*r.ptr, 'e');
  889. // Invalid inputs.
  890. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  891. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  892. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  895. // Pathological but well-formed inputs must stay bounded (no overflow, no
  896. // out-of-bounds table access) and stay within [0, 1] for the caller.
  897. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  898. std::errc{});
  899. EXPECT_DOUBLE_EQ(v, 0.0);
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  901. std::errc{});
  902. EXPECT_GE(v, 0.0);
  903. EXPECT_LE(v, 1.0);
  904. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  905. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  906. }
  907. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  908. // Simple case without quality values
  909. std::vector<std::string> result1;
  910. EXPECT_TRUE(detail::parse_accept_header(
  911. "text/html,application/json,text/plain", result1));
  912. EXPECT_EQ(result1.size(), 3U);
  913. EXPECT_EQ(result1[0], "text/html");
  914. EXPECT_EQ(result1[1], "application/json");
  915. EXPECT_EQ(result1[2], "text/plain");
  916. // With quality values
  917. std::vector<std::string> result2;
  918. EXPECT_TRUE(detail::parse_accept_header(
  919. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  920. EXPECT_EQ(result2.size(), 3U);
  921. EXPECT_EQ(result2[0], "application/json"); // highest q value
  922. EXPECT_EQ(result2[1], "text/html");
  923. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  924. }
  925. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  926. // Mixed with and without quality values
  927. std::vector<std::string> result;
  928. EXPECT_TRUE(detail::parse_accept_header(
  929. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  930. EXPECT_EQ(result.size(), 3U);
  931. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  932. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  933. EXPECT_EQ(result[2], "application/json"); // q=0.5
  934. }
  935. TEST(ParseAcceptHeaderTest, EdgeCases) {
  936. // Empty header
  937. std::vector<std::string> empty_result;
  938. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  939. EXPECT_TRUE(empty_result.empty());
  940. // Single type
  941. std::vector<std::string> single_result;
  942. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  943. EXPECT_EQ(single_result.size(), 1U);
  944. EXPECT_EQ(single_result[0], "application/json");
  945. // Wildcard types
  946. std::vector<std::string> wildcard_result;
  947. EXPECT_TRUE(detail::parse_accept_header(
  948. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  949. EXPECT_EQ(wildcard_result.size(), 3U);
  950. EXPECT_EQ(wildcard_result[0], "application/json");
  951. EXPECT_EQ(wildcard_result[1], "text/*");
  952. EXPECT_EQ(wildcard_result[2], "*/*");
  953. }
  954. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  955. // Common browser Accept header
  956. std::vector<std::string> browser_result;
  957. EXPECT_TRUE(
  958. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  959. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  960. browser_result));
  961. EXPECT_EQ(browser_result.size(), 6U);
  962. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  963. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  964. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  965. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  967. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  968. // API client header
  969. std::vector<std::string> api_result;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  972. api_result));
  973. EXPECT_EQ(api_result.size(), 3U);
  974. EXPECT_EQ(api_result[0], "application/json");
  975. EXPECT_EQ(api_result[1], "application/xml");
  976. EXPECT_EQ(api_result[2], "text/plain");
  977. }
  978. TEST(ParseAcceptHeaderTest, SpecialCases) {
  979. // Quality value with 3 decimal places
  980. std::vector<std::string> decimal_result;
  981. EXPECT_TRUE(detail::parse_accept_header(
  982. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  983. EXPECT_EQ(decimal_result.size(), 2U);
  984. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  985. EXPECT_EQ(decimal_result[1], "text/html");
  986. // Zero quality (should still be included but with lowest priority)
  987. std::vector<std::string> zero_q_result;
  988. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  989. zero_q_result));
  990. EXPECT_EQ(zero_q_result.size(), 2U);
  991. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  992. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  993. // No spaces around commas
  994. std::vector<std::string> no_space_result;
  995. EXPECT_TRUE(detail::parse_accept_header(
  996. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  997. no_space_result));
  998. EXPECT_EQ(no_space_result.size(), 3U);
  999. EXPECT_EQ(no_space_result[0], "text/html");
  1000. EXPECT_EQ(no_space_result[1], "application/json");
  1001. EXPECT_EQ(no_space_result[2], "text/plain");
  1002. }
  1003. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1004. // Quality values always use '.' as the decimal separator, so parsing must
  1005. // not depend on the process locale. An embedding application may have
  1006. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1007. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1008. std::string saved = cur ? cur : "C";
  1009. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1010. "fr_FR.UTF-8"};
  1011. bool switched = false;
  1012. for (const auto loc : comma_locales) {
  1013. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1014. std::localeconv()->decimal_point[0] == ',') {
  1015. switched = true;
  1016. break;
  1017. }
  1018. }
  1019. if (!switched) {
  1020. std::setlocale(LC_NUMERIC, saved.c_str());
  1021. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1022. }
  1023. // The higher-weighted type appears later in the list, so a correct parse
  1024. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1025. // sensitive parse reads both weights as 0 and leaves the original order.
  1026. std::vector<std::string> result;
  1027. EXPECT_TRUE(detail::parse_accept_header(
  1028. "application/json;q=0.1,text/html;q=0.9", result));
  1029. ASSERT_EQ(result.size(), 2U);
  1030. EXPECT_EQ(result[0], "text/html");
  1031. EXPECT_EQ(result[1], "application/json");
  1032. std::setlocale(LC_NUMERIC, saved.c_str());
  1033. }
  1034. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1035. std::vector<std::string> result;
  1036. // Invalid quality value (> 1.0)
  1037. EXPECT_FALSE(
  1038. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1039. // Invalid quality value (< 0.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1042. // Invalid quality value (not a number)
  1043. EXPECT_FALSE(detail::parse_accept_header(
  1044. "text/html;q=invalid,application/json", result));
  1045. // A valid numeric prefix does not make the entire quality value valid.
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=0.5junk,application/json", result));
  1048. // Empty quality value
  1049. EXPECT_FALSE(
  1050. detail::parse_accept_header("text/html;q=,application/json", result));
  1051. // Invalid media type format (no slash and not wildcard)
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("invalidtype,application/json", result));
  1054. // Valid cases should still work
  1055. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1056. EXPECT_EQ(result.size(), 1U);
  1057. EXPECT_EQ(result[0], "*/*");
  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("text/*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "text/*");
  1064. }
  1065. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1066. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1067. // and must not be answered with 400 Bad Request.
  1068. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1069. struct {
  1070. const char *value;
  1071. std::vector<std::string> expected;
  1072. } cases[] = {
  1073. {",application/json", {"application/json"}},
  1074. {"text/html,", {"text/html"}},
  1075. {"text/html,,*/*", {"text/html", "*/*"}},
  1076. // An empty element may be spelled with whitespace in it
  1077. {"text/html, , application/json", {"text/html", "application/json"}},
  1078. // Nothing but empty elements is an empty list, which means the same
  1079. // thing as no Accept header at all
  1080. {",,,", {}},
  1081. // Quality values still apply across ignored empty elements
  1082. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1083. };
  1084. for (const auto &c : cases) {
  1085. std::vector<std::string> result;
  1086. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1087. << "value: " << c.value;
  1088. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1089. }
  1090. // An invalid entry is still rejected when empty elements surround it
  1091. std::vector<std::string> result;
  1092. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1093. }
  1094. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1095. // or ';' inside one does not end the list element or the parameter. Section
  1096. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1097. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1098. struct {
  1099. const char *value;
  1100. std::vector<std::string> expected;
  1101. } cases[] = {
  1102. {"text/html;profile=\"a,b\",application/json",
  1103. {"text/html", "application/json"}},
  1104. // A "q=" inside a quoted value is not the weight
  1105. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1106. {"text/html", "application/json"}},
  1107. // The weight after a quoted value still applies
  1108. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1109. {"application/json", "text/html"}},
  1110. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1111. {"application/json", "text/html"}},
  1112. {"text/html;profile=\"a\\\"b\",application/json",
  1113. {"text/html", "application/json"}},
  1114. // An escaped backslash does not escape the '"' after it
  1115. {"text/html;profile=\"a\\\\\",application/json",
  1116. {"text/html", "application/json"}},
  1117. };
  1118. for (const auto &c : cases) {
  1119. std::vector<std::string> result;
  1120. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1121. << "value: " << c.value;
  1122. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1123. }
  1124. }
  1125. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1126. Server svr;
  1127. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1128. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1129. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1130. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1131. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1132. res.set_content("ok", "text/plain");
  1133. });
  1134. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1135. EXPECT_TRUE(false);
  1136. res.set_content("bad request", "text/plain");
  1137. });
  1138. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1139. auto se = detail::scope_exit([&] {
  1140. svr.stop();
  1141. listen_thread.join();
  1142. ASSERT_FALSE(svr.is_running());
  1143. });
  1144. svr.wait_until_ready();
  1145. Client cli("localhost", PORT);
  1146. {
  1147. auto res = cli.Get(
  1148. "/accept_ok",
  1149. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1151. EXPECT_EQ(StatusCode::OK_200, res->status);
  1152. }
  1153. {
  1154. auto res = cli.Get("/accept_bad_request",
  1155. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1157. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1158. }
  1159. }
  1160. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1161. Server svr;
  1162. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1163. res.set_content("ok", "text/plain");
  1164. });
  1165. std::atomic<int> start_count{0};
  1166. std::atomic<bool> running_when_called{false};
  1167. svr.set_start_handler([&]() {
  1168. running_when_called = svr.is_running();
  1169. start_count++;
  1170. });
  1171. auto port = svr.bind_to_any_port(HOST);
  1172. std::thread t([&]() { svr.listen_after_bind(); });
  1173. auto se = detail::scope_exit([&] {
  1174. svr.stop();
  1175. t.join();
  1176. ASSERT_FALSE(svr.is_running());
  1177. });
  1178. svr.wait_until_ready();
  1179. // A successful request proves the accept loop is running, which the start
  1180. // handler precedes; so by now the handler must have run exactly once.
  1181. Client cli(HOST, port);
  1182. cli.set_connection_timeout(std::chrono::seconds(5));
  1183. auto res = cli.Get("/");
  1184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1185. EXPECT_EQ(StatusCode::OK_200, res->status);
  1186. EXPECT_EQ(1, start_count.load());
  1187. EXPECT_TRUE(running_when_called.load());
  1188. }
  1189. TEST(DivideTest, DivideStringTests) {
  1190. auto divide = [](const std::string &str, char d) {
  1191. std::string lhs;
  1192. std::string rhs;
  1193. detail::divide(str, d,
  1194. [&](const char *lhs_data, std::size_t lhs_size,
  1195. const char *rhs_data, std::size_t rhs_size) {
  1196. lhs.assign(lhs_data, lhs_size);
  1197. rhs.assign(rhs_data, rhs_size);
  1198. });
  1199. return std::make_pair(std::move(lhs), std::move(rhs));
  1200. };
  1201. {
  1202. const auto res = divide("", '=');
  1203. EXPECT_EQ(res.first, "");
  1204. EXPECT_EQ(res.second, "");
  1205. }
  1206. {
  1207. const auto res = divide("=", '=');
  1208. EXPECT_EQ(res.first, "");
  1209. EXPECT_EQ(res.second, "");
  1210. }
  1211. {
  1212. const auto res = divide(" ", '=');
  1213. EXPECT_EQ(res.first, " ");
  1214. EXPECT_EQ(res.second, "");
  1215. }
  1216. {
  1217. const auto res = divide("a", '=');
  1218. EXPECT_EQ(res.first, "a");
  1219. EXPECT_EQ(res.second, "");
  1220. }
  1221. {
  1222. const auto res = divide("a=", '=');
  1223. EXPECT_EQ(res.first, "a");
  1224. EXPECT_EQ(res.second, "");
  1225. }
  1226. {
  1227. const auto res = divide("=b", '=');
  1228. EXPECT_EQ(res.first, "");
  1229. EXPECT_EQ(res.second, "b");
  1230. }
  1231. {
  1232. const auto res = divide("a=b", '=');
  1233. EXPECT_EQ(res.first, "a");
  1234. EXPECT_EQ(res.second, "b");
  1235. }
  1236. {
  1237. const auto res = divide("a=b=", '=');
  1238. EXPECT_EQ(res.first, "a");
  1239. EXPECT_EQ(res.second, "b=");
  1240. }
  1241. {
  1242. const auto res = divide("a=b=c", '=');
  1243. EXPECT_EQ(res.first, "a");
  1244. EXPECT_EQ(res.second, "b=c");
  1245. }
  1246. }
  1247. TEST(SplitTest, ParseQueryString) {
  1248. string s = "key1=val1&key2=val2&key3=val3";
  1249. Params dic;
  1250. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1251. [&](const char *b, const char *e) {
  1252. string key, val;
  1253. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1254. if (key.empty()) {
  1255. key.assign(b2, e2);
  1256. } else {
  1257. val.assign(b2, e2);
  1258. }
  1259. });
  1260. dic.emplace(key, val);
  1261. });
  1262. EXPECT_EQ("val1", dic.find("key1")->second);
  1263. EXPECT_EQ("val2", dic.find("key2")->second);
  1264. EXPECT_EQ("val3", dic.find("key3")->second);
  1265. }
  1266. TEST(SplitTest, ParseInvalidQueryTests) {
  1267. {
  1268. string s = " ";
  1269. Params dict;
  1270. detail::parse_query_text(s, dict);
  1271. EXPECT_TRUE(dict.empty());
  1272. }
  1273. {
  1274. string s = " = =";
  1275. Params dict;
  1276. detail::parse_query_text(s, dict);
  1277. EXPECT_TRUE(dict.empty());
  1278. }
  1279. }
  1280. TEST(ParseQueryTest, ParseQueryString) {
  1281. {
  1282. std::string s = "key1=val1&key2=val2&key3=val3";
  1283. Params dic;
  1284. detail::parse_query_text(s, dic);
  1285. EXPECT_EQ("val1", dic.find("key1")->second);
  1286. EXPECT_EQ("val2", dic.find("key2")->second);
  1287. EXPECT_EQ("val3", dic.find("key3")->second);
  1288. }
  1289. {
  1290. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1291. Params dic;
  1292. detail::parse_query_text(s, dic);
  1293. EXPECT_EQ("", dic.find("key1")->second);
  1294. EXPECT_EQ("val1", dic.find("key2")->second);
  1295. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1296. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1297. }
  1298. }
  1299. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1300. Params dic;
  1301. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1302. dic.emplace("key1", "val1");
  1303. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1304. dic.emplace("key2", "val2");
  1305. dic.emplace("key3", "val3");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1307. }
  1308. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1309. Params params;
  1310. params.emplace("a", "1");
  1311. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1312. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1313. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1314. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1315. // Long enough to overflow the stack when matched with std::regex.
  1316. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1317. EXPECT_EQ("/p?" + long_query + "&a=1",
  1318. append_query_params("/p?" + long_query, params));
  1319. }
  1320. // Joins every entry of a Headers or Params into "key=value " so a whole
  1321. // traversal can be compared in one assertion. Both are instantiations of the
  1322. // same insertion-ordered container, so one helper serves both.
  1323. template <typename Map> static std::string entries_to_string(const Map &m) {
  1324. std::string s;
  1325. for (const auto &entry : m) {
  1326. s += entry.first + "=" + entry.second + " ";
  1327. }
  1328. return s;
  1329. }
  1330. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1331. // Params used to be a std::multimap, which sorted by name and handed the
  1332. // caller's query back alphabetised. A client signing its query string could
  1333. // not reproduce the order it asked for.
  1334. Params dic;
  1335. dic.emplace("zulu", "1");
  1336. dic.emplace("alpha", "2");
  1337. dic.emplace("mike", "3");
  1338. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1339. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1340. }
  1341. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1342. Params dic;
  1343. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1344. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1345. }
  1346. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1347. Request req;
  1348. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1349. req.params);
  1350. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1351. EXPECT_EQ("first", req.get_param_value("tag"));
  1352. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1353. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1354. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1355. EXPECT_EQ("", req.get_param_value("tag", 3));
  1356. }
  1357. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1358. // Params shares its container with Headers, which matches field names
  1359. // case-insensitively. Parameter names must not pick that up.
  1360. Params dic;
  1361. dic.emplace("Key", "upper");
  1362. dic.emplace("key", "lower");
  1363. EXPECT_EQ(2U, dic.size());
  1364. EXPECT_EQ(1U, dic.count("Key"));
  1365. EXPECT_EQ(1U, dic.count("key"));
  1366. EXPECT_EQ("upper", dic.find("Key")->second);
  1367. EXPECT_EQ("lower", dic.find("key")->second);
  1368. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1369. }
  1370. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1371. Server svr;
  1372. std::string order;
  1373. svr.Get("/order", [&](const Request &req, Response &res) {
  1374. order = entries_to_string(req.params);
  1375. res.set_content("ok", "text/plain");
  1376. });
  1377. auto port = svr.bind_to_any_port(HOST);
  1378. thread t = thread([&] { svr.listen_after_bind(); });
  1379. auto se = detail::scope_exit([&] {
  1380. svr.stop();
  1381. t.join();
  1382. ASSERT_FALSE(svr.is_running());
  1383. });
  1384. svr.wait_until_ready();
  1385. Client cli(HOST, port);
  1386. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1387. ASSERT_TRUE(res);
  1388. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1389. }
  1390. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1391. Server svr;
  1392. std::string field_order, file_order;
  1393. svr.Post("/order", [&](const Request &req, Response &res) {
  1394. for (const auto &field : req.form.fields) {
  1395. field_order += field.first + "=" + field.second.content + " ";
  1396. }
  1397. for (const auto &file : req.form.files) {
  1398. file_order += file.first + "=" + file.second.filename + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. UploadFormDataItems items = {
  1411. {"zulu", "1", "", ""},
  1412. {"alpha", "2", "", ""},
  1413. {"mike", "3", "", ""},
  1414. {"zebra", "z", "z.txt", "text/plain"},
  1415. {"apple", "a", "a.txt", "text/plain"},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/order", items);
  1419. ASSERT_TRUE(res);
  1420. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1421. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1422. }
  1423. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1424. Server svr;
  1425. std::vector<std::string> values;
  1426. std::string first, second, out_of_range, order;
  1427. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1428. values = req.form.get_fields("tag");
  1429. first = req.form.get_field("tag", 0);
  1430. second = req.form.get_field("tag", 1);
  1431. out_of_range = req.form.get_field("tag", 2);
  1432. for (const auto &field : req.form.fields) {
  1433. order += field.first + "=" + field.second.content + " ";
  1434. }
  1435. res.set_content("ok", "text/plain");
  1436. });
  1437. auto port = svr.bind_to_any_port(HOST);
  1438. thread t = thread([&] { svr.listen_after_bind(); });
  1439. auto se = detail::scope_exit([&] {
  1440. svr.stop();
  1441. t.join();
  1442. ASSERT_FALSE(svr.is_running());
  1443. });
  1444. svr.wait_until_ready();
  1445. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1446. // not adjacent in the container.
  1447. UploadFormDataItems items = {
  1448. {"tag", "first", "", ""},
  1449. {"other", "x", "", ""},
  1450. {"tag", "second", "", ""},
  1451. };
  1452. Client cli(HOST, port);
  1453. auto res = cli.Post("/repeated", items);
  1454. ASSERT_TRUE(res);
  1455. ASSERT_EQ(2U, values.size());
  1456. EXPECT_EQ("first", values[0]);
  1457. EXPECT_EQ("second", values[1]);
  1458. EXPECT_EQ("first", first);
  1459. EXPECT_EQ("second", second);
  1460. // std::multimap already kept entries sharing a name in insertion order, so
  1461. // everything above passes without this change too. The whole traversal is
  1462. // what tells the two apart: sorting by name would hoist "other" to the front
  1463. // and the two "tag" parts would end up adjacent.
  1464. EXPECT_EQ("tag=first other=x tag=second ", order);
  1465. // Advancing past the last entry of a name used to run off the container;
  1466. // the container's saturating increment makes it return the default instead.
  1467. EXPECT_EQ("", out_of_range);
  1468. }
  1469. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1470. // Server::read_content() keeps a FormFields::iterator alive across the
  1471. // content callbacks that fill the part it points at. The container is
  1472. // vector-backed, so a later emplace can reallocate and invalidate an older
  1473. // iterator; 64 parts grow the vector through seven reallocations, which
  1474. // checks that every part's content still lands in its own entry.
  1475. const size_t part_count = 64;
  1476. // One formula for both the parts sent and the values expected back, so the
  1477. // two cannot drift apart.
  1478. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1479. auto content_of = [](size_t i) {
  1480. return std::string(64, static_cast<char>('a' + (i % 26)));
  1481. };
  1482. Server svr;
  1483. std::vector<std::pair<std::string, std::string>> received;
  1484. svr.Post("/many", [&](const Request &req, Response &res) {
  1485. for (const auto &field : req.form.fields) {
  1486. received.emplace_back(field.first, field.second.content);
  1487. }
  1488. res.set_content("ok", "text/plain");
  1489. });
  1490. auto port = svr.bind_to_any_port(HOST);
  1491. thread t = thread([&] { svr.listen_after_bind(); });
  1492. auto se = detail::scope_exit([&] {
  1493. svr.stop();
  1494. t.join();
  1495. ASSERT_FALSE(svr.is_running());
  1496. });
  1497. svr.wait_until_ready();
  1498. UploadFormDataItems items;
  1499. for (size_t i = 0; i < part_count; i++) {
  1500. items.push_back({name_of(i), content_of(i), "", ""});
  1501. }
  1502. Client cli(HOST, port);
  1503. auto res = cli.Post("/many", items);
  1504. ASSERT_TRUE(res);
  1505. ASSERT_EQ(part_count, received.size());
  1506. for (size_t i = 0; i < part_count; i++) {
  1507. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1508. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1509. }
  1510. }
  1511. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1512. string content_type = "multipart/form-data; boundary=something";
  1513. string boundary;
  1514. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1515. EXPECT_TRUE(ret);
  1516. EXPECT_EQ(boundary, "something");
  1517. }
  1518. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1519. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1520. string boundary;
  1521. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1522. EXPECT_TRUE(ret);
  1523. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1524. }
  1525. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1526. string content_type =
  1527. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1528. string boundary;
  1529. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1530. EXPECT_TRUE(ret);
  1531. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1532. }
  1533. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1534. string content_type =
  1535. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1536. string boundary;
  1537. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1538. EXPECT_TRUE(ret);
  1539. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1542. const string boundary(70, 'a');
  1543. string content_type = "multipart/form-data; boundary=" + boundary;
  1544. string parsed;
  1545. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(parsed, boundary);
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1550. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1551. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1552. string parsed;
  1553. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1554. EXPECT_FALSE(ret);
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1557. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1558. // is 72 characters on the wire and still valid.
  1559. const string boundary(70, 'a');
  1560. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1561. string parsed;
  1562. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1563. EXPECT_EQ(parsed, boundary);
  1564. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1565. parsed.clear();
  1566. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1567. }
  1568. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1569. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1570. // The parameter parser must not treat that '=' as the key/value separator.
  1571. string content_type =
  1572. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1573. "charset=UTF-8";
  1574. string parsed;
  1575. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1576. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1577. }
  1578. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1579. // A ';' inside the quoted-string is part of the value, not a parameter
  1580. // separator, so it must not truncate the boundary.
  1581. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1582. string parsed;
  1583. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1584. EXPECT_EQ(parsed, "a;b");
  1585. }
  1586. TEST(ParseDispositionParamsTest, QuotedValues) {
  1587. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1588. // ';' and '=' are ordinary characters inside one.
  1589. struct {
  1590. const char *value;
  1591. std::vector<std::pair<const char *, const char *>> expected;
  1592. } cases[] = {
  1593. {"name=\"file1\"; filename=\"a.txt\"",
  1594. {{"name", "file1"}, {"filename", "a.txt"}}},
  1595. // Whitespace around '=' and ';' is still trimmed
  1596. {"name=\"file2\" ;filename = \"a.html\"",
  1597. {{"name", "file2"}, {"filename", "a.html"}}},
  1598. // '=' inside the value used to leave only the text after the last one
  1599. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1600. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1601. {"name=\"x=y\"", {{"name", "x=y"}}},
  1602. // ';' inside the value used to truncate the pair and leave a bogus one
  1603. {"name=\"file3\"; filename=\"a;b.txt\"",
  1604. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1605. // An unquoted value keeps working, and so does filename*
  1606. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1607. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1608. // A parameter with no key is dropped rather than turned into one whose
  1609. // key is the value
  1610. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1611. // An escaped quote does not end the value
  1612. {"name=\"a\\\"; filename=evil.php\"",
  1613. {{"name", "a\"; filename=evil.php"}}},
  1614. // Other backslashes, as in a Windows path, are kept
  1615. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1616. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1617. };
  1618. for (const auto &c : cases) {
  1619. Params params;
  1620. detail::parse_disposition_params(c.value, params);
  1621. for (const auto &kv : c.expected) {
  1622. auto it = params.find(kv.first);
  1623. ASSERT_NE(it, params.end())
  1624. << "value: " << c.value << ", key: " << kv.first;
  1625. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1626. }
  1627. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1628. }
  1629. }
  1630. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1631. Server svr;
  1632. std::string filename;
  1633. std::string content;
  1634. svr.Post("/upload", [&](const Request &req, Response &) {
  1635. const auto &file = req.form.get_file("file");
  1636. filename = file.filename;
  1637. content = file.content;
  1638. });
  1639. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1640. auto se = detail::scope_exit([&] {
  1641. svr.stop();
  1642. thread.join();
  1643. ASSERT_FALSE(svr.is_running());
  1644. });
  1645. svr.wait_until_ready();
  1646. std::string body = "--B\r\n"
  1647. "Content-Disposition: form-data; name=\"file\"; "
  1648. "filename=\"a.txt\"\r\n"
  1649. "Content-Type: text/plain\r\n"
  1650. "\r\n"
  1651. "hello\r\n"
  1652. "--B--\r\n";
  1653. Client cli(HOST, PORT);
  1654. auto res = cli.Post(
  1655. "/upload",
  1656. [&](size_t offset, DataSink &sink) {
  1657. if (offset < body.size()) {
  1658. sink.write(&body[offset], 1);
  1659. } else {
  1660. sink.done();
  1661. }
  1662. return true;
  1663. },
  1664. "multipart/form-data; boundary=B");
  1665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1666. EXPECT_EQ(StatusCode::OK_200, res->status);
  1667. EXPECT_EQ("a.txt", filename);
  1668. EXPECT_EQ("hello", content);
  1669. }
  1670. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1671. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1672. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1673. Server svr;
  1674. std::string field_value, file_name, file_filename;
  1675. bool has_field = false, has_file = false;
  1676. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1677. has_field = req.form.has_field("x=y");
  1678. field_value = req.form.get_field("x=y");
  1679. has_file = req.form.has_file("file1");
  1680. const auto &file = req.form.get_file("file1");
  1681. file_name = file.name;
  1682. file_filename = file.filename;
  1683. res.set_content("ok", "text/plain");
  1684. });
  1685. auto port = svr.bind_to_any_port(HOST);
  1686. thread t = thread([&] { svr.listen_after_bind(); });
  1687. auto se = detail::scope_exit([&] {
  1688. svr.stop();
  1689. t.join();
  1690. ASSERT_FALSE(svr.is_running());
  1691. });
  1692. svr.wait_until_ready();
  1693. UploadFormDataItems items = {
  1694. {"x=y", "field-value", "", ""},
  1695. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1696. };
  1697. Client cli(HOST, port);
  1698. auto res = cli.Post("/quoted", items);
  1699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1700. ASSERT_EQ(StatusCode::OK_200, res->status);
  1701. EXPECT_TRUE(has_field);
  1702. EXPECT_EQ("field-value", field_value);
  1703. EXPECT_TRUE(has_file);
  1704. EXPECT_EQ("file1", file_name);
  1705. EXPECT_EQ("a;b=report.pdf", file_filename);
  1706. }
  1707. TEST(GetHeaderValueTest, DefaultValue) {
  1708. Headers headers = {{"Dummy", "Dummy"}};
  1709. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1710. EXPECT_STREQ("text/plain", val);
  1711. }
  1712. TEST(GetHeaderValueTest, DefaultValueInt) {
  1713. Headers headers = {{"Dummy", "Dummy"}};
  1714. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1715. EXPECT_EQ(100ull, val);
  1716. }
  1717. TEST(GetHeaderValueTest, RegularValue) {
  1718. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1719. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1720. EXPECT_STREQ("text/html", val);
  1721. }
  1722. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1723. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1724. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1725. EXPECT_STREQ("text/html", val);
  1726. }
  1727. TEST(GetHeaderValueTest, SetContent) {
  1728. Response res;
  1729. res.set_content("html", "text/html");
  1730. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1731. res.set_content("text", "text/plain");
  1732. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1733. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1734. }
  1735. TEST(GetHeaderValueTest, RegularValueInt) {
  1736. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1737. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1738. EXPECT_EQ(100ull, val);
  1739. }
  1740. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1741. Headers headers = {{"Content-Length", "x"}};
  1742. auto is_invalid_value = false;
  1743. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1744. is_invalid_value);
  1745. EXPECT_EQ(0ull, val);
  1746. EXPECT_TRUE(is_invalid_value);
  1747. }
  1748. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1749. // An all-digit value that overflows size_t must be reported as invalid, not
  1750. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1751. // a large length to a small one on 32-bit builds, leaving the framing length
  1752. // wrong while is_invalid_value stayed false.
  1753. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1754. auto is_invalid_value = false;
  1755. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1756. is_invalid_value);
  1757. EXPECT_TRUE(is_invalid_value);
  1758. // A well-formed length is unaffected.
  1759. Headers ok = {{"Content-Length", "1234"}};
  1760. is_invalid_value = false;
  1761. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1762. is_invalid_value);
  1763. EXPECT_EQ(1234ull, val);
  1764. EXPECT_FALSE(is_invalid_value);
  1765. }
  1766. TEST(GetHeaderValueTest, Range) {
  1767. {
  1768. Headers headers = {make_range_header({{1, -1}})};
  1769. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1770. EXPECT_STREQ("bytes=1-", val);
  1771. }
  1772. {
  1773. Headers headers = {make_range_header({{-1, 1}})};
  1774. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1775. EXPECT_STREQ("bytes=-1", val);
  1776. }
  1777. {
  1778. Headers headers = {make_range_header({{1, 10}})};
  1779. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1780. EXPECT_STREQ("bytes=1-10", val);
  1781. }
  1782. {
  1783. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1784. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1785. EXPECT_STREQ("bytes=1-10, 100-", val);
  1786. }
  1787. {
  1788. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1789. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1790. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1791. }
  1792. {
  1793. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1794. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1795. EXPECT_STREQ("bytes=0-0, -1", val);
  1796. }
  1797. }
  1798. TEST(BearerTokenAuthTest, SchemeValidation) {
  1799. // A value shorter than "Bearer " must not throw from the fixed-length
  1800. // substr, and a non-Bearer scheme must not be reported as a token.
  1801. struct {
  1802. const char *value;
  1803. const char *expected;
  1804. } cases[] = {
  1805. {"x", ""},
  1806. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1807. {"Bearer abc123", "abc123"},
  1808. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1809. };
  1810. for (const auto &c : cases) {
  1811. Request req;
  1812. req.set_header("Authorization", c.value);
  1813. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1814. }
  1815. }
  1816. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1817. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1818. // to depend on the standard library (libstdc++ handed back duplicates in
  1819. // reverse insertion order, libc++ in insertion order).
  1820. Request req;
  1821. req.set_header("Accept-Encoding", "gzip");
  1822. req.set_header("Accept-Encoding", "deflate");
  1823. req.set_header("Accept-Encoding", "br");
  1824. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1825. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1826. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1827. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1828. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1829. }
  1830. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1831. Request req;
  1832. req.set_header("X-Test", "only");
  1833. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1834. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1835. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1836. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1837. }
  1838. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1839. Request req;
  1840. req.set_header("X-First", "1");
  1841. req.set_header("X-Test", "2");
  1842. req.params.emplace("first", "1");
  1843. req.params.emplace("test", "2");
  1844. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1845. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1846. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1847. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1848. // The second one is negative when read as a signed value
  1849. const auto max_id = (std::numeric_limits<size_t>::max)();
  1850. for (auto id : {max_id / 2, max_id}) {
  1851. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1852. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1853. EXPECT_EQ("", req.get_param_value("test", id));
  1854. EXPECT_EQ("", req.form.get_field("test", id));
  1855. EXPECT_EQ("", req.form.get_file("test", id).content);
  1856. }
  1857. }
  1858. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1859. Headers headers;
  1860. headers.emplace("Host", "example.com");
  1861. headers.emplace("Accept-Encoding", "gzip");
  1862. headers.emplace("User-Agent", "test");
  1863. headers.emplace("Accept-Encoding", "deflate");
  1864. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1865. "Accept-Encoding=deflate ",
  1866. entries_to_string(headers));
  1867. }
  1868. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1869. Headers headers = {{"Content-Type", "text/html"},
  1870. {"CONTENT-TYPE", "text/xml"}};
  1871. EXPECT_EQ(2U, headers.count("content-type"));
  1872. auto it = headers.find("content-type");
  1873. ASSERT_TRUE(it != headers.end());
  1874. EXPECT_EQ("text/html", it->second);
  1875. }
  1876. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1877. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1878. // drop only those fields and leave everything positioned between them.
  1879. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1880. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1881. auto rng = headers.equal_range("a");
  1882. headers.erase(rng.first, rng.second);
  1883. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1884. }
  1885. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1886. Headers headers = {
  1887. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1888. EXPECT_EQ(3U, headers.erase("A"));
  1889. EXPECT_EQ(0U, headers.count("A"));
  1890. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1891. }
  1892. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1893. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1894. headers.emplace_front("Host", "example.com");
  1895. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1896. entries_to_string(headers));
  1897. }
  1898. TEST(ParseHeaderValueTest, Range) {
  1899. {
  1900. Ranges ranges;
  1901. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1902. EXPECT_TRUE(ret);
  1903. EXPECT_EQ(1u, ranges.size());
  1904. EXPECT_EQ(1u, ranges[0].first);
  1905. EXPECT_EQ(-1, ranges[0].second);
  1906. }
  1907. {
  1908. Ranges ranges;
  1909. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1910. EXPECT_TRUE(ret);
  1911. EXPECT_EQ(1u, ranges.size());
  1912. EXPECT_EQ(-1, ranges[0].first);
  1913. EXPECT_EQ(1u, ranges[0].second);
  1914. }
  1915. {
  1916. Ranges ranges;
  1917. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1918. EXPECT_TRUE(ret);
  1919. EXPECT_EQ(1u, ranges.size());
  1920. EXPECT_EQ(1u, ranges[0].first);
  1921. EXPECT_EQ(10u, ranges[0].second);
  1922. }
  1923. {
  1924. Ranges ranges;
  1925. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1926. EXPECT_FALSE(ret);
  1927. }
  1928. {
  1929. Ranges ranges;
  1930. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1931. EXPECT_TRUE(ret);
  1932. EXPECT_EQ(2u, ranges.size());
  1933. EXPECT_EQ(1u, ranges[0].first);
  1934. EXPECT_EQ(10u, ranges[0].second);
  1935. EXPECT_EQ(100u, ranges[1].first);
  1936. EXPECT_EQ(-1, ranges[1].second);
  1937. }
  1938. {
  1939. Ranges ranges;
  1940. auto ret =
  1941. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ(3u, ranges.size());
  1944. EXPECT_EQ(1u, ranges[0].first);
  1945. EXPECT_EQ(10u, ranges[0].second);
  1946. EXPECT_EQ(100u, ranges[1].first);
  1947. EXPECT_EQ(200u, ranges[1].second);
  1948. EXPECT_EQ(300u, ranges[2].first);
  1949. EXPECT_EQ(400u, ranges[2].second);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1954. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1955. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1956. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1957. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1958. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1959. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1960. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1961. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1962. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1963. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1964. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1965. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1966. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1967. EXPECT_FALSE(
  1968. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1969. EXPECT_TRUE(ranges.empty());
  1970. }
  1971. {
  1972. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1973. // remainder of the representation, so it stays accepted.
  1974. Ranges ranges;
  1975. auto ret =
  1976. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1977. EXPECT_TRUE(ret);
  1978. ASSERT_EQ(1u, ranges.size());
  1979. EXPECT_EQ(0, ranges[0].first);
  1980. EXPECT_EQ(-1, ranges[0].second);
  1981. }
  1982. // RFC 9110 14.1: range unit names are case-insensitive.
  1983. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1984. Ranges ranges;
  1985. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1986. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1987. }
  1988. }
  1989. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1990. Request req;
  1991. req.set_header("Accept-Encoding", "gzip");
  1992. Response res;
  1993. res.set_header("Content-Type", "text/plain");
  1994. auto ret = detail::encoding_type(req, res);
  1995. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1996. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1997. #else
  1998. EXPECT_TRUE(ret == detail::EncodingType::None);
  1999. #endif
  2000. }
  2001. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2002. Request req;
  2003. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2004. Response res;
  2005. res.set_header("Content-Type", "text/plain");
  2006. auto ret = detail::encoding_type(req, res);
  2007. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2008. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2009. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2010. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2011. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2012. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2013. #else
  2014. EXPECT_TRUE(ret == detail::EncodingType::None);
  2015. #endif
  2016. }
  2017. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2018. Request req;
  2019. req.set_header("Accept-Encoding",
  2020. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2021. Response res;
  2022. res.set_header("Content-Type", "text/plain");
  2023. auto ret = detail::encoding_type(req, res);
  2024. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2025. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2026. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2027. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2028. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2029. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2030. #else
  2031. EXPECT_TRUE(ret == detail::EncodingType::None);
  2032. #endif
  2033. }
  2034. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2035. // All supported encodings rejected with q=0 should return None
  2036. Request req;
  2037. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2038. Response res;
  2039. res.set_header("Content-Type", "text/plain");
  2040. auto ret = detail::encoding_type(req, res);
  2041. EXPECT_TRUE(ret == detail::EncodingType::None);
  2042. }
  2043. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2044. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2045. Request req;
  2046. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2047. Response res;
  2048. res.set_header("Content-Type", "text/plain");
  2049. auto ret = detail::encoding_type(req, res);
  2050. EXPECT_TRUE(ret == detail::EncodingType::None);
  2051. }
  2052. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2053. Request req;
  2054. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2055. Response res;
  2056. res.set_header("Content-Type", "text/plain");
  2057. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2058. }
  2059. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2060. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2061. Request req;
  2062. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2063. Response res;
  2064. res.set_header("Content-Type", "text/plain");
  2065. auto ret = detail::encoding_type(req, res);
  2066. EXPECT_TRUE(ret == detail::EncodingType::None);
  2067. }
  2068. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2069. // RFC 7231: Accept-Encoding values are case-insensitive
  2070. Request req;
  2071. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2072. Response res;
  2073. res.set_header("Content-Type", "text/plain");
  2074. auto ret = detail::encoding_type(req, res);
  2075. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2076. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2077. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2078. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2079. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2080. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2081. #else
  2082. EXPECT_TRUE(ret == detail::EncodingType::None);
  2083. #endif
  2084. }
  2085. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2086. // q value should determine priority, not hardcoded order
  2087. Request req;
  2088. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2089. Response res;
  2090. res.set_header("Content-Type", "text/plain");
  2091. auto ret = detail::encoding_type(req, res);
  2092. // gzip has highest q=1.0, so it should be selected even though
  2093. // br and zstd are also supported
  2094. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2095. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2096. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2097. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2098. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2100. #else
  2101. EXPECT_TRUE(ret == detail::EncodingType::None);
  2102. #endif
  2103. }
  2104. TEST(BufferStreamTest, read) {
  2105. detail::BufferStream strm1;
  2106. Stream &strm = strm1;
  2107. EXPECT_EQ(5, strm.write("hello"));
  2108. char buf[512];
  2109. EXPECT_EQ(2, strm.read(buf, 2));
  2110. EXPECT_EQ('h', buf[0]);
  2111. EXPECT_EQ('e', buf[1]);
  2112. EXPECT_EQ(2, strm.read(buf, 2));
  2113. EXPECT_EQ('l', buf[0]);
  2114. EXPECT_EQ('l', buf[1]);
  2115. EXPECT_EQ(1, strm.read(buf, 1));
  2116. EXPECT_EQ('o', buf[0]);
  2117. EXPECT_EQ(0, strm.read(buf, 1));
  2118. }
  2119. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2120. auto host = "www.httpwatch.com";
  2121. auto ip = hosted_at(host);
  2122. EXPECT_EQ("23.96.13.243", ip);
  2123. std::vector<std::string> addrs;
  2124. hosted_at(host, addrs);
  2125. EXPECT_EQ(1u, addrs.size());
  2126. }
  2127. #if 0 // It depends on each test environment...
  2128. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2129. auto host = "www.youtube.com";
  2130. std::vector<std::string> addrs;
  2131. hosted_at(host, addrs);
  2132. EXPECT_EQ(20u, addrs.size());
  2133. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2134. EXPECT_TRUE(it != addrs.end());
  2135. }
  2136. #endif
  2137. class ChunkedEncodingTest : public ::testing::Test {
  2138. protected:
  2139. ChunkedEncodingTest()
  2140. : cli_(HOST, PORT)
  2141. #ifdef CPPHTTPLIB_SSL_ENABLED
  2142. ,
  2143. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2144. #endif
  2145. {
  2146. cli_.set_connection_timeout(2);
  2147. #ifdef CPPHTTPLIB_SSL_ENABLED
  2148. cli_.enable_server_certificate_verification(false);
  2149. #endif
  2150. }
  2151. virtual void SetUp() {
  2152. read_file("./image.jpg", image_data_);
  2153. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2154. res.set_content("Hello World!", "text/plain");
  2155. });
  2156. svr_.Get(
  2157. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2158. res.set_chunked_content_provider(
  2159. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2160. size_t remaining = image_data_.size() - offset;
  2161. if (remaining == 0) {
  2162. sink.done();
  2163. } else {
  2164. constexpr size_t CHUNK_SIZE = 1024;
  2165. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2166. sink.write(&image_data_[offset], send_size);
  2167. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2168. }
  2169. return true;
  2170. });
  2171. });
  2172. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2173. svr_.wait_until_ready();
  2174. }
  2175. virtual void TearDown() {
  2176. svr_.stop();
  2177. if (!request_threads_.empty()) {
  2178. std::this_thread::sleep_for(std::chrono::seconds(1));
  2179. for (auto &t : request_threads_) {
  2180. t.join();
  2181. }
  2182. }
  2183. t_.join();
  2184. }
  2185. #ifdef CPPHTTPLIB_SSL_ENABLED
  2186. SSLClient cli_;
  2187. SSLServer svr_;
  2188. #else
  2189. Client cli_;
  2190. Server svr_;
  2191. #endif
  2192. thread t_;
  2193. std::vector<thread> request_threads_;
  2194. std::string image_data_;
  2195. };
  2196. TEST_F(ChunkedEncodingTest, NormalGet) {
  2197. auto res = cli_.Get("/chunked");
  2198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2199. std::string out;
  2200. read_file("./image.jpg", out);
  2201. EXPECT_EQ(StatusCode::OK_200, res->status);
  2202. EXPECT_EQ(out, res->body);
  2203. }
  2204. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2205. std::string body;
  2206. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2207. body.append(data, data_length);
  2208. return true;
  2209. });
  2210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2211. std::string out;
  2212. read_file("./image.jpg", out);
  2213. EXPECT_EQ(StatusCode::OK_200, res->status);
  2214. EXPECT_EQ(out, body);
  2215. }
  2216. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2217. std::string body;
  2218. auto res = cli_.Get(
  2219. "/chunked",
  2220. [&](const Response &response) {
  2221. EXPECT_EQ(StatusCode::OK_200, response.status);
  2222. return true;
  2223. },
  2224. [&](const char *data, size_t data_length) {
  2225. body.append(data, data_length);
  2226. return true;
  2227. });
  2228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2229. std::string out;
  2230. read_file("./image.jpg", out);
  2231. EXPECT_EQ(StatusCode::OK_200, res->status);
  2232. EXPECT_EQ(out, body);
  2233. }
  2234. TEST(RangeTest, FromHTTPBin_Online) {
  2235. auto host = "httpbingo.org";
  2236. auto path = std::string{"/range/32"};
  2237. #ifdef CPPHTTPLIB_SSL_ENABLED
  2238. auto port = 443;
  2239. SSLClient cli(host, port);
  2240. #else
  2241. auto port = 80;
  2242. Client cli(host, port);
  2243. #endif
  2244. cli.set_connection_timeout(5);
  2245. {
  2246. auto res = cli.Get(path);
  2247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2248. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2249. EXPECT_EQ(StatusCode::OK_200, res->status);
  2250. }
  2251. {
  2252. Headers headers = {make_range_header({{1, -1}})};
  2253. auto res = cli.Get(path, headers);
  2254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2255. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2257. }
  2258. {
  2259. Headers headers = {make_range_header({{1, 10}})};
  2260. auto res = cli.Get(path, headers);
  2261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2262. EXPECT_EQ("bcdefghijk", res->body);
  2263. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2264. }
  2265. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2266. // entire resource, while the original httpbin returned 200. Both are
  2267. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2268. {
  2269. Headers headers = {make_range_header({{0, 31}})};
  2270. auto res = cli.Get(path, headers);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2274. res->status == StatusCode::PartialContent_206);
  2275. }
  2276. {
  2277. Headers headers = {make_range_header({{0, -1}})};
  2278. auto res = cli.Get(path, headers);
  2279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2280. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2281. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2282. res->status == StatusCode::PartialContent_206);
  2283. }
  2284. // go-httpbin returns 206 with clamped range for over-range requests,
  2285. // while the original httpbin returned 416. Both behaviors are observed
  2286. // in real servers, so we only verify the request succeeds.
  2287. {
  2288. Headers headers = {make_range_header({{0, 32}})};
  2289. auto res = cli.Get(path, headers);
  2290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2291. }
  2292. }
  2293. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2294. auto host = "unresolvableaddress.local";
  2295. auto path = std::string{"/"};
  2296. #ifdef CPPHTTPLIB_SSL_ENABLED
  2297. auto port = 443;
  2298. SSLClient cli(host, port);
  2299. #else
  2300. auto port = 80;
  2301. Client cli(host, port);
  2302. #endif
  2303. cli.set_connection_timeout(1);
  2304. {
  2305. auto res = cli.Get(path);
  2306. ASSERT_FALSE(res);
  2307. }
  2308. std::this_thread::sleep_for(std::chrono::seconds(8));
  2309. }
  2310. #if defined(__linux__) && defined(__GLIBC__) && \
  2311. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2312. // Forward declaration: in split builds split.py strips `inline` and moves the
  2313. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2314. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2315. // against the symbol in both header-only and split builds.
  2316. namespace httplib {
  2317. namespace detail {
  2318. int getaddrinfo_with_timeout(const char *node, const char *service,
  2319. const struct addrinfo *hints,
  2320. struct addrinfo **res, time_t timeout_sec);
  2321. } // namespace detail
  2322. } // namespace httplib
  2323. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2324. //
  2325. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2326. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2327. // gai_suspend() call hits the connection timeout the function calls
  2328. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2329. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2330. // still alive and still references the now-destroyed stack frame.
  2331. //
  2332. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2333. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2334. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2335. // and runs them in a container.
  2336. namespace {
  2337. bool should_run_issue_2431_tests() {
  2338. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2339. return v && *v && std::string(v) != "0";
  2340. }
  2341. std::string unique_unresolvable_host(int n) {
  2342. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2343. // glibc still asks the configured nameserver — which is exactly the path
  2344. // we want to exercise. A unique label per call avoids the resolver cache.
  2345. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2346. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2347. std::to_string(n) + ".invalid";
  2348. }
  2349. } // namespace
  2350. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2351. if (!should_run_issue_2431_tests()) {
  2352. GTEST_SKIP()
  2353. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2354. }
  2355. for (int i = 0; i < 8; ++i) {
  2356. struct addrinfo hints;
  2357. memset(&hints, 0, sizeof(hints));
  2358. hints.ai_family = AF_UNSPEC;
  2359. hints.ai_socktype = SOCK_STREAM;
  2360. auto host = unique_unresolvable_host(i);
  2361. struct addrinfo *result = nullptr;
  2362. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2363. &result, /*timeout_sec=*/1);
  2364. if (rc == 0 && result) { freeaddrinfo(result); }
  2365. }
  2366. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2367. // stack region they still believe holds their gaicb.
  2368. std::this_thread::sleep_for(std::chrono::seconds(3));
  2369. }
  2370. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2371. if (!should_run_issue_2431_tests()) {
  2372. GTEST_SKIP()
  2373. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2374. }
  2375. std::atomic<bool> stop{false};
  2376. std::vector<std::thread> threads;
  2377. for (int t = 0; t < 8; ++t) {
  2378. threads.emplace_back([t, &stop] {
  2379. int i = 0;
  2380. while (!stop.load(std::memory_order_relaxed)) {
  2381. struct addrinfo hints;
  2382. memset(&hints, 0, sizeof(hints));
  2383. hints.ai_family = AF_UNSPEC;
  2384. hints.ai_socktype = SOCK_STREAM;
  2385. auto host = unique_unresolvable_host(t * 100000 + i++);
  2386. struct addrinfo *result = nullptr;
  2387. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2388. &result, /*timeout_sec=*/1);
  2389. if (rc == 0 && result) { freeaddrinfo(result); }
  2390. }
  2391. });
  2392. }
  2393. std::this_thread::sleep_for(std::chrono::seconds(8));
  2394. stop.store(true, std::memory_order_relaxed);
  2395. for (auto &th : threads) {
  2396. th.join();
  2397. }
  2398. std::this_thread::sleep_for(std::chrono::seconds(3));
  2399. }
  2400. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2401. if (!should_run_issue_2431_tests()) {
  2402. GTEST_SKIP()
  2403. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2404. }
  2405. std::atomic<bool> stop{false};
  2406. std::vector<std::thread> threads;
  2407. for (int t = 0; t < 8; ++t) {
  2408. threads.emplace_back([t, &stop] {
  2409. int i = 0;
  2410. while (!stop.load(std::memory_order_relaxed)) {
  2411. auto host = unique_unresolvable_host(t * 100000 + i++);
  2412. Client cli(host, 80);
  2413. cli.set_connection_timeout(1, 0);
  2414. cli.set_read_timeout(1, 0);
  2415. cli.set_write_timeout(1, 0);
  2416. (void)cli.Get("/");
  2417. }
  2418. });
  2419. }
  2420. std::this_thread::sleep_for(std::chrono::seconds(8));
  2421. stop.store(true, std::memory_order_relaxed);
  2422. for (auto &th : threads) {
  2423. th.join();
  2424. }
  2425. std::this_thread::sleep_for(std::chrono::seconds(3));
  2426. }
  2427. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2428. TEST(ConnectionErrorTest, InvalidHost) {
  2429. auto host = "-abcde.com";
  2430. #ifdef CPPHTTPLIB_SSL_ENABLED
  2431. auto port = 443;
  2432. SSLClient cli(host, port);
  2433. #else
  2434. auto port = 80;
  2435. Client cli(host, port);
  2436. #endif
  2437. cli.set_connection_timeout(std::chrono::seconds(2));
  2438. auto res = cli.Get("/");
  2439. ASSERT_TRUE(!res);
  2440. EXPECT_EQ(Error::Connection, res.error());
  2441. }
  2442. TEST(ConnectionErrorTest, InvalidHost2) {
  2443. auto host = "httpcan.org/";
  2444. #ifdef CPPHTTPLIB_SSL_ENABLED
  2445. SSLClient cli(host);
  2446. #else
  2447. Client cli(host);
  2448. #endif
  2449. cli.set_connection_timeout(std::chrono::seconds(2));
  2450. auto res = cli.Get("/");
  2451. ASSERT_TRUE(!res);
  2452. EXPECT_EQ(Error::Connection, res.error());
  2453. }
  2454. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2455. auto host = "httpcan.org/";
  2456. #ifdef CPPHTTPLIB_SSL_ENABLED
  2457. SSLClient cli(host);
  2458. #else
  2459. Client cli(host);
  2460. #endif
  2461. cli.set_connection_timeout(std::chrono::seconds(2));
  2462. auto res = cli.Get("/");
  2463. ASSERT_TRUE(!res);
  2464. stringstream s;
  2465. s << "error code: " << res.error();
  2466. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2467. }
  2468. TEST(ConnectionErrorTest, InvalidPort) {
  2469. auto host = "localhost";
  2470. auto port = 44380;
  2471. #ifdef CPPHTTPLIB_SSL_ENABLED
  2472. SSLClient cli(host, port);
  2473. #else
  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_TRUE(Error::Connection == res.error() ||
  2480. Error::ConnectionTimeout == res.error());
  2481. }
  2482. TEST(ConnectionErrorTest, Timeout_Online) {
  2483. auto host = "google.com";
  2484. #ifdef CPPHTTPLIB_SSL_ENABLED
  2485. auto port = 44380;
  2486. SSLClient cli(host, port);
  2487. #else
  2488. auto port = 8080;
  2489. Client cli(host, port);
  2490. #endif
  2491. cli.set_connection_timeout(std::chrono::seconds(2));
  2492. // only probe one address type so that the error reason
  2493. // correlates to the timed-out IPv4, not the unsupported
  2494. // IPv6 connection attempt
  2495. cli.set_address_family(AF_INET);
  2496. auto res = cli.Get("/");
  2497. ASSERT_TRUE(!res);
  2498. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2499. }
  2500. TEST(CancelTest, NoCancel_Online) {
  2501. auto host = "httpbingo.org";
  2502. auto path = std::string{"/range/32"};
  2503. #ifdef CPPHTTPLIB_SSL_ENABLED
  2504. auto port = 443;
  2505. SSLClient cli(host, port);
  2506. #else
  2507. auto port = 80;
  2508. Client cli(host, port);
  2509. #endif
  2510. cli.set_connection_timeout(std::chrono::seconds(5));
  2511. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2513. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2514. EXPECT_EQ(StatusCode::OK_200, res->status);
  2515. }
  2516. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2517. // Use /bytes with a large payload so that the DownloadProgress callback
  2518. // (which only fires for Content-Length responses) is invoked before the
  2519. // entire body is received, giving cancellation a chance to fire.
  2520. auto host = "httpbingo.org";
  2521. auto path = std::string{"/bytes/524288"};
  2522. #ifdef CPPHTTPLIB_SSL_ENABLED
  2523. auto port = 443;
  2524. SSLClient cli(host, port);
  2525. #else
  2526. auto port = 80;
  2527. Client cli(host, port);
  2528. #endif
  2529. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2530. cli.set_connection_timeout(std::chrono::seconds(5));
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. TEST(CancelTest, WithCancelLargePayload_Online) {
  2535. auto host = "httpbingo.org";
  2536. auto path = std::string{"/bytes/524288"};
  2537. #ifdef CPPHTTPLIB_SSL_ENABLED
  2538. auto port = 443;
  2539. SSLClient cli(host, port);
  2540. #else
  2541. auto port = 80;
  2542. Client cli(host, port);
  2543. #endif
  2544. cli.set_connection_timeout(std::chrono::seconds(5));
  2545. uint32_t count = 0;
  2546. auto res =
  2547. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2548. ASSERT_TRUE(!res);
  2549. EXPECT_EQ(Error::Canceled, res.error());
  2550. }
  2551. TEST(CancelTest, NoCancelPost) {
  2552. Server svr;
  2553. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2554. res.set_content("Hello World!", "text/plain");
  2555. });
  2556. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2557. auto se = detail::scope_exit([&] {
  2558. svr.stop();
  2559. thread.join();
  2560. ASSERT_FALSE(svr.is_running());
  2561. });
  2562. svr.wait_until_ready();
  2563. Client cli(HOST, PORT);
  2564. cli.set_connection_timeout(std::chrono::seconds(5));
  2565. auto res =
  2566. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2567. "application/json", [](uint64_t, uint64_t) { return true; });
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. EXPECT_EQ("Hello World!", res->body);
  2570. EXPECT_EQ(StatusCode::OK_200, res->status);
  2571. }
  2572. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2573. Server svr;
  2574. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2575. res.set_content("Hello World!", "text/plain");
  2576. });
  2577. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2578. auto se = detail::scope_exit([&] {
  2579. svr.stop();
  2580. thread.join();
  2581. ASSERT_FALSE(svr.is_running());
  2582. });
  2583. svr.wait_until_ready();
  2584. Client cli(HOST, PORT);
  2585. cli.set_connection_timeout(std::chrono::seconds(5));
  2586. auto res =
  2587. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2588. "application/json", [](uint64_t, uint64_t) { return false; });
  2589. ASSERT_TRUE(!res);
  2590. EXPECT_EQ(Error::Canceled, res.error());
  2591. }
  2592. TEST(CancelTest, WithCancelLargePayloadPost) {
  2593. Server svr;
  2594. svr.set_payload_max_length(200 * 1024 * 1024);
  2595. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2596. res.set_content(LARGE_DATA, "text/plain");
  2597. });
  2598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2599. auto se = detail::scope_exit([&] {
  2600. svr.stop();
  2601. thread.join();
  2602. ASSERT_FALSE(svr.is_running());
  2603. });
  2604. svr.wait_until_ready();
  2605. Client cli(HOST, PORT);
  2606. cli.set_payload_max_length(200 * 1024 * 1024);
  2607. cli.set_connection_timeout(std::chrono::seconds(5));
  2608. auto res =
  2609. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2610. "application/json", [](uint64_t, uint64_t) { return false; });
  2611. ASSERT_TRUE(!res);
  2612. EXPECT_EQ(Error::Canceled, res.error());
  2613. }
  2614. TEST(CancelTest, NoCancelPut) {
  2615. Server svr;
  2616. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2617. res.set_content("Hello World!", "text/plain");
  2618. });
  2619. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2620. auto se = detail::scope_exit([&] {
  2621. svr.stop();
  2622. thread.join();
  2623. ASSERT_FALSE(svr.is_running());
  2624. });
  2625. svr.wait_until_ready();
  2626. Client cli(HOST, PORT);
  2627. cli.set_connection_timeout(std::chrono::seconds(5));
  2628. auto res =
  2629. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2630. "application/json", [](uint64_t, uint64_t) { return true; });
  2631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2632. EXPECT_EQ("Hello World!", res->body);
  2633. EXPECT_EQ(StatusCode::OK_200, res->status);
  2634. }
  2635. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2636. Server svr;
  2637. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2638. res.set_content("Hello World!", "text/plain");
  2639. });
  2640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2641. auto se = detail::scope_exit([&] {
  2642. svr.stop();
  2643. thread.join();
  2644. ASSERT_FALSE(svr.is_running());
  2645. });
  2646. svr.wait_until_ready();
  2647. Client cli(HOST, PORT);
  2648. cli.set_connection_timeout(std::chrono::seconds(5));
  2649. auto res =
  2650. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2651. "application/json", [](uint64_t, uint64_t) { return false; });
  2652. ASSERT_TRUE(!res);
  2653. EXPECT_EQ(Error::Canceled, res.error());
  2654. }
  2655. TEST(CancelTest, WithCancelLargePayloadPut) {
  2656. Server svr;
  2657. svr.set_payload_max_length(200 * 1024 * 1024);
  2658. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2659. res.set_content(LARGE_DATA, "text/plain");
  2660. });
  2661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2662. auto se = detail::scope_exit([&] {
  2663. svr.stop();
  2664. thread.join();
  2665. ASSERT_FALSE(svr.is_running());
  2666. });
  2667. svr.wait_until_ready();
  2668. Client cli(HOST, PORT);
  2669. cli.set_payload_max_length(200 * 1024 * 1024);
  2670. cli.set_connection_timeout(std::chrono::seconds(5));
  2671. auto res =
  2672. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2673. "application/json", [](uint64_t, uint64_t) { return false; });
  2674. ASSERT_TRUE(!res);
  2675. EXPECT_EQ(Error::Canceled, res.error());
  2676. }
  2677. TEST(CancelTest, NoCancelPatch) {
  2678. Server svr;
  2679. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2680. res.set_content("Hello World!", "text/plain");
  2681. });
  2682. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2683. auto se = detail::scope_exit([&] {
  2684. svr.stop();
  2685. thread.join();
  2686. ASSERT_FALSE(svr.is_running());
  2687. });
  2688. svr.wait_until_ready();
  2689. Client cli(HOST, PORT);
  2690. cli.set_connection_timeout(std::chrono::seconds(5));
  2691. auto res =
  2692. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2693. "application/json", [](uint64_t, uint64_t) { return true; });
  2694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2695. EXPECT_EQ("Hello World!", res->body);
  2696. EXPECT_EQ(StatusCode::OK_200, res->status);
  2697. }
  2698. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2699. Server svr;
  2700. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2701. res.set_content("Hello World!", "text/plain");
  2702. });
  2703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2704. auto se = detail::scope_exit([&] {
  2705. svr.stop();
  2706. thread.join();
  2707. ASSERT_FALSE(svr.is_running());
  2708. });
  2709. svr.wait_until_ready();
  2710. Client cli(HOST, PORT);
  2711. cli.set_connection_timeout(std::chrono::seconds(5));
  2712. auto res =
  2713. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2714. "application/json", [](uint64_t, uint64_t) { return false; });
  2715. ASSERT_TRUE(!res);
  2716. EXPECT_EQ(Error::Canceled, res.error());
  2717. }
  2718. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2719. Server svr;
  2720. svr.set_payload_max_length(200 * 1024 * 1024);
  2721. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2722. res.set_content(LARGE_DATA, "text/plain");
  2723. });
  2724. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2725. auto se = detail::scope_exit([&] {
  2726. svr.stop();
  2727. thread.join();
  2728. ASSERT_FALSE(svr.is_running());
  2729. });
  2730. svr.wait_until_ready();
  2731. Client cli(HOST, PORT);
  2732. cli.set_payload_max_length(200 * 1024 * 1024);
  2733. cli.set_connection_timeout(std::chrono::seconds(5));
  2734. auto res =
  2735. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2736. "application/json", [](uint64_t, uint64_t) { return false; });
  2737. ASSERT_TRUE(!res);
  2738. EXPECT_EQ(Error::Canceled, res.error());
  2739. }
  2740. TEST(CancelTest, NoCancelDelete) {
  2741. Server svr;
  2742. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2743. res.set_content("Hello World!", "text/plain");
  2744. });
  2745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2746. auto se = detail::scope_exit([&] {
  2747. svr.stop();
  2748. thread.join();
  2749. ASSERT_FALSE(svr.is_running());
  2750. });
  2751. svr.wait_until_ready();
  2752. Client cli(HOST, PORT);
  2753. cli.set_connection_timeout(std::chrono::seconds(5));
  2754. auto res =
  2755. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2756. "application/json", [](uint64_t, uint64_t) { return true; });
  2757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2758. EXPECT_EQ("Hello World!", res->body);
  2759. EXPECT_EQ(StatusCode::OK_200, res->status);
  2760. }
  2761. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2762. Server svr;
  2763. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2764. res.set_content("Hello World!", "text/plain");
  2765. });
  2766. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2767. auto se = detail::scope_exit([&] {
  2768. svr.stop();
  2769. thread.join();
  2770. ASSERT_FALSE(svr.is_running());
  2771. });
  2772. svr.wait_until_ready();
  2773. Client cli(HOST, PORT);
  2774. cli.set_connection_timeout(std::chrono::seconds(5));
  2775. auto res =
  2776. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2777. "application/json", [](uint64_t, uint64_t) { return false; });
  2778. ASSERT_TRUE(!res);
  2779. EXPECT_EQ(Error::Canceled, res.error());
  2780. }
  2781. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2782. Server svr;
  2783. svr.set_payload_max_length(200 * 1024 * 1024);
  2784. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2785. res.set_content(LARGE_DATA, "text/plain");
  2786. });
  2787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2788. auto se = detail::scope_exit([&] {
  2789. svr.stop();
  2790. thread.join();
  2791. ASSERT_FALSE(svr.is_running());
  2792. });
  2793. svr.wait_until_ready();
  2794. Client cli(HOST, PORT);
  2795. cli.set_payload_max_length(200 * 1024 * 1024);
  2796. cli.set_connection_timeout(std::chrono::seconds(5));
  2797. auto res =
  2798. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2799. "application/json", [](uint64_t, uint64_t) { return false; });
  2800. ASSERT_TRUE(!res);
  2801. EXPECT_EQ(Error::Canceled, res.error());
  2802. }
  2803. static std::string remove_whitespace(const std::string &input) {
  2804. std::string output;
  2805. output.reserve(input.size());
  2806. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2807. [](unsigned char c) { return !std::isspace(c); });
  2808. return output;
  2809. }
  2810. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2811. auto host = "httpbingo.org";
  2812. auto path = std::string{"/basic-auth/hello/world"};
  2813. #ifdef CPPHTTPLIB_SSL_ENABLED
  2814. auto port = 443;
  2815. SSLClient cli(host, port);
  2816. #else
  2817. auto port = 80;
  2818. Client cli(host, port);
  2819. #endif
  2820. {
  2821. auto res = cli.Get(path);
  2822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2823. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2824. }
  2825. {
  2826. auto res = cli.Get(
  2827. path, Headers{make_basic_authentication_header("hello", "world")});
  2828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2829. auto body = remove_whitespace(res->body);
  2830. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2831. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2832. EXPECT_EQ(StatusCode::OK_200, res->status);
  2833. }
  2834. {
  2835. cli.set_basic_auth("hello", "world");
  2836. auto res = cli.Get(path);
  2837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2838. auto body = remove_whitespace(res->body);
  2839. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2840. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2841. EXPECT_EQ(StatusCode::OK_200, res->status);
  2842. }
  2843. {
  2844. cli.set_basic_auth("hello", "bad");
  2845. auto res = cli.Get(path);
  2846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2848. }
  2849. {
  2850. cli.set_basic_auth("bad", "world");
  2851. auto res = cli.Get(path);
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2854. }
  2855. }
  2856. #ifdef CPPHTTPLIB_SSL_ENABLED
  2857. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2858. auto host = "httpbingo.org";
  2859. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2860. auto paths = std::vector<std::string>{
  2861. "/digest-auth/auth/hello/world/MD5",
  2862. "/digest-auth/auth/hello/world/SHA-256",
  2863. };
  2864. auto port = 443;
  2865. SSLClient cli(host, port);
  2866. {
  2867. auto res = cli.Get(unauth_path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2870. }
  2871. {
  2872. cli.set_digest_auth("hello", "world");
  2873. for (const auto &path : paths) {
  2874. auto res = cli.Get(path.c_str());
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. auto body = remove_whitespace(res->body);
  2877. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2878. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2879. EXPECT_EQ(StatusCode::OK_200, res->status);
  2880. }
  2881. cli.set_digest_auth("hello", "bad");
  2882. for (const auto &path : paths) {
  2883. auto res = cli.Get(path.c_str());
  2884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2885. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2886. }
  2887. }
  2888. }
  2889. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2890. // comma-separated list of challenges, and each challenge may itself carry a
  2891. // comma-separated auth-param list, so a server can legally offer Basic
  2892. // before Digest, either as two field lines or packed into one. Runs one 401
  2893. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2894. // value() joins them in receipt order) and checks that the retry carries a
  2895. // well-formed Digest Authorization header naming expected_realm.
  2896. static void
  2897. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2898. const std::string &expected_realm) {
  2899. std::atomic<int> hits{0};
  2900. Server svr;
  2901. svr.Get("/x", [&](const Request &req, Response &res) {
  2902. if (++hits == 1) {
  2903. res.status = StatusCode::Unauthorized_401;
  2904. for (const auto &challenge : challenges) {
  2905. res.set_header("WWW-Authenticate", challenge);
  2906. }
  2907. } else {
  2908. auto authorization = req.get_header_value("Authorization");
  2909. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2910. EXPECT_NE(std::string::npos,
  2911. authorization.find("realm=\"" + expected_realm + "\""));
  2912. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2913. res.set_content("ok", "text/plain");
  2914. }
  2915. });
  2916. auto port = svr.bind_to_any_port(HOST);
  2917. std::thread t([&]() { svr.listen_after_bind(); });
  2918. auto se = detail::scope_exit([&] {
  2919. svr.stop();
  2920. t.join();
  2921. });
  2922. svr.wait_until_ready();
  2923. Client cli(HOST, port);
  2924. cli.set_digest_auth("hello", "world");
  2925. auto res = cli.Get("/x");
  2926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2927. EXPECT_EQ(2, hits.load());
  2928. }
  2929. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2930. static const char *kDigestChallenge =
  2931. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2932. "algorithm=MD5";
  2933. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2934. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2935. "testrealm");
  2936. }
  2937. // Same challenge list with the schemes in the opposite order, to make sure
  2938. // the fix above didn't just special-case "Basic first".
  2939. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2940. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2941. "testrealm");
  2942. }
  2943. // A comma inside a quoted auth-param value must not be mistaken for the
  2944. // separator between two challenges (or two auth-params).
  2945. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2946. run_digest_challenge_list_test(
  2947. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2948. "algorithm=MD5"},
  2949. "test,realm");
  2950. }
  2951. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2952. // make_digest_authentication_header() dereferences both unconditionally, so
  2953. // a server sending a challenge missing either one must not be treated as
  2954. // usable -- doing so used to crash the client with std::out_of_range.
  2955. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2956. Server svr;
  2957. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2958. res.status = StatusCode::Unauthorized_401;
  2959. res.set_header("WWW-Authenticate", challenge);
  2960. });
  2961. auto port = svr.bind_to_any_port(HOST);
  2962. std::thread t([&]() { svr.listen_after_bind(); });
  2963. auto se = detail::scope_exit([&] {
  2964. svr.stop();
  2965. t.join();
  2966. });
  2967. svr.wait_until_ready();
  2968. Client cli(HOST, port);
  2969. cli.set_digest_auth("hello", "world");
  2970. auto res = cli.Get("/x");
  2971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2972. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2973. }
  2974. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2975. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2976. }
  2977. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2978. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2979. }
  2980. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2981. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2982. }
  2983. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2984. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2985. // when storing the values, so the header builder has to re-escape them (and
  2986. // keep algorithm a bare token); otherwise the value breaks out of its
  2987. // quoted-string and injects extra auth-params into the client's Authorization.
  2988. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2989. std::atomic<int> hits{0};
  2990. std::string authorization;
  2991. Server svr;
  2992. svr.Get("/x", [&](const Request &req, Response &res) {
  2993. if (++hits == 1) {
  2994. res.status = StatusCode::Unauthorized_401;
  2995. // On the wire the quotes embedded in the values are backslash-escaped.
  2996. res.set_header("WWW-Authenticate",
  2997. "Digest realm=\"testrealm\", "
  2998. "nonce=\"n\\\"; injected=\\\"x\", "
  2999. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3000. } else {
  3001. authorization = req.get_header_value("Authorization");
  3002. res.set_content("ok", "text/plain");
  3003. }
  3004. });
  3005. auto port = svr.bind_to_any_port(HOST);
  3006. std::thread t([&]() { svr.listen_after_bind(); });
  3007. auto se = detail::scope_exit([&] {
  3008. svr.stop();
  3009. t.join();
  3010. });
  3011. svr.wait_until_ready();
  3012. Client cli(HOST, port);
  3013. cli.set_digest_auth("hello", "world");
  3014. auto res = cli.Get("/x");
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ(2, hits.load());
  3017. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3018. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3019. // inside its quoted-string rather than starting an "injected" auth-param.
  3020. EXPECT_NE(std::string::npos,
  3021. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3022. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3023. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3024. }
  3025. #endif
  3026. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3027. auto host = "google.com";
  3028. auto another_host = "example.com";
  3029. auto wrong_ip = "0.0.0.0";
  3030. #ifdef CPPHTTPLIB_SSL_ENABLED
  3031. SSLClient cli(host);
  3032. #else
  3033. Client cli(host);
  3034. #endif
  3035. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3036. auto res = cli.Get("/");
  3037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3038. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3039. }
  3040. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3041. auto host = "google.com";
  3042. auto wrong_ip = "0.0.0.0";
  3043. #ifdef CPPHTTPLIB_SSL_ENABLED
  3044. SSLClient cli(host);
  3045. #else
  3046. Client cli(host);
  3047. #endif
  3048. cli.set_hostname_addr_map({{host, wrong_ip}});
  3049. auto res = cli.Get("/");
  3050. ASSERT_TRUE(!res);
  3051. EXPECT_EQ(Error::Connection, res.error());
  3052. }
  3053. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3054. // A mapped value that is not an IP literal must be resolved. "localhost"
  3055. // resolves from the hosts file, so this test needs no external DNS.
  3056. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3057. auto host = "target.invalid";
  3058. Server svr;
  3059. std::string received_host;
  3060. svr.Get("/hi", [&](const Request &req, Response &res) {
  3061. received_host = req.get_header_value("Host");
  3062. res.set_content("Hello World!", "text/plain");
  3063. });
  3064. auto port = svr.bind_to_any_port(HOST);
  3065. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3066. auto se = detail::scope_exit([&] {
  3067. svr.stop();
  3068. thread.join();
  3069. ASSERT_FALSE(svr.is_running());
  3070. });
  3071. svr.wait_until_ready();
  3072. Client cli(host, port);
  3073. cli.set_hostname_addr_map({{host, HOST}});
  3074. auto res = cli.Get("/hi");
  3075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3076. EXPECT_EQ(StatusCode::OK_200, res->status);
  3077. // The mapping only redirects the connection; the identity stays host_.
  3078. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3079. }
  3080. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3081. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3082. auto host = "target.invalid";
  3083. Server svr;
  3084. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3085. res.set_content("Hello World!", "text/plain");
  3086. });
  3087. auto port = svr.bind_to_any_port("127.0.0.1");
  3088. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3089. auto se = detail::scope_exit([&] {
  3090. svr.stop();
  3091. thread.join();
  3092. ASSERT_FALSE(svr.is_running());
  3093. });
  3094. svr.wait_until_ready();
  3095. Client cli(host, port);
  3096. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3097. auto res = cli.Get("/hi");
  3098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3099. EXPECT_EQ(StatusCode::OK_200, res->status);
  3100. }
  3101. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3102. // An empty mapped value must leave host_ as the connection target. Without
  3103. // that guard the empty value would become the host argument, getaddrinfo
  3104. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3105. // loopback - silently connecting somewhere the caller never asked for.
  3106. // The server listens on loopback, so such a fallback would succeed and is
  3107. // therefore observable as a failure of this test.
  3108. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3109. Server svr;
  3110. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3111. res.set_content("Hello World!", "text/plain");
  3112. });
  3113. auto port = svr.bind_to_any_port(HOST);
  3114. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3115. auto se = detail::scope_exit([&] {
  3116. svr.stop();
  3117. thread.join();
  3118. ASSERT_FALSE(svr.is_running());
  3119. });
  3120. svr.wait_until_ready();
  3121. Client cli(blackhole, port);
  3122. cli.set_hostname_addr_map({{blackhole, ""}});
  3123. cli.set_connection_timeout(1);
  3124. auto res = cli.Get("/hi");
  3125. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3126. }
  3127. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3128. auto host = "httpbingo.org";
  3129. auto path = std::string{"/absolute-redirect/3"};
  3130. #ifdef CPPHTTPLIB_SSL_ENABLED
  3131. SSLClient cli(host);
  3132. #else
  3133. Client cli(host);
  3134. #endif
  3135. cli.set_follow_location(true);
  3136. auto res = cli.Get(path);
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ(StatusCode::OK_200, res->status);
  3139. }
  3140. TEST(RedirectTest, Redirect_Online) {
  3141. auto host = "httpbingo.org";
  3142. auto path = std::string{"/redirect/3"};
  3143. #ifdef CPPHTTPLIB_SSL_ENABLED
  3144. SSLClient cli(host);
  3145. #else
  3146. Client cli(host);
  3147. #endif
  3148. cli.set_follow_location(true);
  3149. auto res = cli.Get(path);
  3150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3151. EXPECT_EQ(StatusCode::OK_200, res->status);
  3152. }
  3153. TEST(RelativeRedirectTest, Redirect_Online) {
  3154. auto host = "httpbingo.org";
  3155. auto path = std::string{"/relative-redirect/3"};
  3156. #ifdef CPPHTTPLIB_SSL_ENABLED
  3157. SSLClient cli(host);
  3158. #else
  3159. Client cli(host);
  3160. #endif
  3161. cli.set_follow_location(true);
  3162. auto res = cli.Get(path);
  3163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3164. EXPECT_EQ(StatusCode::OK_200, res->status);
  3165. }
  3166. TEST(TooManyRedirectTest, Redirect_Online) {
  3167. auto host = "httpbingo.org";
  3168. auto path = std::string{"/redirect/21"};
  3169. #ifdef CPPHTTPLIB_SSL_ENABLED
  3170. SSLClient cli(host);
  3171. #else
  3172. Client cli(host);
  3173. #endif
  3174. cli.set_follow_location(true);
  3175. auto res = cli.Get(path);
  3176. ASSERT_TRUE(!res);
  3177. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3178. }
  3179. #ifdef CPPHTTPLIB_SSL_ENABLED
  3180. TEST(YahooRedirectTest, Redirect_Online) {
  3181. Client cli("yahoo.com");
  3182. auto res = cli.Get("/");
  3183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3184. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3185. cli.set_follow_location(true);
  3186. res = cli.Get("/");
  3187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3188. EXPECT_EQ(StatusCode::OK_200, res->status);
  3189. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3190. }
  3191. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3192. #define REDIR_HOST "httpbingo.org"
  3193. #define REDIR_PATH "/redirect-to"
  3194. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3195. SSLClient cli(REDIR_HOST);
  3196. cli.set_follow_location(true);
  3197. auto res =
  3198. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3200. EXPECT_EQ(StatusCode::OK_200, res->status);
  3201. }
  3202. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3203. SSLClient cli(REDIR_HOST);
  3204. cli.set_follow_location(true);
  3205. Params params;
  3206. params.emplace("url", "http://example.com");
  3207. params.emplace("status_code", "302");
  3208. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3210. EXPECT_EQ(StatusCode::OK_200, res->status);
  3211. }
  3212. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3213. SSLClient cli(REDIR_HOST);
  3214. cli.set_follow_location(true);
  3215. Params params;
  3216. params.emplace("url", "http://example.com");
  3217. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. }
  3221. TEST(UrlWithSpace, Redirect_Online) {
  3222. SSLClient cli("edge.forgecdn.net");
  3223. cli.set_follow_location(true);
  3224. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3226. EXPECT_EQ(StatusCode::OK_200, res->status);
  3227. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3228. }
  3229. #endif
  3230. #if !defined(_WIN32) && !defined(_WIN64)
  3231. TEST(ReceiveSignals, Signal) {
  3232. auto setupSignalHandlers = []() {
  3233. struct sigaction act;
  3234. sigemptyset(&act.sa_mask);
  3235. act.sa_flags = SA_SIGINFO;
  3236. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3237. switch (sig) {
  3238. case SIGINT:
  3239. default: break;
  3240. }
  3241. };
  3242. ::sigaction(SIGINT, &act, nullptr);
  3243. };
  3244. Server svr;
  3245. int port = 0;
  3246. auto thread = std::thread([&]() {
  3247. setupSignalHandlers();
  3248. port = svr.bind_to_any_port(HOST);
  3249. svr.listen_after_bind();
  3250. });
  3251. auto se = detail::scope_exit([&] {
  3252. svr.stop();
  3253. thread.join();
  3254. ASSERT_FALSE(svr.is_running());
  3255. });
  3256. svr.wait_until_ready();
  3257. ASSERT_TRUE(svr.is_running());
  3258. pthread_kill(thread.native_handle(), SIGINT);
  3259. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3260. ASSERT_TRUE(svr.is_running());
  3261. }
  3262. #endif
  3263. TEST(RedirectToDifferentPort, Redirect) {
  3264. Server svr1;
  3265. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3266. res.set_content("Hello World!", "text/plain");
  3267. });
  3268. int svr1_port = 0;
  3269. auto thread1 = std::thread([&]() {
  3270. svr1_port = svr1.bind_to_any_port(HOST);
  3271. svr1.listen_after_bind();
  3272. });
  3273. Server svr2;
  3274. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3275. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3276. });
  3277. int svr2_port = 0;
  3278. auto thread2 = std::thread([&]() {
  3279. svr2_port = svr2.bind_to_any_port(HOST);
  3280. svr2.listen_after_bind();
  3281. });
  3282. auto se = detail::scope_exit([&] {
  3283. svr2.stop();
  3284. thread2.join();
  3285. svr1.stop();
  3286. thread1.join();
  3287. ASSERT_FALSE(svr2.is_running());
  3288. ASSERT_FALSE(svr1.is_running());
  3289. });
  3290. svr1.wait_until_ready();
  3291. svr2.wait_until_ready();
  3292. Client cli("localhost", svr2_port);
  3293. cli.set_follow_location(true);
  3294. auto res = cli.Get("/2");
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. EXPECT_EQ("Hello World!", res->body);
  3298. }
  3299. // GET /redir on one server redirects to /target on another port, so the
  3300. // client follows it with a new client.
  3301. static Result
  3302. GetThroughRedirectToDifferentPort(Server::Handler target,
  3303. const std::function<void(Client &)> &setup,
  3304. const Headers &headers = Headers()) {
  3305. Server target_svr;
  3306. target_svr.Get("/target", target);
  3307. int target_port = 0;
  3308. auto target_thread = std::thread([&]() {
  3309. target_port = target_svr.bind_to_any_port(HOST);
  3310. target_svr.listen_after_bind();
  3311. });
  3312. Server origin_svr;
  3313. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3314. res.set_redirect(
  3315. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3316. });
  3317. int origin_port = 0;
  3318. auto origin_thread = std::thread([&]() {
  3319. origin_port = origin_svr.bind_to_any_port(HOST);
  3320. origin_svr.listen_after_bind();
  3321. });
  3322. auto se = detail::scope_exit([&] {
  3323. origin_svr.stop();
  3324. origin_thread.join();
  3325. target_svr.stop();
  3326. target_thread.join();
  3327. });
  3328. target_svr.wait_until_ready();
  3329. origin_svr.wait_until_ready();
  3330. Client cli("localhost", origin_port);
  3331. cli.set_follow_location(true);
  3332. setup(cli);
  3333. return cli.Get("/redir", headers);
  3334. }
  3335. static void
  3336. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3337. std::string captured_authorization;
  3338. auto result = GetThroughRedirectToDifferentPort(
  3339. [&](const Request &req, Response &res) {
  3340. captured_authorization = req.get_header_value("Authorization");
  3341. res.set_content("OK", "text/plain");
  3342. },
  3343. set_auth);
  3344. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3345. EXPECT_EQ(StatusCode::OK_200, result->status);
  3346. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3347. EXPECT_TRUE(captured_authorization.empty());
  3348. }
  3349. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3350. TestDoNotForwardCredentialsOnRedirect(
  3351. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3352. }
  3353. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3354. TestDoNotForwardCredentialsOnRedirect(
  3355. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3356. }
  3357. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3358. std::string captured_cookie;
  3359. auto result = GetThroughRedirectToDifferentPort(
  3360. [&](const Request &req, Response &res) {
  3361. captured_cookie = req.get_header_value("Cookie");
  3362. res.set_content("OK", "text/plain");
  3363. },
  3364. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3365. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3366. EXPECT_EQ(StatusCode::OK_200, result->status);
  3367. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3368. EXPECT_TRUE(captured_cookie.empty());
  3369. }
  3370. TEST(RedirectToSamePort, ForwardCookie) {
  3371. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3372. // header so that ordinary session flows keep working.
  3373. Server svr;
  3374. std::string captured_cookie;
  3375. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3376. res.set_redirect("/target", 302);
  3377. });
  3378. svr.Get("/target", [&](const Request &req, Response &res) {
  3379. captured_cookie = req.get_header_value("Cookie");
  3380. res.set_content("OK", "text/plain");
  3381. });
  3382. auto port = svr.bind_to_any_port(HOST);
  3383. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3384. auto se = detail::scope_exit([&] {
  3385. svr.stop();
  3386. thread.join();
  3387. ASSERT_FALSE(svr.is_running());
  3388. });
  3389. svr.wait_until_ready();
  3390. Client cli(HOST, port);
  3391. cli.set_follow_location(true);
  3392. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3393. auto res = cli.Get("/redir", headers);
  3394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3395. EXPECT_EQ(StatusCode::OK_200, res->status);
  3396. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3397. }
  3398. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3399. std::string authorization;
  3400. std::string trace_id;
  3401. auto result = GetThroughRedirectToDifferentPort(
  3402. [&](const Request &req, Response &res) {
  3403. authorization = req.get_header_value("Authorization");
  3404. trace_id = req.get_header_value("X-Trace-Id");
  3405. res.set_content("OK", "text/plain");
  3406. },
  3407. [](Client &cli) {
  3408. cli.set_default_headers(
  3409. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3410. });
  3411. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3412. EXPECT_EQ(StatusCode::OK_200, result->status);
  3413. // Like a header given with the request, a default one goes along unless it
  3414. // carries credentials (RFC 9110 15.4).
  3415. EXPECT_TRUE(authorization.empty());
  3416. EXPECT_EQ("42", trace_id);
  3417. }
  3418. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3419. auto result = GetThroughRedirectToDifferentPort(
  3420. [](const Request &, Response &res) {
  3421. res.set_content(std::string(2048, 'x'), "text/plain");
  3422. },
  3423. [](Client &cli) { cli.set_payload_max_length(1024); });
  3424. EXPECT_FALSE(result);
  3425. }
  3426. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3427. auto result = GetThroughRedirectToDifferentPort(
  3428. [](const Request &req, Response &res) {
  3429. // Answer after a second, or once the client gives up.
  3430. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3431. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3432. }
  3433. res.set_content("late", "text/plain");
  3434. },
  3435. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3436. ASSERT_FALSE(result);
  3437. EXPECT_EQ(Error::Read, result.error());
  3438. }
  3439. #ifdef CPPHTTPLIB_SSL_ENABLED
  3440. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3441. auto result = GetThroughRedirectToDifferentPort(
  3442. [](const Request &, Response &res) {
  3443. res.status = StatusCode::Unauthorized_401;
  3444. res.set_header("WWW-Authenticate",
  3445. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3446. },
  3447. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3448. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3449. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3450. }
  3451. #endif
  3452. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3453. Server svr;
  3454. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3455. // Port number that overflows int — should not crash
  3456. res.set_redirect("http://localhost:99999999999999999999/target");
  3457. });
  3458. auto port = svr.bind_to_any_port(HOST);
  3459. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3460. auto se = detail::scope_exit([&] {
  3461. svr.stop();
  3462. thread.join();
  3463. ASSERT_FALSE(svr.is_running());
  3464. });
  3465. svr.wait_until_ready();
  3466. Client cli(HOST, port);
  3467. cli.set_follow_location(true);
  3468. auto res = cli.Get("/redir");
  3469. // Should fail gracefully, not crash (no valid response due to bad port)
  3470. EXPECT_FALSE(res);
  3471. }
  3472. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3473. Server svr;
  3474. auto port = svr.bind_to_any_port(HOST);
  3475. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3476. // The server's own port followed by junk must not be followed
  3477. res.set_redirect("http://" + std::string(HOST) + ":" +
  3478. std::to_string(port) + "junk/target");
  3479. });
  3480. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3481. res.set_content("target", "text/plain");
  3482. });
  3483. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3484. auto se = detail::scope_exit([&] {
  3485. svr.stop();
  3486. thread.join();
  3487. ASSERT_FALSE(svr.is_running());
  3488. });
  3489. svr.wait_until_ready();
  3490. Client cli(HOST, port);
  3491. cli.set_follow_location(true);
  3492. auto res = cli.Get("/redir");
  3493. EXPECT_FALSE(res);
  3494. }
  3495. TEST(RedirectFromPageWithContent, Redirect) {
  3496. Server svr;
  3497. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3498. res.set_content("___", "text/plain");
  3499. res.set_redirect("/2");
  3500. });
  3501. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3502. res.set_content("Hello World!", "text/plain");
  3503. });
  3504. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3505. auto se = detail::scope_exit([&] {
  3506. svr.stop();
  3507. th.join();
  3508. ASSERT_FALSE(svr.is_running());
  3509. });
  3510. svr.wait_until_ready();
  3511. {
  3512. Client cli("localhost", PORT);
  3513. cli.set_follow_location(true);
  3514. std::string body;
  3515. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3516. body.append(data, data_length);
  3517. return true;
  3518. });
  3519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3520. EXPECT_EQ(StatusCode::OK_200, res->status);
  3521. EXPECT_EQ("Hello World!", body);
  3522. }
  3523. {
  3524. Client cli("localhost", PORT);
  3525. std::string body;
  3526. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3527. body.append(data, data_length);
  3528. return true;
  3529. });
  3530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3531. EXPECT_EQ(StatusCode::Found_302, res->status);
  3532. EXPECT_EQ("___", body);
  3533. }
  3534. }
  3535. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3536. Server svr;
  3537. auto port_str = std::to_string(PORT);
  3538. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3539. auto expected_host = "[::1]:" + port_str;
  3540. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3541. res.set_content("___", "text/plain");
  3542. // res.set_redirect("/2");
  3543. res.set_redirect(redirect_url);
  3544. });
  3545. svr.Get("/2", [&](const Request &req, Response &res) {
  3546. auto host_header = req.headers.find("Host");
  3547. ASSERT_TRUE(host_header != req.headers.end());
  3548. EXPECT_EQ(expected_host, host_header->second);
  3549. res.set_content("Hello World!", "text/plain");
  3550. });
  3551. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3552. auto se = detail::scope_exit([&] {
  3553. svr.stop();
  3554. th.join();
  3555. ASSERT_FALSE(svr.is_running());
  3556. });
  3557. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3558. // actually starts anything, so the condition !svr.is_running() will
  3559. // always remain true, and the loop never stops.
  3560. // This basically counts how many milliseconds have passed since the
  3561. // call to svr.listen(), and if after 5 seconds nothing started yet
  3562. // aborts the test.
  3563. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3564. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3565. ASSERT_LT(milliseconds, 5000U);
  3566. }
  3567. {
  3568. Client cli("::1", PORT);
  3569. cli.set_follow_location(true);
  3570. std::string body;
  3571. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3572. body.append(data, data_length);
  3573. return true;
  3574. });
  3575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3576. EXPECT_EQ(StatusCode::OK_200, res->status);
  3577. EXPECT_EQ("Hello World!", body);
  3578. }
  3579. {
  3580. Client cli("::1", PORT);
  3581. std::string body;
  3582. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3583. body.append(data, data_length);
  3584. return true;
  3585. });
  3586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3587. EXPECT_EQ(StatusCode::Found_302, res->status);
  3588. EXPECT_EQ("___", body);
  3589. }
  3590. }
  3591. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3592. Server svr;
  3593. svr.Get("/foo", [](const Request &req, Response &res) {
  3594. auto a = req.params.find("a");
  3595. if (a != req.params.end()) {
  3596. res.set_content((*a).second, "text/plain");
  3597. res.status = StatusCode::OK_200;
  3598. } else {
  3599. res.status = StatusCode::BadRequest_400;
  3600. }
  3601. });
  3602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3603. auto se = detail::scope_exit([&] {
  3604. svr.stop();
  3605. thread.join();
  3606. ASSERT_FALSE(svr.is_running());
  3607. });
  3608. svr.wait_until_ready();
  3609. {
  3610. Client cli(HOST, PORT);
  3611. cli.set_path_encode(false);
  3612. auto res = cli.Get("/foo?a=explicitly+encoded");
  3613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3614. EXPECT_EQ(StatusCode::OK_200, res->status);
  3615. // This expects it back with a space, as the `+` won't have been
  3616. // url-encoded, and server-side the params get decoded turning `+`
  3617. // into spaces.
  3618. EXPECT_EQ("explicitly encoded", res->body);
  3619. }
  3620. }
  3621. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3622. // When path encoding is disabled the client must transmit the supplied
  3623. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3624. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3625. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3626. // than a space (0x20). Assert on the raw wire target to catch this.
  3627. Server svr;
  3628. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3629. svr.Get("/foo", [&](const Request &req, Response &res) {
  3630. EXPECT_EQ(expected_target, req.target);
  3631. res.status = StatusCode::OK_200;
  3632. });
  3633. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3634. auto se = detail::scope_exit([&] {
  3635. svr.stop();
  3636. thread.join();
  3637. ASSERT_FALSE(svr.is_running());
  3638. });
  3639. svr.wait_until_ready();
  3640. {
  3641. Client cli(HOST, PORT);
  3642. cli.set_path_encode(false);
  3643. auto res = cli.Get(expected_target.c_str());
  3644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3645. EXPECT_EQ(StatusCode::OK_200, res->status);
  3646. }
  3647. }
  3648. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3649. // `open_stream()` used to skip the path encoding that the buffered send
  3650. // path applies, so the same `path` produced different bytes in the request
  3651. // line depending on which API was used. Assert the two agree.
  3652. Server svr;
  3653. std::string target;
  3654. svr.Get(".*", [&](const Request &req, Response &res) {
  3655. target = req.target;
  3656. res.status = StatusCode::OK_200;
  3657. });
  3658. auto port = svr.bind_to_any_port(HOST);
  3659. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3660. auto se = detail::scope_exit([&] {
  3661. svr.stop();
  3662. thread.join();
  3663. ASSERT_FALSE(svr.is_running());
  3664. });
  3665. svr.wait_until_ready();
  3666. struct {
  3667. const char *path;
  3668. const char *expected;
  3669. } cases[] = {
  3670. {"/a b?x=1", "/a%20b?x=1"},
  3671. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3672. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3673. };
  3674. for (const auto &c : cases) {
  3675. Client cli(HOST, port);
  3676. target.clear();
  3677. auto res = cli.Get(c.path);
  3678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3679. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3680. auto buffered_target = target;
  3681. target.clear();
  3682. auto handle = cli.open_stream("GET", c.path);
  3683. EXPECT_TRUE(handle.is_valid())
  3684. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3685. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3686. }
  3687. }
  3688. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3689. // The `set_path_encode(false)` contract — transmit the supplied target
  3690. // verbatim — must hold for the streaming API too.
  3691. Server svr;
  3692. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3693. std::string target;
  3694. svr.Get("/foo", [&](const Request &req, Response &res) {
  3695. target = req.target;
  3696. res.status = StatusCode::OK_200;
  3697. });
  3698. auto port = svr.bind_to_any_port(HOST);
  3699. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3700. auto se = detail::scope_exit([&] {
  3701. svr.stop();
  3702. thread.join();
  3703. ASSERT_FALSE(svr.is_running());
  3704. });
  3705. svr.wait_until_ready();
  3706. {
  3707. Client cli(HOST, port);
  3708. cli.set_path_encode(false);
  3709. auto handle = cli.open_stream("GET", expected_target);
  3710. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3711. EXPECT_EQ(expected_target, target);
  3712. }
  3713. }
  3714. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3715. // With path encoding enabled a CR/LF in the target is percent-encoded
  3716. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3717. // write_request_line still backstops `set_path_encode(false)`, which is
  3718. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3719. Server svr;
  3720. // Captured before routing: the decoded path contains a newline, which a
  3721. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3722. std::string target;
  3723. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3724. target = req.target;
  3725. res.status = StatusCode::OK_200;
  3726. return Server::HandlerResponse::Handled;
  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. {
  3737. Client cli(HOST, port);
  3738. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3739. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3740. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3741. }
  3742. }
  3743. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3744. // Every control character is percent-encoded, not just CR/LF, so the target
  3745. // passes the request-target check in write_request_line.
  3746. Server svr;
  3747. std::string target;
  3748. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3749. target = req.target;
  3750. res.status = StatusCode::OK_200;
  3751. return Server::HandlerResponse::Handled;
  3752. });
  3753. auto port = svr.bind_to_any_port(HOST);
  3754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3755. auto se = detail::scope_exit([&] {
  3756. svr.stop();
  3757. thread.join();
  3758. ASSERT_FALSE(svr.is_running());
  3759. });
  3760. svr.wait_until_ready();
  3761. {
  3762. Client cli(HOST, port);
  3763. auto res = cli.Get("/a\tb\x1b\x7f");
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. EXPECT_EQ("/a%09b%1B%7F", target);
  3766. }
  3767. }
  3768. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3769. // Nothing may reach the wire: a raw CR/LF target would split the request
  3770. // line and inject headers.
  3771. Server svr;
  3772. // Pre-routing so that "not called" means nothing reached the server at all,
  3773. // rather than merely failing to match a handler pattern.
  3774. auto handler_called = false;
  3775. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3776. handler_called = true;
  3777. res.status = StatusCode::OK_200;
  3778. return Server::HandlerResponse::Handled;
  3779. });
  3780. auto port = svr.bind_to_any_port(HOST);
  3781. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3782. auto se = detail::scope_exit([&] {
  3783. svr.stop();
  3784. thread.join();
  3785. ASSERT_FALSE(svr.is_running());
  3786. });
  3787. svr.wait_until_ready();
  3788. {
  3789. Client cli(HOST, port);
  3790. cli.set_path_encode(false);
  3791. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3792. EXPECT_FALSE(handle.is_valid());
  3793. EXPECT_EQ(Error::Write, handle.error);
  3794. EXPECT_FALSE(handler_called);
  3795. }
  3796. }
  3797. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3798. // Which of the two branches runs is decided by whether the query component
  3799. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3800. // an empty query and must still fall back to building one from
  3801. // `req.params`, while a non-empty query must win over `req.params`.
  3802. Server svr;
  3803. std::string target;
  3804. svr.Get("/foo", [&](const Request &req, Response &res) {
  3805. target = req.target;
  3806. res.status = StatusCode::OK_200;
  3807. });
  3808. auto port = svr.bind_to_any_port(HOST);
  3809. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. {
  3817. // Trailing `?` -> empty query component -> `req.params` is used.
  3818. Client cli(HOST, port);
  3819. Request req;
  3820. req.method = "GET";
  3821. req.path = "/foo?";
  3822. req.params.emplace("a", "1");
  3823. target.clear();
  3824. auto res = cli.send(req);
  3825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3826. EXPECT_EQ("/foo?a=1", target);
  3827. }
  3828. {
  3829. // Non-empty query in `req.path` -> `req.params` is not appended.
  3830. Client cli(HOST, port);
  3831. Request req;
  3832. req.method = "GET";
  3833. req.path = "/foo?b=2";
  3834. req.params.emplace("a", "1");
  3835. target.clear();
  3836. auto res = cli.send(req);
  3837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3838. EXPECT_EQ("/foo?b=2", target);
  3839. }
  3840. }
  3841. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3842. Server svr;
  3843. svr.Get("/", [](const Request &req, Response &) {
  3844. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3845. });
  3846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3847. auto se = detail::scope_exit([&] {
  3848. svr.stop();
  3849. thread.join();
  3850. ASSERT_FALSE(svr.is_running());
  3851. });
  3852. svr.wait_until_ready();
  3853. {
  3854. Client cli(HOST, PORT);
  3855. cli.set_path_encode(false);
  3856. auto res = cli.Get("/?something=%0A");
  3857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3858. EXPECT_EQ(StatusCode::OK_200, res->status);
  3859. }
  3860. }
  3861. TEST(BindServerTest, BindDualStack) {
  3862. Server svr;
  3863. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3864. res.set_content("Hello World!", "text/plain");
  3865. });
  3866. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3867. auto se = detail::scope_exit([&] {
  3868. svr.stop();
  3869. thread.join();
  3870. ASSERT_FALSE(svr.is_running());
  3871. });
  3872. svr.wait_until_ready();
  3873. {
  3874. Client cli("127.0.0.1", PORT);
  3875. auto res = cli.Get("/1");
  3876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3877. EXPECT_EQ(StatusCode::OK_200, res->status);
  3878. EXPECT_EQ("Hello World!", res->body);
  3879. }
  3880. {
  3881. Client cli("::1", PORT);
  3882. auto res = cli.Get("/1");
  3883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3884. EXPECT_EQ(StatusCode::OK_200, res->status);
  3885. EXPECT_EQ("Hello World!", res->body);
  3886. }
  3887. }
  3888. TEST(BindServerTest, BindAndListenSeparately) {
  3889. Server svr;
  3890. int port = svr.bind_to_any_port("0.0.0.0");
  3891. ASSERT_TRUE(svr.is_valid());
  3892. ASSERT_TRUE(port > 0);
  3893. svr.stop();
  3894. }
  3895. // Reports whether anything is still listening on a loopback port. A plain
  3896. // connect() is used instead of a Client request because a socket left bound by
  3897. // mistake accepts the connection into its backlog and never answers, which
  3898. // would hang the test instead of failing it.
  3899. static bool is_loopback_port_accepting(int port) {
  3900. sockaddr_in addr{};
  3901. addr.sin_family = AF_INET;
  3902. addr.sin_port = htons(static_cast<uint16_t>(port));
  3903. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3904. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3905. EXPECT_NE(sock, INVALID_SOCKET);
  3906. if (sock == INVALID_SOCKET) { return false; }
  3907. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3908. static_cast<socklen_t>(sizeof(addr)));
  3909. detail::close_socket(sock);
  3910. return ret == 0;
  3911. }
  3912. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3913. Server svr;
  3914. auto port = svr.bind_to_any_port("127.0.0.1");
  3915. ASSERT_TRUE(port > 0);
  3916. svr.stop();
  3917. // bind_to_any_port() already called listen(2), so until stop() closed the
  3918. // descriptor the port kept accepting connections into the backlog. ASSERT
  3919. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3920. // below blocks forever in the accept loop.
  3921. ASSERT_FALSE(is_loopback_port_accepting(port));
  3922. // Nothing is left to accept on, so listen_after_bind() must report failure
  3923. // instead of returning success without ever serving.
  3924. EXPECT_FALSE(svr.listen_after_bind());
  3925. // The failed listen marks the server decommissioned, so a waiter returns
  3926. // instead of spinning forever.
  3927. svr.wait_until_ready();
  3928. }
  3929. #ifdef CPPHTTPLIB_SSL_ENABLED
  3930. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3931. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3932. CLIENT_CA_CERT_DIR);
  3933. int port = svr.bind_to_any_port("0.0.0.0");
  3934. ASSERT_TRUE(svr.is_valid());
  3935. ASSERT_TRUE(port > 0);
  3936. svr.stop();
  3937. }
  3938. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3939. // or a rejected CustomRoute() registration would not stop the server binding.
  3940. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3942. CLIENT_CA_CERT_DIR);
  3943. ASSERT_TRUE(svr.is_valid());
  3944. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3945. EXPECT_FALSE(svr.is_valid());
  3946. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3947. }
  3948. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3949. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3950. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3951. int port = svr.bind_to_any_port("0.0.0.0");
  3952. ASSERT_TRUE(svr.is_valid());
  3953. ASSERT_TRUE(port > 0);
  3954. svr.stop();
  3955. }
  3956. TEST(BindServerTest, UpdateCertsPem) {
  3957. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3958. int port = svr.bind_to_any_port("0.0.0.0");
  3959. ASSERT_TRUE(svr.is_valid());
  3960. ASSERT_TRUE(port > 0);
  3961. // Read PEM files
  3962. std::string cert_pem, key_pem, ca_pem;
  3963. read_file(SERVER_CERT_FILE, cert_pem);
  3964. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3965. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3966. // Update server certificates using PEM API
  3967. ASSERT_TRUE(
  3968. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3969. ASSERT_TRUE(svr.is_valid());
  3970. svr.stop();
  3971. }
  3972. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3973. // Start server with client CA (enables client auth)
  3974. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3975. ASSERT_TRUE(svr.is_valid());
  3976. bool handler_called = false;
  3977. svr.Get("/test", [&](const Request &req, Response &res) {
  3978. handler_called = true;
  3979. // Verify client certificate is present
  3980. auto cert = req.peer_cert();
  3981. EXPECT_TRUE(static_cast<bool>(cert));
  3982. res.set_content("ok", "text/plain");
  3983. });
  3984. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3985. auto se = detail::scope_exit([&] {
  3986. svr.stop();
  3987. t.join();
  3988. ASSERT_FALSE(svr.is_running());
  3989. });
  3990. svr.wait_until_ready();
  3991. // Read PEM files
  3992. std::string cert_pem, key_pem, ca_pem;
  3993. read_file(SERVER_CERT_FILE, cert_pem);
  3994. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3995. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3996. // Update server certificates and client CA using PEM API while server running
  3997. ASSERT_TRUE(
  3998. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3999. // Connect with client certificate
  4000. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4001. cli.enable_server_certificate_verification(false);
  4002. cli.set_connection_timeout(30);
  4003. auto res = cli.Get("/test");
  4004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4005. ASSERT_EQ(StatusCode::OK_200, res->status);
  4006. ASSERT_TRUE(handler_called);
  4007. EXPECT_EQ("ok", res->body);
  4008. }
  4009. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4011. ASSERT_TRUE(svr.is_valid());
  4012. svr.Get("/test", [](const Request &, Response &res) {
  4013. res.set_content("ok", "text/plain");
  4014. });
  4015. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4016. auto se = detail::scope_exit([&] {
  4017. svr.stop();
  4018. t.join();
  4019. ASSERT_FALSE(svr.is_running());
  4020. });
  4021. svr.wait_until_ready();
  4022. auto get = [] {
  4023. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4024. cli.enable_server_certificate_verification(false);
  4025. return cli.Get("/test");
  4026. };
  4027. ASSERT_TRUE(get());
  4028. // A CA that did not sign the client's certificate takes the old one's place.
  4029. std::string cert_pem, key_pem, ca_pem;
  4030. read_file(SERVER_CERT_FILE, cert_pem);
  4031. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4032. read_file(SERVER_CERT2_FILE, ca_pem);
  4033. ASSERT_TRUE(
  4034. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4035. EXPECT_FALSE(get());
  4036. }
  4037. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4038. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4039. ASSERT_TRUE(svr.is_valid());
  4040. svr.Get("/test", [](const Request &, Response &res) {
  4041. res.set_content("ok", "text/plain");
  4042. });
  4043. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4044. auto se = detail::scope_exit([&] {
  4045. svr.stop();
  4046. t.join();
  4047. ASSERT_FALSE(svr.is_running());
  4048. });
  4049. svr.wait_until_ready();
  4050. // A connection that sends no ClientHello keeps its handshake in progress,
  4051. // once the server has had a moment to start it.
  4052. auto error = Error::Success;
  4053. auto sock = detail::create_client_socket(
  4054. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4055. /*connection_timeout_sec=*/5, 0,
  4056. /*read_timeout_sec=*/5, 0,
  4057. /*write_timeout_sec=*/5, 0, std::string(), error);
  4058. ASSERT_NE(INVALID_SOCKET, sock);
  4059. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4060. std::string cert_pem, key_pem;
  4061. read_file(SERVER_CERT_FILE, cert_pem);
  4062. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4063. auto update = std::async(std::launch::async, [&]() {
  4064. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4065. });
  4066. EXPECT_EQ(std::future_status::timeout,
  4067. update.wait_for(std::chrono::milliseconds(200)));
  4068. detail::close_socket(sock);
  4069. EXPECT_TRUE(update.get());
  4070. SSLClient cli(HOST, PORT);
  4071. cli.enable_server_certificate_verification(false);
  4072. auto res = cli.Get("/test");
  4073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4074. EXPECT_EQ(StatusCode::OK_200, res->status);
  4075. }
  4076. #endif
  4077. TEST(ErrorHandlerTest, ContentLength) {
  4078. Server svr;
  4079. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4080. res.status = StatusCode::OK_200;
  4081. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4082. "text/html"); // <= Content-Length still 13
  4083. });
  4084. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4085. res.set_content("Hello World!\n", "text/plain");
  4086. res.status = 524;
  4087. });
  4088. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4089. auto se = detail::scope_exit([&] {
  4090. svr.stop();
  4091. thread.join();
  4092. ASSERT_FALSE(svr.is_running());
  4093. });
  4094. svr.wait_until_ready();
  4095. {
  4096. Client cli(HOST, PORT);
  4097. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4099. EXPECT_EQ(StatusCode::OK_200, res->status);
  4100. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4101. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4102. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4103. }
  4104. }
  4105. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4106. TEST(ExceptionTest, WithoutExceptionHandler) {
  4107. Server svr;
  4108. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4109. throw std::runtime_error("exception...");
  4110. });
  4111. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4112. throw std::runtime_error("exception\r\n...");
  4113. });
  4114. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4115. auto se = detail::scope_exit([&] {
  4116. svr.stop();
  4117. listen_thread.join();
  4118. ASSERT_FALSE(svr.is_running());
  4119. });
  4120. svr.wait_until_ready();
  4121. Client cli("localhost", PORT);
  4122. {
  4123. auto res = cli.Get("/exception");
  4124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4125. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4126. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4127. }
  4128. {
  4129. auto res = cli.Get("/unknown");
  4130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4131. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4132. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4133. }
  4134. }
  4135. TEST(ExceptionTest, WithExceptionHandler) {
  4136. Server svr;
  4137. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4138. std::exception_ptr ep) {
  4139. EXPECT_FALSE(ep == nullptr);
  4140. try {
  4141. std::rethrow_exception(ep);
  4142. } catch (std::exception &e) {
  4143. EXPECT_EQ("abc", std::string(e.what()));
  4144. } catch (...) {}
  4145. res.status = StatusCode::InternalServerError_500;
  4146. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4147. "text/html"); // <= Content-Length still 13 at this point
  4148. });
  4149. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4150. res.set_content("Hello World!\n", "text/plain");
  4151. throw std::runtime_error("abc");
  4152. });
  4153. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4154. auto se = detail::scope_exit([&] {
  4155. svr.stop();
  4156. thread.join();
  4157. ASSERT_FALSE(svr.is_running());
  4158. });
  4159. svr.wait_until_ready();
  4160. for (size_t i = 0; i < 10; i++) {
  4161. Client cli(HOST, PORT);
  4162. for (size_t j = 0; j < 100; j++) {
  4163. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4165. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4166. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4167. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4168. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4169. }
  4170. cli.set_keep_alive(true);
  4171. for (size_t j = 0; j < 100; j++) {
  4172. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4174. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4175. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4176. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4177. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4178. }
  4179. }
  4180. }
  4181. TEST(ExceptionTest, AndErrorHandler) {
  4182. Server svr;
  4183. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4184. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4185. });
  4186. svr.set_exception_handler(
  4187. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4188. EXPECT_FALSE(ep == nullptr);
  4189. try {
  4190. std::rethrow_exception(ep);
  4191. } catch (std::exception &e) {
  4192. res.set_content(e.what(), "text/html");
  4193. } catch (...) {}
  4194. res.status = StatusCode::InternalServerError_500;
  4195. });
  4196. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4197. throw std::runtime_error("EXCEPTION");
  4198. });
  4199. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4200. res.set_content("ERROR", "text/html");
  4201. res.status = StatusCode::InternalServerError_500;
  4202. });
  4203. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4204. auto se = detail::scope_exit([&] {
  4205. svr.stop();
  4206. thread.join();
  4207. ASSERT_FALSE(svr.is_running());
  4208. });
  4209. svr.wait_until_ready();
  4210. Client cli(HOST, PORT);
  4211. {
  4212. auto res = cli.Get("/exception");
  4213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4214. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4215. EXPECT_EQ("EXCEPTION", res->body);
  4216. }
  4217. {
  4218. auto res = cli.Get("/error");
  4219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4220. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4221. EXPECT_EQ("ERROR", res->body);
  4222. }
  4223. {
  4224. auto res = cli.Get("/invalid");
  4225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4226. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4227. EXPECT_EQ("NOT_FOUND", res->body);
  4228. }
  4229. }
  4230. #endif
  4231. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4232. // process_request() wraps only routing() in a try/catch, so an exception from
  4233. // any other user callback used to unwind into the task queue - which does not
  4234. // catch - and terminate the process. Each test below runs the server on a
  4235. // single worker thread: a guard that catches the exception but still loses the
  4236. // thread would otherwise be hidden by a spare worker serving the follow-up
  4237. // request. Note that a regression here aborts the whole test binary rather
  4238. // than failing one test.
  4239. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4240. Server svr;
  4241. svr.new_task_queue = [] { return new ThreadPool(1); };
  4242. std::atomic<int> reported{0};
  4243. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4244. if (err == Error::UserCallbackException) { reported++; }
  4245. });
  4246. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4247. res.set_content_provider(
  4248. 1024, "text/plain",
  4249. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4250. sink.write("hello", 5);
  4251. throw std::runtime_error("from the content provider");
  4252. });
  4253. });
  4254. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4255. res.set_content("ok", "text/plain");
  4256. });
  4257. auto port = svr.bind_to_any_port(HOST);
  4258. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4259. auto se = detail::scope_exit([&] {
  4260. svr.stop();
  4261. listen_thread.join();
  4262. ASSERT_FALSE(svr.is_running());
  4263. });
  4264. svr.wait_until_ready();
  4265. {
  4266. Client cli(HOST, port);
  4267. cli.set_read_timeout(5, 0);
  4268. EXPECT_FALSE(cli.Get("/throw"));
  4269. }
  4270. EXPECT_TRUE(svr.is_running());
  4271. EXPECT_EQ(1, reported.load());
  4272. // A request on a fresh connection is still served.
  4273. {
  4274. Client cli(HOST, port);
  4275. auto res = cli.Get("/ok");
  4276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4277. EXPECT_EQ(StatusCode::OK_200, res->status);
  4278. EXPECT_EQ("ok", res->body);
  4279. }
  4280. }
  4281. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4282. Server svr;
  4283. svr.new_task_queue = [] { return new ThreadPool(1); };
  4284. std::atomic<bool> should_throw{true};
  4285. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4286. res.set_content("hi", "text/plain");
  4287. });
  4288. svr.set_post_routing_handler(
  4289. [&](const Request & /*req*/, Response & /*res*/) {
  4290. if (should_throw) {
  4291. throw std::runtime_error("from the post-routing handler");
  4292. }
  4293. });
  4294. auto port = svr.bind_to_any_port(HOST);
  4295. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4296. auto se = detail::scope_exit([&] {
  4297. svr.stop();
  4298. listen_thread.join();
  4299. ASSERT_FALSE(svr.is_running());
  4300. });
  4301. svr.wait_until_ready();
  4302. {
  4303. Client cli(HOST, port);
  4304. cli.set_read_timeout(5, 0);
  4305. EXPECT_FALSE(cli.Get("/hi"));
  4306. }
  4307. EXPECT_TRUE(svr.is_running());
  4308. should_throw = false;
  4309. {
  4310. Client cli(HOST, port);
  4311. auto res = cli.Get("/hi");
  4312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4313. EXPECT_EQ(StatusCode::OK_200, res->status);
  4314. EXPECT_EQ("hi", res->body);
  4315. }
  4316. }
  4317. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4318. // The guard reports the caught exception through the error logger, which is
  4319. // a user callback too. A logger that throws has to be contained as well, or
  4320. // the process would terminate from inside the catch.
  4321. Server svr;
  4322. svr.new_task_queue = [] { return new ThreadPool(1); };
  4323. std::atomic<int> reported{0};
  4324. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4325. if (err == Error::UserCallbackException) {
  4326. reported++;
  4327. throw std::runtime_error("from the error logger");
  4328. }
  4329. });
  4330. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4331. res.set_content_provider(
  4332. 1024, "text/plain",
  4333. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4334. sink.write("hello", 5);
  4335. throw std::runtime_error("from the content provider");
  4336. });
  4337. });
  4338. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4339. res.set_content("ok", "text/plain");
  4340. });
  4341. auto port = svr.bind_to_any_port(HOST);
  4342. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4343. auto se = detail::scope_exit([&] {
  4344. svr.stop();
  4345. listen_thread.join();
  4346. ASSERT_FALSE(svr.is_running());
  4347. });
  4348. svr.wait_until_ready();
  4349. {
  4350. Client cli(HOST, port);
  4351. cli.set_read_timeout(5, 0);
  4352. EXPECT_FALSE(cli.Get("/throw"));
  4353. }
  4354. EXPECT_TRUE(svr.is_running());
  4355. EXPECT_EQ(1, reported.load());
  4356. {
  4357. Client cli(HOST, port);
  4358. auto res = cli.Get("/ok");
  4359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4360. EXPECT_EQ(StatusCode::OK_200, res->status);
  4361. EXPECT_EQ("ok", res->body);
  4362. }
  4363. }
  4364. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4365. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4366. // so the exception unwinds through the ws::WebSocket object on its way to
  4367. // the guard. None of the HTTP cases above cross that.
  4368. Server svr;
  4369. svr.new_task_queue = [] { return new ThreadPool(1); };
  4370. std::atomic<int> reported{0};
  4371. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4372. if (err == Error::UserCallbackException) { reported++; }
  4373. });
  4374. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4375. throw std::runtime_error("from the WebSocket handler");
  4376. });
  4377. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4378. res.set_content("ok", "text/plain");
  4379. });
  4380. auto port = svr.bind_to_any_port(HOST);
  4381. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4382. auto se = detail::scope_exit([&] {
  4383. svr.stop();
  4384. listen_thread.join();
  4385. ASSERT_FALSE(svr.is_running());
  4386. });
  4387. svr.wait_until_ready();
  4388. {
  4389. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4390. "/ws");
  4391. auto res = client.connect();
  4392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4393. // The server dropped the connection instead of dying.
  4394. std::string msg;
  4395. EXPECT_FALSE(client.read(msg));
  4396. client.close();
  4397. }
  4398. EXPECT_TRUE(svr.is_running());
  4399. EXPECT_EQ(1, reported.load());
  4400. {
  4401. Client cli(HOST, port);
  4402. auto res = cli.Get("/ok");
  4403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4404. EXPECT_EQ(StatusCode::OK_200, res->status);
  4405. EXPECT_EQ("ok", res->body);
  4406. }
  4407. }
  4408. #ifdef CPPHTTPLIB_SSL_ENABLED
  4409. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4410. // SSLServer::process_and_close_socket() is a separate overload with its own
  4411. // guard, so it is exercised on its own.
  4412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4413. ASSERT_TRUE(svr.is_valid());
  4414. svr.new_task_queue = [] { return new ThreadPool(1); };
  4415. std::atomic<int> reported{0};
  4416. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4417. if (err == Error::UserCallbackException) { reported++; }
  4418. });
  4419. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4420. res.set_content_provider(
  4421. 1024, "text/plain",
  4422. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4423. sink.write("hello", 5);
  4424. throw std::runtime_error("from the content provider");
  4425. });
  4426. });
  4427. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4428. res.set_content("ok", "text/plain");
  4429. });
  4430. auto port = svr.bind_to_any_port(HOST);
  4431. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4432. auto se = detail::scope_exit([&] {
  4433. svr.stop();
  4434. listen_thread.join();
  4435. ASSERT_FALSE(svr.is_running());
  4436. });
  4437. svr.wait_until_ready();
  4438. {
  4439. SSLClient cli(HOST, port);
  4440. cli.enable_server_certificate_verification(false);
  4441. cli.set_read_timeout(5, 0);
  4442. EXPECT_FALSE(cli.Get("/throw"));
  4443. }
  4444. EXPECT_TRUE(svr.is_running());
  4445. EXPECT_EQ(1, reported.load());
  4446. {
  4447. SSLClient cli(HOST, port);
  4448. cli.enable_server_certificate_verification(false);
  4449. auto res = cli.Get("/ok");
  4450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4451. EXPECT_EQ(StatusCode::OK_200, res->status);
  4452. EXPECT_EQ("ok", res->body);
  4453. }
  4454. }
  4455. #endif
  4456. #endif
  4457. TEST(NoContentTest, ContentLength) {
  4458. Server svr;
  4459. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4460. res.status = StatusCode::NoContent_204;
  4461. });
  4462. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4463. auto se = detail::scope_exit([&] {
  4464. svr.stop();
  4465. thread.join();
  4466. ASSERT_FALSE(svr.is_running());
  4467. });
  4468. svr.wait_until_ready();
  4469. {
  4470. Client cli(HOST, PORT);
  4471. auto res = cli.Get("/hi");
  4472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4473. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4474. // RFC 9110 8.6: none in a 204 response
  4475. EXPECT_FALSE(res->has_header("Content-Length"));
  4476. }
  4477. }
  4478. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4479. Server svr;
  4480. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4481. res.set_header("Content-Length", "5");
  4482. res.set_content("hello world", "text/plain");
  4483. });
  4484. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4485. // A body that reads as the last chunk, were it taken as chunked
  4486. res.set_header("Transfer-Encoding", "chunked");
  4487. res.set_content("0\r\n\r\n", "text/plain");
  4488. });
  4489. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4490. res.set_header("Content-Length", "2");
  4491. res.set_content_provider(5, "text/plain",
  4492. [](size_t offset, size_t length, DataSink &sink) {
  4493. sink.write(&"hello"[offset], length);
  4494. return true;
  4495. });
  4496. });
  4497. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4498. res.set_header("Content-Length", "1234");
  4499. });
  4500. thread t = thread([&] { svr.listen(HOST, PORT); });
  4501. auto se = detail::scope_exit([&] {
  4502. svr.stop();
  4503. t.join();
  4504. ASSERT_FALSE(svr.is_running());
  4505. });
  4506. svr.wait_until_ready();
  4507. Client cli(HOST, PORT);
  4508. cli.set_read_timeout(1, 0);
  4509. auto expect_body = [&](const Result &res, const std::string &body) {
  4510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4511. EXPECT_EQ(body, res->body);
  4512. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4513. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4514. };
  4515. Headers identity{{"Accept-Encoding", ""}};
  4516. expect_body(cli.Get("/body", identity), "hello world");
  4517. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4518. expect_body(cli.Get("/body",
  4519. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4520. "he");
  4521. expect_body(cli.Get("/provider", identity), "hello");
  4522. expect_body(cli.Get("/empty", identity), "");
  4523. // A HEAD response may give the length of the body a GET would get.
  4524. auto res = cli.Head("/empty");
  4525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4526. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4527. }
  4528. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4529. Server svr;
  4530. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4531. res.set_content("short", "text/plain");
  4532. });
  4533. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4534. res.body += " with a footer";
  4535. res.set_header("Transfer-Encoding", "chunked");
  4536. });
  4537. thread t = thread([&] { svr.listen(HOST, PORT); });
  4538. auto se = detail::scope_exit([&] {
  4539. svr.stop();
  4540. t.join();
  4541. ASSERT_FALSE(svr.is_running());
  4542. });
  4543. svr.wait_until_ready();
  4544. Client cli(HOST, PORT);
  4545. cli.set_read_timeout(1, 0);
  4546. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4548. EXPECT_EQ("short with a footer", res->body);
  4549. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4550. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4551. }
  4552. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4553. #ifdef CPPHTTPLIB_SSL_ENABLED
  4554. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4555. ASSERT_TRUE(svr.is_valid());
  4556. #else
  4557. Server svr;
  4558. #endif
  4559. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4560. if (req.path == "/routing_handler") {
  4561. res.set_header("PRE_ROUTING", "on");
  4562. res.set_content("Routing Handler", "text/plain");
  4563. return httplib::Server::HandlerResponse::Handled;
  4564. }
  4565. return httplib::Server::HandlerResponse::Unhandled;
  4566. });
  4567. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4568. res.set_content("Error", "text/html");
  4569. });
  4570. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4571. if (req.path == "/routing_handler") {
  4572. res.set_header("POST_ROUTING", "on");
  4573. }
  4574. });
  4575. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4576. res.set_content("Hello World!\n", "text/plain");
  4577. });
  4578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4579. auto se = detail::scope_exit([&] {
  4580. svr.stop();
  4581. thread.join();
  4582. ASSERT_FALSE(svr.is_running());
  4583. });
  4584. svr.wait_until_ready();
  4585. {
  4586. #ifdef CPPHTTPLIB_SSL_ENABLED
  4587. SSLClient cli(HOST, PORT);
  4588. cli.enable_server_certificate_verification(false);
  4589. #else
  4590. Client cli(HOST, PORT);
  4591. #endif
  4592. auto res = cli.Get("/routing_handler");
  4593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4594. EXPECT_EQ(StatusCode::OK_200, res->status);
  4595. EXPECT_EQ("Routing Handler", res->body);
  4596. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4597. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4598. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4599. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4600. }
  4601. {
  4602. #ifdef CPPHTTPLIB_SSL_ENABLED
  4603. SSLClient cli(HOST, PORT);
  4604. cli.enable_server_certificate_verification(false);
  4605. #else
  4606. Client cli(HOST, PORT);
  4607. #endif
  4608. auto res = cli.Get("/hi");
  4609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4610. EXPECT_EQ(StatusCode::OK_200, res->status);
  4611. EXPECT_EQ("Hello World!\n", res->body);
  4612. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4613. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4614. }
  4615. {
  4616. #ifdef CPPHTTPLIB_SSL_ENABLED
  4617. SSLClient cli(HOST, PORT);
  4618. cli.enable_server_certificate_verification(false);
  4619. #else
  4620. Client cli(HOST, PORT);
  4621. #endif
  4622. auto res = cli.Get("/aaa");
  4623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4624. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4625. EXPECT_EQ("Error", res->body);
  4626. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4627. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4628. }
  4629. }
  4630. TEST(RequestHandlerTest, PreRequestHandler) {
  4631. auto route_path = "/user/:user";
  4632. Server svr;
  4633. svr.Get("/hi", [](const Request &, Response &res) {
  4634. res.set_content("hi", "text/plain");
  4635. });
  4636. svr.Get(route_path, [](const Request &req, Response &res) {
  4637. res.set_content(req.path_params.at("user"), "text/plain");
  4638. });
  4639. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4640. if (req.matched_route == route_path) {
  4641. auto user = req.path_params.at("user");
  4642. if (user != "john") {
  4643. res.status = StatusCode::Forbidden_403;
  4644. res.set_content("error", "text/html");
  4645. return Server::HandlerResponse::Handled;
  4646. }
  4647. }
  4648. return Server::HandlerResponse::Unhandled;
  4649. });
  4650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4651. auto se = detail::scope_exit([&] {
  4652. svr.stop();
  4653. thread.join();
  4654. ASSERT_FALSE(svr.is_running());
  4655. });
  4656. svr.wait_until_ready();
  4657. Client cli(HOST, PORT);
  4658. {
  4659. auto res = cli.Get("/hi");
  4660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4661. EXPECT_EQ(StatusCode::OK_200, res->status);
  4662. EXPECT_EQ("hi", res->body);
  4663. }
  4664. {
  4665. auto res = cli.Get("/user/john");
  4666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ("john", res->body);
  4669. }
  4670. {
  4671. auto res = cli.Get("/user/invalid-user");
  4672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4673. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4674. EXPECT_EQ("error", res->body);
  4675. }
  4676. }
  4677. // The pre-request handler must run before the request body is read, so a
  4678. // rejected request never forces the server to buffer a (potentially large)
  4679. // body. Here the posted body is larger than the payload limit: if the body
  4680. // were read first the server would answer 413, but because the pre-request
  4681. // handler runs first it answers 403 and the body is never read.
  4682. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4683. Server svr;
  4684. svr.set_payload_max_length(8);
  4685. auto handler_ran = false;
  4686. svr.Post("/reject", [&](const Request &req, Response &res) {
  4687. handler_ran = true;
  4688. res.set_content(req.body, "text/plain");
  4689. });
  4690. svr.Post("/accept", [](const Request &req, Response &res) {
  4691. res.set_content(req.body, "text/plain");
  4692. });
  4693. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4694. if (req.matched_route == "/reject") {
  4695. res.status = StatusCode::Forbidden_403;
  4696. res.set_content("denied", "text/plain");
  4697. return Server::HandlerResponse::Handled;
  4698. }
  4699. return Server::HandlerResponse::Unhandled;
  4700. });
  4701. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4702. auto se = detail::scope_exit([&] {
  4703. svr.stop();
  4704. thread.join();
  4705. ASSERT_FALSE(svr.is_running());
  4706. });
  4707. svr.wait_until_ready();
  4708. Client cli(HOST, PORT);
  4709. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4710. // rejects with 403 before the body is read, so 413 is never reached.
  4711. {
  4712. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4714. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4715. EXPECT_EQ("denied", res->body);
  4716. EXPECT_FALSE(handler_ran);
  4717. }
  4718. // An approved route still reads the body and enforces the payload limit.
  4719. {
  4720. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4722. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4723. }
  4724. }
  4725. TEST(UserDataTest, BasicOperations) {
  4726. httplib::UserData ud;
  4727. // Initially empty
  4728. EXPECT_FALSE(ud.has("key"));
  4729. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4730. // set and get
  4731. ud.set("key", 42);
  4732. EXPECT_TRUE(ud.has("key"));
  4733. auto *p = ud.get<int>("key");
  4734. ASSERT_NE(nullptr, p);
  4735. EXPECT_EQ(42, *p);
  4736. // Type mismatch → nullptr
  4737. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4738. // Overwrite with different type
  4739. ud.set("key", std::string("hello"));
  4740. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4741. auto *s = ud.get<std::string>("key");
  4742. ASSERT_NE(nullptr, s);
  4743. EXPECT_EQ("hello", *s);
  4744. // erase
  4745. ud.erase("key");
  4746. EXPECT_FALSE(ud.has("key"));
  4747. // clear
  4748. ud.set("a", 1);
  4749. ud.set("b", 2);
  4750. ud.clear();
  4751. EXPECT_FALSE(ud.has("a"));
  4752. EXPECT_FALSE(ud.has("b"));
  4753. }
  4754. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4755. struct AuthCtx {
  4756. std::string user_id;
  4757. };
  4758. Server svr;
  4759. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4760. res.user_data.set("auth", AuthCtx{"alice"});
  4761. return Server::HandlerResponse::Unhandled;
  4762. });
  4763. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4764. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4765. ASSERT_NE(nullptr, ctx);
  4766. res.set_content("Hello " + ctx->user_id, "text/plain");
  4767. });
  4768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4769. auto se = detail::scope_exit([&] {
  4770. svr.stop();
  4771. thread.join();
  4772. ASSERT_FALSE(svr.is_running());
  4773. });
  4774. svr.wait_until_ready();
  4775. Client cli(HOST, PORT);
  4776. auto res = cli.Get("/me");
  4777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4778. EXPECT_EQ(StatusCode::OK_200, res->status);
  4779. EXPECT_EQ("Hello alice", res->body);
  4780. }
  4781. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4782. struct RoleCtx {
  4783. std::string role;
  4784. };
  4785. Server svr;
  4786. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4787. res.user_data.set("role", RoleCtx{"admin"});
  4788. return Server::HandlerResponse::Unhandled;
  4789. });
  4790. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4791. auto *ctx = res.user_data.get<RoleCtx>("role");
  4792. ASSERT_NE(nullptr, ctx);
  4793. res.set_content(ctx->role, "text/plain");
  4794. });
  4795. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4796. auto se = detail::scope_exit([&] {
  4797. svr.stop();
  4798. thread.join();
  4799. ASSERT_FALSE(svr.is_running());
  4800. });
  4801. svr.wait_until_ready();
  4802. Client cli(HOST, PORT);
  4803. auto res = cli.Get("/role");
  4804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4805. EXPECT_EQ(StatusCode::OK_200, res->status);
  4806. EXPECT_EQ("admin", res->body);
  4807. }
  4808. TEST(InvalidFormatTest, StatusCode) {
  4809. Server svr;
  4810. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4811. res.set_content("Hello World!\n", "text/plain");
  4812. res.status = 9999; // Status should be a three-digit code...
  4813. });
  4814. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4815. auto se = detail::scope_exit([&] {
  4816. svr.stop();
  4817. thread.join();
  4818. ASSERT_FALSE(svr.is_running());
  4819. });
  4820. svr.wait_until_ready();
  4821. {
  4822. Client cli(HOST, PORT);
  4823. auto res = cli.Get("/hi");
  4824. ASSERT_FALSE(res);
  4825. }
  4826. }
  4827. TEST(URLFragmentTest, WithFragment) {
  4828. Server svr;
  4829. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4830. EXPECT_TRUE(req.target == "/hi");
  4831. });
  4832. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4833. auto se = detail::scope_exit([&] {
  4834. svr.stop();
  4835. thread.join();
  4836. ASSERT_FALSE(svr.is_running());
  4837. });
  4838. svr.wait_until_ready();
  4839. {
  4840. Client cli(HOST, PORT);
  4841. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4842. EXPECT_TRUE(res);
  4843. EXPECT_EQ(StatusCode::OK_200, res->status);
  4844. res = cli.Get("/hi%23key1=val1=key2=val2");
  4845. EXPECT_TRUE(res);
  4846. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4847. }
  4848. }
  4849. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  4850. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  4851. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  4852. Server svr;
  4853. std::vector<std::string> targets;
  4854. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  4855. targets.push_back(req.target);
  4856. });
  4857. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4858. auto se = detail::scope_exit([&] {
  4859. svr.stop();
  4860. thread.join();
  4861. ASSERT_FALSE(svr.is_running());
  4862. });
  4863. svr.wait_until_ready();
  4864. Client cli(HOST, PORT);
  4865. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  4866. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  4867. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  4868. // A '?' after the '#' belongs to the fragment, not to the query.
  4869. Request req;
  4870. req.method = "GET";
  4871. req.path = "/hi#f?x=1";
  4872. req.params.emplace("a", "1");
  4873. Response res;
  4874. auto error = Error::Success;
  4875. EXPECT_TRUE(cli.send(req, res, error));
  4876. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  4877. "/hi?a=1"}),
  4878. targets);
  4879. }
  4880. TEST(HeaderWriter, SetHeaderWriter) {
  4881. Server svr;
  4882. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4883. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4884. return detail::write_headers(strm, hdrs);
  4885. });
  4886. svr.Get("/hi", [](const Request &req, Response &res) {
  4887. auto it = req.headers.find("CustomClientHeader");
  4888. EXPECT_TRUE(it != req.headers.end());
  4889. EXPECT_EQ(it->second, "CustomClientValue");
  4890. res.set_content("Hello World!\n", "text/plain");
  4891. });
  4892. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4893. auto se = detail::scope_exit([&] {
  4894. svr.stop();
  4895. thread.join();
  4896. ASSERT_FALSE(svr.is_running());
  4897. });
  4898. svr.wait_until_ready();
  4899. {
  4900. Client cli(HOST, PORT);
  4901. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4902. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4903. return detail::write_headers(strm, hdrs);
  4904. });
  4905. auto res = cli.Get("/hi");
  4906. EXPECT_TRUE(res);
  4907. EXPECT_EQ(StatusCode::OK_200, res->status);
  4908. auto it = res->headers.find("CustomServerHeader");
  4909. EXPECT_TRUE(it != res->headers.end());
  4910. EXPECT_EQ(it->second, "CustomServerValue");
  4911. }
  4912. }
  4913. class ServerTest : public ::testing::Test {
  4914. protected:
  4915. ServerTest()
  4916. : cli_(HOST, PORT)
  4917. #ifdef CPPHTTPLIB_SSL_ENABLED
  4918. ,
  4919. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4920. #endif
  4921. {
  4922. #ifdef CPPHTTPLIB_SSL_ENABLED
  4923. cli_.enable_server_certificate_verification(false);
  4924. #endif
  4925. // Allow LARGE_DATA (100MB) responses
  4926. cli_.set_payload_max_length(200 * 1024 * 1024);
  4927. }
  4928. virtual void SetUp() {
  4929. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4930. svr_.set_payload_max_length(200 * 1024 * 1024);
  4931. svr_.set_mount_point("/", "./www");
  4932. svr_.set_mount_point("/mount", "./www2");
  4933. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4934. svr_.Get("/hi",
  4935. [&](const Request & /*req*/, Response &res) {
  4936. res.set_content("Hello World!", "text/plain");
  4937. })
  4938. .Get("/file_content",
  4939. [&](const Request & /*req*/, Response &res) {
  4940. res.set_file_content("./www/dir/test.html");
  4941. })
  4942. .Get("/file_content_with_content_type",
  4943. [&](const Request & /*req*/, Response &res) {
  4944. res.set_file_content("./www/file", "text/plain");
  4945. })
  4946. .Get("/invalid_file_content",
  4947. [&](const Request & /*req*/, Response &res) {
  4948. res.set_file_content("./www/dir/invalid_file_path");
  4949. })
  4950. .Get("/http_response_splitting",
  4951. [&](const Request & /*req*/, Response &res) {
  4952. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4953. EXPECT_EQ(0U, res.headers.size());
  4954. EXPECT_FALSE(res.has_header("a"));
  4955. res.set_header("a", "1\nSet-Cookie: a=1");
  4956. EXPECT_EQ(0U, res.headers.size());
  4957. EXPECT_FALSE(res.has_header("a"));
  4958. res.set_header("a", "1\rSet-Cookie: a=1");
  4959. EXPECT_EQ(0U, res.headers.size());
  4960. EXPECT_FALSE(res.has_header("a"));
  4961. res.set_header("a\r\nb", "0");
  4962. EXPECT_EQ(0U, res.headers.size());
  4963. EXPECT_FALSE(res.has_header("a"));
  4964. res.set_header("a\rb", "0");
  4965. EXPECT_EQ(0U, res.headers.size());
  4966. EXPECT_FALSE(res.has_header("a"));
  4967. res.set_header("a\nb", "0");
  4968. EXPECT_EQ(0U, res.headers.size());
  4969. EXPECT_FALSE(res.has_header("a"));
  4970. res.set_redirect("1\r\nSet-Cookie: a=1");
  4971. EXPECT_EQ(0U, res.headers.size());
  4972. EXPECT_FALSE(res.has_header("Location"));
  4973. })
  4974. .Get("/slow",
  4975. [&](const Request & /*req*/, Response &res) {
  4976. std::this_thread::sleep_for(std::chrono::seconds(4));
  4977. res.set_content("slow", "text/plain");
  4978. })
  4979. #if 0
  4980. .Post("/slowpost",
  4981. [&](const Request & /*req*/, Response &res) {
  4982. std::this_thread::sleep_for(std::chrono::seconds(2));
  4983. res.set_content("slow", "text/plain");
  4984. })
  4985. #endif
  4986. .Get("/remote_addr",
  4987. [&](const Request &req, Response &res) {
  4988. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4989. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4990. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4991. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4992. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4993. #endif
  4994. res.set_content(req.remote_addr, "text/plain");
  4995. })
  4996. .Get("/local_addr",
  4997. [&](const Request &req, Response &res) {
  4998. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4999. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5000. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5001. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5002. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5003. #endif
  5004. auto local_addr = req.local_addr;
  5005. auto local_port = std::to_string(req.local_port);
  5006. res.set_content(local_addr.append(":").append(local_port),
  5007. "text/plain");
  5008. })
  5009. .Get("/endwith%",
  5010. [&](const Request & /*req*/, Response &res) {
  5011. res.set_content("Hello World!", "text/plain");
  5012. })
  5013. .Get("/a\\+\\+b",
  5014. [&](const Request &req, Response &res) {
  5015. ASSERT_TRUE(req.has_param("a +b"));
  5016. auto val = req.get_param_value("a +b");
  5017. res.set_content(val, "text/plain");
  5018. })
  5019. .Get("/", [&](const Request & /*req*/,
  5020. Response &res) { res.set_redirect("/hi"); })
  5021. .Post("/1",
  5022. [](const Request & /*req*/, Response &res) {
  5023. res.set_redirect("/2", StatusCode::SeeOther_303);
  5024. })
  5025. .Get("/2",
  5026. [](const Request & /*req*/, Response &res) {
  5027. res.set_content("redirected.", "text/plain");
  5028. res.status = StatusCode::OK_200;
  5029. })
  5030. .Post("/person",
  5031. [&](const Request &req, Response &res) {
  5032. if (req.has_param("name") && req.has_param("note")) {
  5033. persons_[req.get_param_value("name")] =
  5034. req.get_param_value("note");
  5035. } else {
  5036. res.status = StatusCode::BadRequest_400;
  5037. }
  5038. })
  5039. .Put("/person",
  5040. [&](const Request &req, Response &res) {
  5041. if (req.has_param("name") && req.has_param("note")) {
  5042. persons_[req.get_param_value("name")] =
  5043. req.get_param_value("note");
  5044. } else {
  5045. res.status = StatusCode::BadRequest_400;
  5046. }
  5047. })
  5048. .Get("/person/(.*)",
  5049. [&](const Request &req, Response &res) {
  5050. string name = req.matches[1];
  5051. if (persons_.find(name) != persons_.end()) {
  5052. auto note = persons_[name];
  5053. res.set_content(note, "text/plain");
  5054. } else {
  5055. res.status = StatusCode::NotFound_404;
  5056. }
  5057. })
  5058. .Delete("/person",
  5059. [&](const Request &req, Response &res) {
  5060. if (req.has_param("name")) {
  5061. string name = req.get_param_value("name");
  5062. if (persons_.find(name) != persons_.end()) {
  5063. persons_.erase(name);
  5064. res.set_content("DELETED", "text/plain");
  5065. } else {
  5066. res.status = StatusCode::NotFound_404;
  5067. }
  5068. } else {
  5069. res.status = StatusCode::BadRequest_400;
  5070. }
  5071. })
  5072. .Post("/x-www-form-urlencoded-json",
  5073. [&](const Request &req, Response &res) {
  5074. auto json = req.get_param_value("json");
  5075. ASSERT_EQ(JSON_DATA, json);
  5076. res.set_content(json, "appliation/json");
  5077. res.status = StatusCode::OK_200;
  5078. })
  5079. .Get("/streamed-chunked",
  5080. [&](const Request & /*req*/, Response &res) {
  5081. res.set_chunked_content_provider(
  5082. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5083. sink.os << "123";
  5084. sink.os << "456";
  5085. sink.os << "789";
  5086. sink.done();
  5087. return true;
  5088. });
  5089. })
  5090. .Get("/streamed-chunked-with-prohibited-trailer",
  5091. [&](const Request & /*req*/, Response &res) {
  5092. auto i = new int(0);
  5093. // Declare both a prohibited trailer (Content-Length) and an
  5094. // allowed one
  5095. res.set_header("Trailer", "Content-Length, X-Allowed");
  5096. res.set_chunked_content_provider(
  5097. "text/plain",
  5098. [i](size_t /*offset*/, DataSink &sink) {
  5099. switch (*i) {
  5100. case 0: sink.os << "123"; break;
  5101. case 1: sink.os << "456"; break;
  5102. case 2: sink.os << "789"; break;
  5103. case 3: {
  5104. sink.done_with_trailer(
  5105. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5106. } break;
  5107. }
  5108. (*i)++;
  5109. return true;
  5110. },
  5111. [i](bool success) {
  5112. EXPECT_TRUE(success);
  5113. delete i;
  5114. });
  5115. })
  5116. .Get("/streamed-chunked2",
  5117. [&](const Request & /*req*/, Response &res) {
  5118. auto i = new int(0);
  5119. res.set_chunked_content_provider(
  5120. "text/plain",
  5121. [i](size_t /*offset*/, DataSink &sink) {
  5122. switch (*i) {
  5123. case 0: sink.os << "123"; break;
  5124. case 1: sink.os << "456"; break;
  5125. case 2: sink.os << "789"; break;
  5126. case 3: sink.done(); break;
  5127. }
  5128. (*i)++;
  5129. return true;
  5130. },
  5131. [i](bool success) {
  5132. EXPECT_TRUE(success);
  5133. delete i;
  5134. });
  5135. })
  5136. .Get("/streamed-chunked-with-trailer",
  5137. [&](const Request & /*req*/, Response &res) {
  5138. auto i = new int(0);
  5139. res.set_header("Trailer", "Dummy1, Dummy2");
  5140. res.set_chunked_content_provider(
  5141. "text/plain",
  5142. [i](size_t /*offset*/, DataSink &sink) {
  5143. switch (*i) {
  5144. case 0: sink.os << "123"; break;
  5145. case 1: sink.os << "456"; break;
  5146. case 2: sink.os << "789"; break;
  5147. case 3: {
  5148. sink.done_with_trailer(
  5149. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5150. } break;
  5151. }
  5152. (*i)++;
  5153. return true;
  5154. },
  5155. [i](bool success) {
  5156. EXPECT_TRUE(success);
  5157. delete i;
  5158. });
  5159. })
  5160. .Get("/streamed",
  5161. [&](const Request & /*req*/, Response &res) {
  5162. res.set_content_provider(
  5163. 6, "text/plain",
  5164. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5165. sink.os << (offset < 3 ? "a" : "b");
  5166. return true;
  5167. });
  5168. })
  5169. .Get("/streamed-without-length",
  5170. [&](const Request & /*req*/, Response &res) {
  5171. auto data = new std::string("abcdefg");
  5172. res.set_content_provider(
  5173. "text/plain",
  5174. [data](size_t offset, DataSink &sink) {
  5175. if (offset < data->size()) {
  5176. sink.os << data->substr(offset);
  5177. }
  5178. sink.done();
  5179. return true;
  5180. },
  5181. [data](bool success) {
  5182. EXPECT_TRUE(success);
  5183. delete data;
  5184. });
  5185. })
  5186. .Get("/streamed-with-range",
  5187. [&](const Request &req, Response &res) {
  5188. auto data = new std::string("abcdefg");
  5189. // An explicit status keeps the server from picking the 206 it
  5190. // would otherwise choose for a ranged request, so the response
  5191. // is not a partial representation.
  5192. auto status = req.get_param_value("status");
  5193. if (status == "200") {
  5194. res.status = StatusCode::OK_200;
  5195. } else if (status == "403") {
  5196. res.status = StatusCode::Forbidden_403;
  5197. }
  5198. res.set_content_provider(
  5199. data->size(), "text/plain",
  5200. [data](size_t offset, size_t length, DataSink &sink) {
  5201. size_t DATA_CHUNK_SIZE = 4;
  5202. const auto &d = *data;
  5203. auto out_len =
  5204. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5205. auto ret =
  5206. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5207. EXPECT_TRUE(ret);
  5208. return true;
  5209. },
  5210. [data, &req](bool success) {
  5211. EXPECT_EQ(success, !req.has_param("error"));
  5212. delete data;
  5213. });
  5214. })
  5215. .Get("/streamed-cancel",
  5216. [&](const Request & /*req*/, Response &res) {
  5217. res.set_content_provider(
  5218. size_t(-1), "text/plain",
  5219. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5220. sink.os << "data_chunk";
  5221. return true;
  5222. });
  5223. })
  5224. .Get("/regex-with-delimiter",
  5225. [&](const Request &req, Response & /*res*/) {
  5226. ASSERT_TRUE(req.has_param("key"));
  5227. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5228. })
  5229. .Get("/with-range",
  5230. [&](const Request & /*req*/, Response &res) {
  5231. res.set_content("abcdefg", "text/plain");
  5232. })
  5233. .Get("/test-start-time",
  5234. [&](const Request &req, Response & /*res*/) {
  5235. EXPECT_NE(req.start_time_,
  5236. std::chrono::steady_clock::time_point::min());
  5237. })
  5238. .Get("/with-range-customized-response",
  5239. [&](const Request & /*req*/, Response &res) {
  5240. res.status = StatusCode::BadRequest_400;
  5241. res.set_content(JSON_DATA, "application/json");
  5242. })
  5243. .Post("/chunked",
  5244. [&](const Request &req, Response & /*res*/) {
  5245. EXPECT_EQ(req.body, "dechunked post body");
  5246. })
  5247. .Post("/large-chunked",
  5248. [&](const Request &req, Response & /*res*/) {
  5249. std::string expected(6 * 30 * 1024u, 'a');
  5250. EXPECT_EQ(req.body, expected);
  5251. })
  5252. .Post("/multipart",
  5253. [&](const Request &req, Response & /*res*/) {
  5254. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5255. req.form.get_field_count("text2") +
  5256. req.form.get_field_count("file3") +
  5257. req.form.get_field_count("file4"));
  5258. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5259. req.form.get_file_count("file2"));
  5260. ASSERT_TRUE(!req.form.has_file("???"));
  5261. ASSERT_TRUE(!req.form.has_field("???"));
  5262. ASSERT_TRUE(req.body.empty());
  5263. {
  5264. const auto &text = req.form.get_field("text1");
  5265. EXPECT_EQ("text default", text);
  5266. }
  5267. {
  5268. const auto &text = req.form.get_field("text2");
  5269. EXPECT_EQ("aωb", text);
  5270. }
  5271. {
  5272. const auto &file = req.form.get_file("file1");
  5273. EXPECT_EQ("hello.txt", file.filename);
  5274. EXPECT_EQ("text/plain", file.content_type);
  5275. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5276. }
  5277. {
  5278. const auto &file = req.form.get_file("file2");
  5279. EXPECT_EQ("world.json", file.filename);
  5280. EXPECT_EQ("application/json", file.content_type);
  5281. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5282. }
  5283. {
  5284. const auto &text = req.form.get_field("file3");
  5285. EXPECT_EQ(0u, text.size());
  5286. }
  5287. {
  5288. const auto &text = req.form.get_field("file4");
  5289. EXPECT_EQ(0u, text.size());
  5290. }
  5291. })
  5292. .Post("/multipart/multi_file_values",
  5293. [&](const Request &req, Response & /*res*/) {
  5294. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5295. req.form.get_field_count("multi_text1"));
  5296. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5297. ASSERT_TRUE(!req.form.has_file("???"));
  5298. ASSERT_TRUE(!req.form.has_field("???"));
  5299. ASSERT_TRUE(req.body.empty());
  5300. {
  5301. const auto &text = req.form.get_field("text");
  5302. EXPECT_EQ("default text", text);
  5303. }
  5304. {
  5305. const auto &text1_values = req.form.get_fields("multi_text1");
  5306. EXPECT_EQ(2u, text1_values.size());
  5307. EXPECT_EQ("aaaaa", text1_values[0]);
  5308. EXPECT_EQ("bbbbb", text1_values[1]);
  5309. }
  5310. {
  5311. const auto &file1_values = req.form.get_files("multi_file1");
  5312. EXPECT_EQ(2u, file1_values.size());
  5313. auto file1 = file1_values[0];
  5314. EXPECT_EQ(file1.filename, "hello.txt");
  5315. EXPECT_EQ(file1.content_type, "text/plain");
  5316. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5317. auto file2 = file1_values[1];
  5318. EXPECT_EQ(file2.filename, "world.json");
  5319. EXPECT_EQ(file2.content_type, "application/json");
  5320. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5321. }
  5322. })
  5323. .Post("/empty",
  5324. [&](const Request &req, Response &res) {
  5325. EXPECT_EQ(req.body, "");
  5326. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5327. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5328. res.set_content("empty", "text/plain");
  5329. })
  5330. .Post("/empty-no-content-type",
  5331. [&](const Request &req, Response &res) {
  5332. EXPECT_EQ(req.body, "");
  5333. EXPECT_FALSE(req.has_header("Content-Type"));
  5334. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5335. res.set_content("empty-no-content-type", "text/plain");
  5336. })
  5337. .Post("/path-only",
  5338. [&](const Request &req, Response &res) {
  5339. EXPECT_EQ(req.body, "");
  5340. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5341. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5342. res.set_content("path-only", "text/plain");
  5343. })
  5344. .Post("/path-headers-only",
  5345. [&](const Request &req, Response &res) {
  5346. EXPECT_EQ(req.body, "");
  5347. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5348. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5349. EXPECT_EQ("world", req.get_header_value("hello"));
  5350. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5351. res.set_content("path-headers-only", "text/plain");
  5352. })
  5353. .Post("/post-large",
  5354. [&](const Request &req, Response &res) {
  5355. EXPECT_EQ(req.body, LARGE_DATA);
  5356. res.set_content(req.body, "text/plain");
  5357. })
  5358. .Post("/post-loopback",
  5359. [&](const Request &, Response &res,
  5360. ContentReader const &content_reader) {
  5361. std::string body;
  5362. content_reader([&](const char *data, size_t data_length) {
  5363. body.append(data, data_length);
  5364. return true;
  5365. });
  5366. res.set_content(body, "text/plain");
  5367. })
  5368. .Put("/put-loopback",
  5369. [&](const Request &, Response &res,
  5370. ContentReader const &content_reader) {
  5371. std::string body;
  5372. content_reader([&](const char *data, size_t data_length) {
  5373. body.append(data, data_length);
  5374. return true;
  5375. });
  5376. res.set_content(body, "text/plain");
  5377. })
  5378. .Patch("/patch-loopback",
  5379. [&](const Request &, Response &res,
  5380. ContentReader const &content_reader) {
  5381. std::string body;
  5382. content_reader([&](const char *data, size_t data_length) {
  5383. body.append(data, data_length);
  5384. return true;
  5385. });
  5386. res.set_content(body, "text/plain");
  5387. })
  5388. .Put("/empty-no-content-type",
  5389. [&](const Request &req, Response &res) {
  5390. EXPECT_EQ(req.body, "");
  5391. EXPECT_FALSE(req.has_header("Content-Type"));
  5392. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5393. res.set_content("empty-no-content-type", "text/plain");
  5394. })
  5395. .Put("/put",
  5396. [&](const Request &req, Response &res) {
  5397. EXPECT_EQ(req.body, "PUT");
  5398. res.set_content(req.body, "text/plain");
  5399. })
  5400. .Put("/put-large",
  5401. [&](const Request &req, Response &res) {
  5402. EXPECT_EQ(req.body, LARGE_DATA);
  5403. res.set_content(req.body, "text/plain");
  5404. })
  5405. .Patch("/patch",
  5406. [&](const Request &req, Response &res) {
  5407. EXPECT_EQ(req.body, "PATCH");
  5408. res.set_content(req.body, "text/plain");
  5409. })
  5410. .Delete("/delete",
  5411. [&](const Request & /*req*/, Response &res) {
  5412. res.set_content("DELETE", "text/plain");
  5413. })
  5414. .Delete("/delete-body",
  5415. [&](const Request &req, Response &res) {
  5416. EXPECT_EQ(req.body, "content");
  5417. res.set_content(req.body, "text/plain");
  5418. })
  5419. .Options(R"(\*)",
  5420. [&](const Request & /*req*/, Response &res) {
  5421. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5422. })
  5423. .CustomRoute("PROPFIND", "/dav/:id",
  5424. [&](const Request &req, Response &res) {
  5425. res.set_header("x-body-size",
  5426. std::to_string(req.body.size()));
  5427. res.set_header("x-matched-route", req.matched_route);
  5428. res.set_header("x-dav-id", req.path_params.at("id"));
  5429. res.status = StatusCode::MultiStatus_207;
  5430. res.set_content(req.body, "application/xml");
  5431. })
  5432. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5433. [&](const Request &req, Response &res) {
  5434. res.set_header("x-dav-match", req.matches[1]);
  5435. res.status = StatusCode::MultiStatus_207;
  5436. })
  5437. .CustomRoute("MKCOL", "/dav-mkcol",
  5438. [&](const Request &req, Response &res) {
  5439. EXPECT_TRUE(req.body.empty());
  5440. res.status = StatusCode::Created_201;
  5441. })
  5442. .CustomRoute(
  5443. "REPORT", "/dav-report",
  5444. [&](const Request & /*req*/, Response &res,
  5445. const ContentReader &content_reader) {
  5446. std::string body;
  5447. content_reader([&](const char *data, size_t data_length) {
  5448. body.append(data, data_length);
  5449. return true;
  5450. });
  5451. res.set_header("x-body-size", std::to_string(body.size()));
  5452. res.status = StatusCode::MultiStatus_207;
  5453. res.set_content(body, "application/xml");
  5454. })
  5455. .Get("/request-target",
  5456. [&](const Request &req, Response & /*res*/) {
  5457. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5458. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5459. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5460. })
  5461. .Get("/long-query-value",
  5462. [&](const Request &req, Response & /*res*/) {
  5463. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5464. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5465. })
  5466. .Get("/too-long-query-value",
  5467. [&](const Request &req, Response & /*res*/) {
  5468. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5469. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5470. })
  5471. .Get("/array-param",
  5472. [&](const Request &req, Response & /*res*/) {
  5473. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5474. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5475. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5476. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5477. })
  5478. .Get("/array-param-values",
  5479. [&](const Request &req, Response & /*res*/) {
  5480. auto values = req.get_param_values("array");
  5481. EXPECT_EQ(3u, values.size());
  5482. EXPECT_EQ("value1", values[0]);
  5483. EXPECT_EQ("value2", values[1]);
  5484. EXPECT_EQ("value3", values[2]);
  5485. auto empty = req.get_param_values("nonexistent");
  5486. EXPECT_TRUE(empty.empty());
  5487. })
  5488. .Post("/validate-no-multiple-headers",
  5489. [&](const Request &req, Response & /*res*/) {
  5490. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5491. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5492. })
  5493. .Post("/content_receiver",
  5494. [&](const Request &req, Response &res,
  5495. const ContentReader &content_reader) {
  5496. if (req.is_multipart_form_data()) {
  5497. std::vector<FormData> items;
  5498. content_reader(
  5499. [&](const FormData &file) {
  5500. items.push_back(file);
  5501. return true;
  5502. },
  5503. [&](const char *data, size_t data_length) {
  5504. items.back().content.append(data, data_length);
  5505. return true;
  5506. });
  5507. EXPECT_EQ(5u, items.size());
  5508. {
  5509. const auto &file = get_file_value(items, "text1");
  5510. EXPECT_TRUE(file.filename.empty());
  5511. EXPECT_EQ("text default", file.content);
  5512. }
  5513. {
  5514. const auto &file = get_file_value(items, "text2");
  5515. EXPECT_TRUE(file.filename.empty());
  5516. EXPECT_EQ("aωb", file.content);
  5517. }
  5518. {
  5519. const auto &file = get_file_value(items, "file1");
  5520. EXPECT_EQ("hello.txt", file.filename);
  5521. EXPECT_EQ("text/plain", file.content_type);
  5522. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5523. }
  5524. {
  5525. const auto &file = get_file_value(items, "file2");
  5526. EXPECT_EQ("world.json", file.filename);
  5527. EXPECT_EQ("application/json", file.content_type);
  5528. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5529. }
  5530. {
  5531. const auto &file = get_file_value(items, "file3");
  5532. EXPECT_TRUE(file.filename.empty());
  5533. EXPECT_EQ("application/octet-stream", file.content_type);
  5534. EXPECT_EQ(0u, file.content.size());
  5535. }
  5536. } else {
  5537. std::string body;
  5538. content_reader([&](const char *data, size_t data_length) {
  5539. EXPECT_EQ(7U, data_length);
  5540. body.append(data, data_length);
  5541. return true;
  5542. });
  5543. EXPECT_EQ(body, "content");
  5544. res.set_content(body, "text/plain");
  5545. }
  5546. })
  5547. .Put("/content_receiver",
  5548. [&](const Request & /*req*/, Response &res,
  5549. const ContentReader &content_reader) {
  5550. std::string body;
  5551. content_reader([&](const char *data, size_t data_length) {
  5552. body.append(data, data_length);
  5553. return true;
  5554. });
  5555. EXPECT_EQ(body, "content");
  5556. res.set_content(body, "text/plain");
  5557. })
  5558. .Patch("/content_receiver",
  5559. [&](const Request & /*req*/, Response &res,
  5560. const ContentReader &content_reader) {
  5561. std::string body;
  5562. content_reader([&](const char *data, size_t data_length) {
  5563. body.append(data, data_length);
  5564. return true;
  5565. });
  5566. EXPECT_EQ(body, "content");
  5567. res.set_content(body, "text/plain");
  5568. })
  5569. .Post("/query-string-and-body",
  5570. [&](const Request &req, Response & /*res*/) {
  5571. ASSERT_TRUE(req.has_param("key"));
  5572. EXPECT_EQ(req.get_param_value("key"), "value");
  5573. EXPECT_EQ(req.body, "content");
  5574. })
  5575. .Get("/last-request",
  5576. [&](const Request &req, Response & /*res*/) {
  5577. EXPECT_EQ("close", req.get_header_value("Connection"));
  5578. })
  5579. .Get(R"(/redirect/(\d+))",
  5580. [&](const Request &req, Response &res) {
  5581. auto num = std::stoi(req.matches[1]) + 1;
  5582. std::string url = "/redirect/" + std::to_string(num);
  5583. res.set_redirect(url);
  5584. })
  5585. .Post("/binary",
  5586. [&](const Request &req, Response &res) {
  5587. EXPECT_EQ(4U, req.body.size());
  5588. EXPECT_EQ("application/octet-stream",
  5589. req.get_header_value("Content-Type"));
  5590. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5591. res.set_content(req.body, "application/octet-stream");
  5592. })
  5593. .Put("/binary",
  5594. [&](const Request &req, Response &res) {
  5595. EXPECT_EQ(4U, req.body.size());
  5596. EXPECT_EQ("application/octet-stream",
  5597. req.get_header_value("Content-Type"));
  5598. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5599. res.set_content(req.body, "application/octet-stream");
  5600. })
  5601. .Patch("/binary",
  5602. [&](const Request &req, Response &res) {
  5603. EXPECT_EQ(4U, req.body.size());
  5604. EXPECT_EQ("application/octet-stream",
  5605. req.get_header_value("Content-Type"));
  5606. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5607. res.set_content(req.body, "application/octet-stream");
  5608. })
  5609. .Delete("/binary",
  5610. [&](const Request &req, Response &res) {
  5611. EXPECT_EQ(4U, req.body.size());
  5612. EXPECT_EQ("application/octet-stream",
  5613. req.get_header_value("Content-Type"));
  5614. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5615. res.set_content(req.body, "application/octet-stream");
  5616. })
  5617. .Get("/issue1772",
  5618. [&](const Request & /*req*/, Response &res) {
  5619. res.status = 401;
  5620. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5621. })
  5622. .Delete("/issue609",
  5623. [](const httplib::Request &, httplib::Response &res,
  5624. const httplib::ContentReader &) {
  5625. res.set_content("ok", "text/plain");
  5626. })
  5627. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5628. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5629. .Get("/compress",
  5630. [&](const Request & /*req*/, Response &res) {
  5631. res.set_content(
  5632. "12345678901234567890123456789012345678901234567890123456789"
  5633. "01234567890123456789012345678901234567890",
  5634. "text/plain");
  5635. })
  5636. .Get("/compress-with-charset",
  5637. [&](const Request & /*req*/, Response &res) {
  5638. res.set_content(
  5639. "12345678901234567890123456789012345678901234567890123456789"
  5640. "01234567890123456789012345678901234567890",
  5641. "application/json; charset=utf-8");
  5642. })
  5643. .Get("/nocompress",
  5644. [&](const Request & /*req*/, Response &res) {
  5645. res.set_content(
  5646. "12345678901234567890123456789012345678901234567890123456789"
  5647. "01234567890123456789012345678901234567890",
  5648. "application/octet-stream");
  5649. })
  5650. .Post("/compress-multipart",
  5651. [&](const Request &req, Response & /*res*/) {
  5652. EXPECT_EQ(2u, req.form.fields.size());
  5653. ASSERT_TRUE(!req.form.has_field("???"));
  5654. {
  5655. const auto &text = req.form.get_field("key1");
  5656. EXPECT_EQ("test", text);
  5657. }
  5658. {
  5659. const auto &text = req.form.get_field("key2");
  5660. EXPECT_EQ("--abcdefg123", text);
  5661. }
  5662. })
  5663. #endif
  5664. ;
  5665. persons_["john"] = "programmer";
  5666. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5667. svr_.wait_until_ready();
  5668. }
  5669. virtual void TearDown() {
  5670. svr_.stop();
  5671. if (!request_threads_.empty()) {
  5672. std::this_thread::sleep_for(std::chrono::seconds(1));
  5673. for (auto &t : request_threads_) {
  5674. t.join();
  5675. }
  5676. }
  5677. t_.join();
  5678. }
  5679. map<string, string> persons_;
  5680. #ifdef CPPHTTPLIB_SSL_ENABLED
  5681. SSLClient cli_;
  5682. SSLServer svr_;
  5683. #else
  5684. Client cli_;
  5685. Server svr_;
  5686. #endif
  5687. thread t_;
  5688. std::vector<thread> request_threads_;
  5689. };
  5690. TEST_F(ServerTest, GetMethod200) {
  5691. auto res = cli_.Get("/hi");
  5692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5693. EXPECT_EQ("HTTP/1.1", res->version);
  5694. EXPECT_EQ(StatusCode::OK_200, res->status);
  5695. EXPECT_EQ("OK", res->reason);
  5696. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5697. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5698. EXPECT_EQ("Hello World!", res->body);
  5699. }
  5700. TEST_F(ServerTest, GetEmptyFile) {
  5701. auto res = cli_.Get("/empty_file");
  5702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5703. EXPECT_EQ(StatusCode::OK_200, res->status);
  5704. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5705. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5706. EXPECT_EQ("", res->body);
  5707. }
  5708. TEST_F(ServerTest, GetFileContent) {
  5709. auto res = cli_.Get("/file_content");
  5710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5711. EXPECT_EQ(StatusCode::OK_200, res->status);
  5712. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5713. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5714. EXPECT_EQ("test.html", res->body);
  5715. }
  5716. TEST_F(ServerTest, GetFileContentWithRange) {
  5717. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5720. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5721. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5722. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5723. EXPECT_EQ("est", res->body);
  5724. }
  5725. TEST_F(ServerTest, GetFileContentWithContentType) {
  5726. auto res = cli_.Get("/file_content_with_content_type");
  5727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5728. EXPECT_EQ(StatusCode::OK_200, res->status);
  5729. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5730. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5731. EXPECT_EQ("file\n", res->body);
  5732. }
  5733. TEST_F(ServerTest, GetInvalidFileContent) {
  5734. auto res = cli_.Get("/invalid_file_content");
  5735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5736. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5737. }
  5738. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5739. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5741. EXPECT_EQ("HTTP/1.1", res->version);
  5742. EXPECT_EQ(StatusCode::OK_200, res->status);
  5743. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5744. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5745. EXPECT_EQ("Hello World!", res->body);
  5746. }
  5747. TEST_F(ServerTest, GetMethod302) {
  5748. auto res = cli_.Get("/");
  5749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5750. EXPECT_EQ(StatusCode::Found_302, res->status);
  5751. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5752. }
  5753. TEST_F(ServerTest, GetMethod302Redirect) {
  5754. cli_.set_follow_location(true);
  5755. auto res = cli_.Get("/");
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. EXPECT_EQ(StatusCode::OK_200, res->status);
  5758. EXPECT_EQ("Hello World!", res->body);
  5759. EXPECT_EQ("/hi", res->location);
  5760. }
  5761. TEST_F(ServerTest, GetMethod404) {
  5762. auto res = cli_.Get("/invalid");
  5763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5764. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5765. }
  5766. TEST_F(ServerTest, HeadMethod200) {
  5767. auto res = cli_.Head("/hi");
  5768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5769. EXPECT_EQ(StatusCode::OK_200, res->status);
  5770. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5771. EXPECT_TRUE(res->body.empty());
  5772. }
  5773. TEST_F(ServerTest, HeadMethod200Static) {
  5774. auto res = cli_.Head("/mount/dir/index.html");
  5775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5776. EXPECT_EQ(StatusCode::OK_200, res->status);
  5777. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5778. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5779. EXPECT_TRUE(res->body.empty());
  5780. }
  5781. TEST_F(ServerTest, HeadMethod404) {
  5782. auto res = cli_.Head("/invalid");
  5783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5784. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5785. EXPECT_TRUE(res->body.empty());
  5786. }
  5787. TEST_F(ServerTest, GetMethodPersonJohn) {
  5788. auto res = cli_.Get("/person/john");
  5789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5790. EXPECT_EQ(StatusCode::OK_200, res->status);
  5791. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5792. EXPECT_EQ("programmer", res->body);
  5793. }
  5794. TEST_F(ServerTest, PostMethod1) {
  5795. auto res = cli_.Get("/person/john1");
  5796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5797. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5798. res = cli_.Post("/person", "name=john1&note=coder",
  5799. "application/x-www-form-urlencoded");
  5800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5801. ASSERT_EQ(StatusCode::OK_200, res->status);
  5802. res = cli_.Get("/person/john1");
  5803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5804. ASSERT_EQ(StatusCode::OK_200, res->status);
  5805. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5806. ASSERT_EQ("coder", res->body);
  5807. }
  5808. TEST_F(ServerTest, PostMethod2) {
  5809. auto res = cli_.Get("/person/john2");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5812. Params params;
  5813. params.emplace("name", "john2");
  5814. params.emplace("note", "coder");
  5815. res = cli_.Post("/person", params);
  5816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5817. ASSERT_EQ(StatusCode::OK_200, res->status);
  5818. res = cli_.Get("/person/john2");
  5819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5820. ASSERT_EQ(StatusCode::OK_200, res->status);
  5821. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5822. ASSERT_EQ("coder", res->body);
  5823. }
  5824. TEST_F(ServerTest, PutMethod3) {
  5825. auto res = cli_.Get("/person/john3");
  5826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5827. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5828. Params params;
  5829. params.emplace("name", "john3");
  5830. params.emplace("note", "coder");
  5831. res = cli_.Put("/person", params);
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. ASSERT_EQ(StatusCode::OK_200, res->status);
  5834. res = cli_.Get("/person/john3");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. ASSERT_EQ(StatusCode::OK_200, res->status);
  5837. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5838. ASSERT_EQ("coder", res->body);
  5839. }
  5840. TEST_F(ServerTest, DeleteMethod1) {
  5841. auto res = cli_.Get("/person/john4");
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5844. Params params;
  5845. params.emplace("name", "john4");
  5846. params.emplace("note", "coder");
  5847. res = cli_.Post("/person", params);
  5848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5849. ASSERT_EQ(StatusCode::OK_200, res->status);
  5850. res = cli_.Get("/person/john4");
  5851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5852. ASSERT_EQ(StatusCode::OK_200, res->status);
  5853. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5854. ASSERT_EQ("coder", res->body);
  5855. Params delete_params;
  5856. delete_params.emplace("name", "john4");
  5857. res = cli_.Delete("/person", delete_params);
  5858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5859. ASSERT_EQ(StatusCode::OK_200, res->status);
  5860. ASSERT_EQ("DELETED", res->body);
  5861. res = cli_.Get("/person/john4");
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5864. }
  5865. TEST_F(ServerTest, DeleteMethod2) {
  5866. auto res = cli_.Get("/person/john5");
  5867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5868. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5869. Params params;
  5870. params.emplace("name", "john5");
  5871. params.emplace("note", "developer");
  5872. res = cli_.Post("/person", params);
  5873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5874. ASSERT_EQ(StatusCode::OK_200, res->status);
  5875. res = cli_.Get("/person/john5");
  5876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5877. ASSERT_EQ(StatusCode::OK_200, res->status);
  5878. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5879. ASSERT_EQ("developer", res->body);
  5880. Params delete_params;
  5881. delete_params.emplace("name", "john5");
  5882. Headers headers;
  5883. headers.emplace("Custom-Header", "test-value");
  5884. res = cli_.Delete("/person", headers, delete_params);
  5885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5886. ASSERT_EQ(StatusCode::OK_200, res->status);
  5887. ASSERT_EQ("DELETED", res->body);
  5888. res = cli_.Get("/person/john5");
  5889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5890. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5891. }
  5892. TEST_F(ServerTest, DeleteMethod3) {
  5893. auto res = cli_.Get("/person/john6");
  5894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5895. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5896. Params params;
  5897. params.emplace("name", "john6");
  5898. params.emplace("note", "tester");
  5899. res = cli_.Post("/person", params);
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. ASSERT_EQ(StatusCode::OK_200, res->status);
  5902. res = cli_.Get("/person/john6");
  5903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5904. ASSERT_EQ(StatusCode::OK_200, res->status);
  5905. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5906. ASSERT_EQ("tester", res->body);
  5907. Params delete_params;
  5908. delete_params.emplace("name", "john6");
  5909. Headers headers;
  5910. headers.emplace("Custom-Header", "test-value");
  5911. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5913. ASSERT_EQ(StatusCode::OK_200, res->status);
  5914. ASSERT_EQ("DELETED", res->body);
  5915. res = cli_.Get("/person/john6");
  5916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5917. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5918. }
  5919. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5920. Params params;
  5921. params.emplace("json", JSON_DATA);
  5922. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5924. ASSERT_EQ(StatusCode::OK_200, res->status);
  5925. ASSERT_EQ(JSON_DATA, res->body);
  5926. }
  5927. TEST_F(ServerTest, PostEmptyContent) {
  5928. auto res = cli_.Post("/empty", "", "text/plain");
  5929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5930. ASSERT_EQ(StatusCode::OK_200, res->status);
  5931. ASSERT_EQ("empty", res->body);
  5932. }
  5933. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5934. auto res = cli_.Post("/empty-no-content-type");
  5935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5936. ASSERT_EQ(StatusCode::OK_200, res->status);
  5937. ASSERT_EQ("empty-no-content-type", res->body);
  5938. }
  5939. TEST_F(ServerTest, PostPathOnly) {
  5940. auto res = cli_.Post("/path-only");
  5941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5942. ASSERT_EQ(StatusCode::OK_200, res->status);
  5943. ASSERT_EQ("path-only", res->body);
  5944. }
  5945. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5946. auto res = cli_.Post("/path-headers-only",
  5947. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5949. ASSERT_EQ(StatusCode::OK_200, res->status);
  5950. ASSERT_EQ("path-headers-only", res->body);
  5951. }
  5952. TEST_F(ServerTest, PostLarge) {
  5953. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5955. ASSERT_EQ(StatusCode::OK_200, res->status);
  5956. EXPECT_EQ(LARGE_DATA, res->body);
  5957. }
  5958. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5959. auto res = cli_.Put("/empty-no-content-type");
  5960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5961. ASSERT_EQ(StatusCode::OK_200, res->status);
  5962. ASSERT_EQ("empty-no-content-type", res->body);
  5963. }
  5964. TEST_F(ServerTest, GetMethodDir) {
  5965. auto res = cli_.Get("/dir/");
  5966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5967. EXPECT_EQ(StatusCode::OK_200, res->status);
  5968. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5969. auto body = R"(<html>
  5970. <head>
  5971. </head>
  5972. <body>
  5973. <a href="/dir/test.html">Test</a>
  5974. <a href="/hi">hi</a>
  5975. </body>
  5976. </html>
  5977. )";
  5978. EXPECT_EQ(body, res->body);
  5979. }
  5980. TEST_F(ServerTest, GetMethodDirTest) {
  5981. auto res = cli_.Get("/dir/test.html");
  5982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5983. EXPECT_EQ(StatusCode::OK_200, res->status);
  5984. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5985. EXPECT_EQ("test.html", res->body);
  5986. }
  5987. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5988. auto res = cli_.Get("/dir/../dir/test.html");
  5989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5990. EXPECT_EQ(StatusCode::OK_200, res->status);
  5991. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5992. EXPECT_EQ("test.html", res->body);
  5993. }
  5994. TEST_F(ServerTest, GetMethodInvalidPath) {
  5995. auto res = cli_.Get("/dir/../test.html");
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5998. }
  5999. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6000. auto res = cli_.Get("/../www/dir/test.html");
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6003. }
  6004. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6005. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6007. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6008. }
  6009. TEST_F(ServerTest, GetMethodDirMountTest) {
  6010. auto res = cli_.Get("/mount/dir/test.html");
  6011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6012. EXPECT_EQ(StatusCode::OK_200, res->status);
  6013. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6014. EXPECT_EQ("test.html", res->body);
  6015. }
  6016. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6017. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6021. EXPECT_EQ("test.html", res->body);
  6022. }
  6023. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6024. auto res = cli_.Get("/mount/dir/../test.html");
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6027. }
  6028. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6029. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6031. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6032. }
  6033. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6034. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6037. }
  6038. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6039. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6041. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6042. }
  6043. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6044. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6047. }
  6048. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6049. auto res = cli_.Get("/mount/dir");
  6050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6051. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6052. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6053. }
  6054. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6055. auto res = cli_.Get("//dir");
  6056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6057. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6058. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6059. }
  6060. TEST_F(ServerTest, PostMethod303) {
  6061. auto res = cli_.Post("/1", "body", "text/plain");
  6062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6063. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6064. EXPECT_EQ("/2", res->get_header_value("Location"));
  6065. }
  6066. TEST_F(ServerTest, PostMethod303Redirect) {
  6067. cli_.set_follow_location(true);
  6068. auto res = cli_.Post("/1", "body", "text/plain");
  6069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6070. EXPECT_EQ(StatusCode::OK_200, res->status);
  6071. EXPECT_EQ("redirected.", res->body);
  6072. EXPECT_EQ("/2", res->location);
  6073. }
  6074. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6075. auto res = cli_.Get("/dir/test.abcde");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::OK_200, res->status);
  6078. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6079. EXPECT_EQ("abcde", res->body);
  6080. }
  6081. TEST_F(ServerTest, StaticFileRange) {
  6082. auto res =
  6083. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6085. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6086. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6087. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6088. EXPECT_EQ(true, res->has_header("Content-Range"));
  6089. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6090. EXPECT_EQ(std::string("cd"), res->body);
  6091. }
  6092. TEST_F(ServerTest, StaticFileRanges) {
  6093. auto res = cli_.Get("/dir/test.abcde",
  6094. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6096. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6097. EXPECT_TRUE(
  6098. res->get_header_value("Content-Type")
  6099. .find(
  6100. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6101. 0);
  6102. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6103. }
  6104. TEST_F(ServerTest, StaticFileRangeHead) {
  6105. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6107. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6108. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6109. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6110. EXPECT_EQ(true, res->has_header("Content-Range"));
  6111. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6112. }
  6113. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6114. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6116. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6118. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6119. EXPECT_EQ(true, res->has_header("Content-Range"));
  6120. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6121. res->get_header_value("Content-Range"));
  6122. EXPECT_EQ("LAST\n", res->body);
  6123. }
  6124. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6125. auto res =
  6126. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6128. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6129. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6130. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6131. EXPECT_EQ(true, res->has_header("Content-Range"));
  6132. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6133. }
  6134. TEST_F(ServerTest, StaticFileBigFile) {
  6135. auto res = cli_.Get("/dir/1MB.txt");
  6136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6137. EXPECT_EQ(StatusCode::OK_200, res->status);
  6138. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6139. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6140. }
  6141. TEST_F(ServerTest, InvalidBaseDirMount) {
  6142. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6143. }
  6144. TEST_F(ServerTest, Binary) {
  6145. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6146. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6147. "application/octet-stream");
  6148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6149. ASSERT_EQ(StatusCode::OK_200, res->status);
  6150. ASSERT_EQ(4U, res->body.size());
  6151. res = cli_.Put("/binary", binary.data(), binary.size(),
  6152. "application/octet-stream");
  6153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6154. ASSERT_EQ(StatusCode::OK_200, res->status);
  6155. ASSERT_EQ(4U, res->body.size());
  6156. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6157. "application/octet-stream");
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. ASSERT_EQ(StatusCode::OK_200, res->status);
  6160. ASSERT_EQ(4U, res->body.size());
  6161. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6162. "application/octet-stream");
  6163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6164. ASSERT_EQ(StatusCode::OK_200, res->status);
  6165. ASSERT_EQ(4U, res->body.size());
  6166. }
  6167. TEST_F(ServerTest, BinaryString) {
  6168. auto binary = std::string("\x00\x01\x02\x03", 4);
  6169. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6171. ASSERT_EQ(StatusCode::OK_200, res->status);
  6172. ASSERT_EQ(4U, res->body.size());
  6173. res = cli_.Put("/binary", binary, "application/octet-stream");
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. ASSERT_EQ(StatusCode::OK_200, res->status);
  6176. ASSERT_EQ(4U, res->body.size());
  6177. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6179. ASSERT_EQ(StatusCode::OK_200, res->status);
  6180. ASSERT_EQ(4U, res->body.size());
  6181. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6183. ASSERT_EQ(StatusCode::OK_200, res->status);
  6184. ASSERT_EQ(4U, res->body.size());
  6185. }
  6186. TEST_F(ServerTest, EmptyRequest) {
  6187. auto res = cli_.Get("");
  6188. ASSERT_TRUE(!res);
  6189. EXPECT_EQ(Error::Connection, res.error());
  6190. }
  6191. TEST_F(ServerTest, LongRequest) {
  6192. std::string request;
  6193. for (size_t i = 0; i < 545; i++) {
  6194. request += "/TooLongRequest";
  6195. }
  6196. request += "OK";
  6197. auto res = cli_.Get(request.c_str());
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6200. }
  6201. TEST_F(ServerTest, TooLongRequest) {
  6202. std::string request;
  6203. for (size_t i = 0; i < 546; i++) {
  6204. request += "/TooLongRequest";
  6205. }
  6206. request += "_NG";
  6207. auto start = std::chrono::high_resolution_clock::now();
  6208. cli_.set_keep_alive(true);
  6209. auto res = cli_.Get(request.c_str());
  6210. auto end = std::chrono::high_resolution_clock::now();
  6211. auto elapsed =
  6212. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6213. .count();
  6214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6215. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6216. EXPECT_LE(elapsed, 1000);
  6217. EXPECT_EQ("close", res->get_header_value("Connection"));
  6218. EXPECT_FALSE(cli_.is_socket_open());
  6219. }
  6220. TEST_F(ServerTest, AlmostTooLongRequest) {
  6221. // test for #2046 - URI length check shouldn't include other content on req
  6222. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6223. // leading /, space, HTTP/1.1)
  6224. std::string request =
  6225. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6226. auto res = cli_.Get(request.c_str());
  6227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6228. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6229. }
  6230. TEST_F(ServerTest, LongHeader) {
  6231. Request req;
  6232. req.method = "GET";
  6233. req.path = "/hi";
  6234. std::string host_and_port;
  6235. host_and_port += HOST;
  6236. host_and_port += ":";
  6237. host_and_port += std::to_string(PORT);
  6238. req.headers.emplace("Host", host_and_port.c_str());
  6239. req.headers.emplace("Accept", "*/*");
  6240. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6241. req.headers.emplace(
  6242. "Header-Name",
  6243. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6244. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6245. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6246. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6247. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6248. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6249. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6250. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6251. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6252. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6253. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6254. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6255. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6256. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6257. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6271. "@@@@@@@@@@@@@@@@");
  6272. auto res = std::make_shared<Response>();
  6273. auto error = Error::Success;
  6274. auto ret = cli_.send(req, *res, error);
  6275. ASSERT_TRUE(ret);
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. }
  6278. TEST_F(ServerTest, LongQueryValue) {
  6279. auto start = std::chrono::high_resolution_clock::now();
  6280. cli_.set_keep_alive(true);
  6281. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6282. auto end = std::chrono::high_resolution_clock::now();
  6283. auto elapsed =
  6284. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6285. .count();
  6286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6287. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6288. EXPECT_LE(elapsed, 1000);
  6289. EXPECT_EQ("close", res->get_header_value("Connection"));
  6290. EXPECT_FALSE(cli_.is_socket_open());
  6291. }
  6292. TEST_F(ServerTest, TooLongQueryValue) {
  6293. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6294. ASSERT_FALSE(res);
  6295. EXPECT_EQ(Error::Read, res.error());
  6296. }
  6297. TEST_F(ServerTest, TooLongHeader) {
  6298. Request req;
  6299. req.method = "GET";
  6300. req.path = "/hi";
  6301. std::string host_and_port;
  6302. host_and_port += HOST;
  6303. host_and_port += ":";
  6304. host_and_port += std::to_string(PORT);
  6305. req.headers.emplace("Host", host_and_port.c_str());
  6306. req.headers.emplace("Accept", "*/*");
  6307. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6308. req.headers.emplace(
  6309. "Header-Name",
  6310. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6311. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6312. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6313. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6314. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6315. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6316. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6317. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6318. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6319. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6320. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6321. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6322. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6323. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6324. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6325. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6326. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6327. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6328. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6329. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6330. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6331. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6332. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6333. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6334. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6335. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6336. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6337. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6338. "@@@@@@@@@@@@@@@@@");
  6339. auto res = std::make_shared<Response>();
  6340. auto error = Error::Success;
  6341. auto ret = cli_.send(req, *res, error);
  6342. ASSERT_TRUE(ret);
  6343. EXPECT_EQ(StatusCode::OK_200, res->status);
  6344. }
  6345. TEST_F(ServerTest, HeaderCountAtLimit) {
  6346. // Test with headers just under the 100 limit
  6347. httplib::Headers headers;
  6348. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6349. // This should keep us just under the 100 header limit
  6350. for (int i = 0; i < 95; i++) {
  6351. std::string name = "X-Test-Header-" + std::to_string(i);
  6352. std::string value = "value" + std::to_string(i);
  6353. headers.emplace(name, value);
  6354. }
  6355. // This should work fine as we're under the limit
  6356. auto res = cli_.Get("/hi", headers);
  6357. EXPECT_TRUE(res);
  6358. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6359. }
  6360. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6361. // Test with many headers to exceed the 100 limit
  6362. httplib::Headers headers;
  6363. // Add 150 headers to definitely exceed the 100 limit
  6364. for (int i = 0; i < 150; i++) {
  6365. std::string name = "X-Test-Header-" + std::to_string(i);
  6366. std::string value = "value" + std::to_string(i);
  6367. headers.emplace(name, value);
  6368. }
  6369. // This should fail due to exceeding header count limit
  6370. cli_.set_keep_alive(true);
  6371. auto res = cli_.Get("/hi", headers);
  6372. // The server should respond with 400 Bad Request
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6375. EXPECT_EQ("close", res->get_header_value("Connection"));
  6376. EXPECT_FALSE(cli_.is_socket_open());
  6377. }
  6378. TEST_F(ServerTest, PercentEncoding) {
  6379. auto res = cli_.Get("/e%6edwith%");
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. EXPECT_EQ(StatusCode::OK_200, res->status);
  6382. }
  6383. TEST_F(ServerTest, PercentEncodingUnicode) {
  6384. auto res = cli_.Get("/e%u006edwith%");
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. EXPECT_EQ(StatusCode::OK_200, res->status);
  6387. }
  6388. TEST_F(ServerTest, InvalidPercentEncoding) {
  6389. auto res = cli_.Get("/%endwith%");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6392. }
  6393. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6394. auto res = cli_.Get("/%uendwith%");
  6395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6396. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6397. }
  6398. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6399. auto res = cli_.Get("/hello?aaa=bbb%");
  6400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6401. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6402. }
  6403. TEST_F(ServerTest, PlusSignEncoding) {
  6404. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6406. EXPECT_EQ(StatusCode::OK_200, res->status);
  6407. EXPECT_EQ("a +b", res->body);
  6408. }
  6409. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6410. // This test simulates a potential DoS attack using many headers
  6411. // to verify our security fix prevents memory exhaustion
  6412. httplib::Headers attack_headers;
  6413. // Attempt to add many headers like an attacker would (200 headers to far
  6414. // exceed limit)
  6415. for (int i = 0; i < 200; i++) {
  6416. std::string name = "X-Attack-Header-" + std::to_string(i);
  6417. std::string value = "attack_payload_" + std::to_string(i);
  6418. attack_headers.emplace(name, value);
  6419. }
  6420. // Try to POST with excessive headers
  6421. cli_.set_keep_alive(true);
  6422. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6423. // Should either fail or return 400 Bad Request due to security limit
  6424. if (res) {
  6425. // If we get a response, it should be 400 Bad Request
  6426. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6427. EXPECT_EQ("close", res->get_header_value("Connection"));
  6428. }
  6429. EXPECT_FALSE(cli_.is_socket_open());
  6430. }
  6431. TEST_F(ServerTest, MultipartFormData) {
  6432. UploadFormDataItems items = {
  6433. {"text1", "text default", "", ""},
  6434. {"text2", "aωb", "", ""},
  6435. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6436. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6437. {"file3", "", "", "application/octet-stream"},
  6438. {"file4", "", "", " application/json tmp-string "}};
  6439. auto res = cli_.Post("/multipart", items);
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. }
  6443. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6444. UploadFormDataItems items = {
  6445. {"text", "default text", "", ""},
  6446. {"multi_text1", "aaaaa", "", ""},
  6447. {"multi_text1", "bbbbb", "", ""},
  6448. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6449. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6450. "application/json"},
  6451. };
  6452. auto res = cli_.Post("/multipart/multi_file_values", items);
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. }
  6456. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6457. auto res = cli_.Get("/hi");
  6458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6459. EXPECT_EQ(StatusCode::OK_200, res->status);
  6460. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6461. EXPECT_EQ("Hello World!", res->body);
  6462. }
  6463. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6464. Request req;
  6465. req.method = "POST";
  6466. req.path = "/chunked";
  6467. std::string host_and_port;
  6468. host_and_port += HOST;
  6469. host_and_port += ":";
  6470. host_and_port += std::to_string(PORT);
  6471. req.headers.emplace("Host", host_and_port.c_str());
  6472. req.headers.emplace("Accept", "*/*");
  6473. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6474. req.headers.emplace("Content-Type", "text/plain");
  6475. req.headers.emplace("Content-Length", "0");
  6476. req.headers.emplace(
  6477. "Transfer-Encoding",
  6478. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6479. // Client does not chunk, so make a chunked body manually.
  6480. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6481. auto res = std::make_shared<Response>();
  6482. auto error = Error::Success;
  6483. auto ret = cli_.send(req, *res, error);
  6484. ASSERT_TRUE(ret);
  6485. EXPECT_EQ(StatusCode::OK_200, res->status);
  6486. }
  6487. template <typename ClientT>
  6488. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6489. int expected_status) {
  6490. Request req;
  6491. req.method = "POST";
  6492. req.path = "/chunked";
  6493. std::string host_and_port;
  6494. host_and_port += HOST;
  6495. host_and_port += ":";
  6496. host_and_port += std::to_string(PORT);
  6497. req.headers.emplace("Host", host_and_port.c_str());
  6498. req.headers.emplace("Content-Length", "0");
  6499. req.headers.emplace("Transfer-Encoding", "chunked");
  6500. req.body = body;
  6501. auto res = std::make_shared<Response>();
  6502. auto error = Error::Success;
  6503. ASSERT_TRUE(cli.send(req, *res, error));
  6504. EXPECT_EQ(expected_status, res->status);
  6505. }
  6506. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6507. // rather than treat them as valid lengths.
  6508. template <typename ClientT>
  6509. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6510. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6511. }
  6512. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6513. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6514. }
  6515. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6516. expect_chunked_body_rejected(
  6517. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6518. }
  6519. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6520. // chunk-size line carries no CR, LF or other control character ahead of its
  6521. // terminator. Such a line must be refused rather than read as extension text.
  6522. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6523. expect_chunked_body_rejected(
  6524. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6525. }
  6526. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6527. expect_chunked_body_rejected(
  6528. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6529. }
  6530. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6531. expect_chunked_body_rejected(
  6532. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6533. }
  6534. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6535. // The literal stays split: a hex escape consumes every hex digit that
  6536. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6537. expect_chunked_body_rejected(
  6538. cli_, "4;a\x01"
  6539. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6540. }
  6541. TEST_F(ServerTest, AcceptsChunkExtension) {
  6542. expect_chunked_body_status(cli_,
  6543. "4;name=value\r\ndech\r\n"
  6544. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6545. "0;last\r\n\r\n",
  6546. StatusCode::OK_200);
  6547. }
  6548. TEST_F(ServerTest, GetStreamed2) {
  6549. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6552. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6553. EXPECT_EQ(true, res->has_header("Content-Range"));
  6554. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6555. EXPECT_EQ(std::string("ab"), res->body);
  6556. }
  6557. TEST_F(ServerTest, GetStreamed) {
  6558. auto res = cli_.Get("/streamed");
  6559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6560. EXPECT_EQ(StatusCode::OK_200, res->status);
  6561. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6562. EXPECT_EQ(std::string("aaabbb"), res->body);
  6563. }
  6564. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6565. auto res = cli_.Get("/streamed-without-length",
  6566. Headers{make_range_header({{0, -1}})});
  6567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6568. EXPECT_EQ(StatusCode::OK_200, res->status);
  6569. EXPECT_EQ(false, res->has_header("Content-Length"));
  6570. EXPECT_EQ(false, res->has_header("Content-Range"));
  6571. EXPECT_EQ(std::string("abcdefg"), res->body);
  6572. }
  6573. TEST_F(ServerTest, GetStreamedWithRange1) {
  6574. auto res =
  6575. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6577. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6578. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6579. EXPECT_EQ(true, res->has_header("Content-Range"));
  6580. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6581. EXPECT_EQ(std::string("def"), res->body);
  6582. }
  6583. TEST_F(ServerTest, GetStreamedWithRange2) {
  6584. auto res =
  6585. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6587. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6588. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6589. EXPECT_EQ(true, res->has_header("Content-Range"));
  6590. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6591. EXPECT_EQ(std::string("bcdefg"), res->body);
  6592. }
  6593. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6594. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6596. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6597. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6598. EXPECT_EQ(true, res->has_header("Content-Range"));
  6599. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6600. EXPECT_EQ(std::string("efg"), res->body);
  6601. }
  6602. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6603. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6604. // the entire representation.
  6605. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6606. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6608. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6609. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6610. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6611. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6612. }
  6613. }
  6614. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6615. auto res =
  6616. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6619. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6620. EXPECT_EQ(false, res->has_header("Content-Range"));
  6621. EXPECT_EQ(0U, res->body.size());
  6622. }
  6623. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6624. // Only a 206 is served as a partial representation. Under any other status
  6625. // `apply_ranges()` reported the full content length, so the body must match
  6626. // that header, and the content provider must never be asked for an offset
  6627. // outside the representation.
  6628. auto check = [&](int status, const char *range) {
  6629. auto path =
  6630. std::string("/streamed-with-range?status=") + std::to_string(status);
  6631. auto ctx = path + " Range: " + range;
  6632. auto res = cli_.Get(path, Headers{{"Range", range}});
  6633. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6634. EXPECT_EQ(status, res->status) << ctx;
  6635. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6636. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6637. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6638. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6639. };
  6640. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6641. check(403, "bytes=3-5");
  6642. // The offset is far past the representation.
  6643. check(403, "bytes=100000-100200");
  6644. // `first_pos` is still -1 here, and the bounds asserts in
  6645. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6646. check(403, "bytes=-3");
  6647. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6648. // multipart branch would have written one that is empty.
  6649. check(403, "bytes=1-2, 4-5");
  6650. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6651. // covers the whole representation.
  6652. check(200, "bytes=3-5");
  6653. check(200, "bytes=1-2, 4-5");
  6654. }
  6655. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6656. auto res =
  6657. cli_.Get("/streamed-with-range",
  6658. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6659. "92233720368547758079223372036854775807"}});
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6662. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6663. EXPECT_EQ(false, res->has_header("Content-Range"));
  6664. EXPECT_EQ(0U, res->body.size());
  6665. }
  6666. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6667. auto res = cli_.Get(
  6668. "/with-range",
  6669. Headers{{"Range",
  6670. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6671. {"Accept-Encoding", ""}});
  6672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6673. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6674. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6675. EXPECT_EQ(true, res->has_header("Content-Range"));
  6676. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6677. EXPECT_EQ(std::string("abcdefg"), res->body);
  6678. }
  6679. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6680. auto res = cli_.Get("/with-range", Headers{
  6681. {"Range", "bytes=0-"},
  6682. {"Accept-Encoding", ""},
  6683. });
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6686. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6687. EXPECT_EQ(true, res->has_header("Content-Range"));
  6688. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6689. EXPECT_EQ(std::string("abcdefg"), res->body);
  6690. }
  6691. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6692. auto res = cli_.Get("/streamed-with-range",
  6693. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6696. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6697. EXPECT_EQ(false, res->has_header("Content-Range"));
  6698. EXPECT_EQ(267U, res->body.size());
  6699. // Check that both range contents are present
  6700. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6701. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6702. // Check that Content-Range headers are present for both ranges
  6703. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6704. std::string::npos);
  6705. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6706. std::string::npos);
  6707. }
  6708. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6709. Ranges ranges;
  6710. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6711. ranges.emplace_back(0, -1);
  6712. }
  6713. auto res = cli_.Get("/streamed-with-range?error",
  6714. Headers{{make_range_header(ranges)}});
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6717. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6718. EXPECT_EQ(false, res->has_header("Content-Range"));
  6719. EXPECT_EQ(0U, res->body.size());
  6720. }
  6721. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6722. auto res = cli_.Get("/streamed-with-range",
  6723. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6725. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6726. EXPECT_EQ(5U, res->body.size());
  6727. // Check that overlapping ranges are coalesced into a single range
  6728. EXPECT_EQ("bcdef", res->body);
  6729. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6730. // Should be single range, not multipart
  6731. EXPECT_TRUE(res->has_header("Content-Range"));
  6732. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6733. }
  6734. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6735. auto res = cli_.Get("/streamed-with-range",
  6736. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6738. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6739. EXPECT_EQ(268U, res->body.size());
  6740. // Check that both range contents are present
  6741. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6742. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6743. // Check that Content-Range headers are present for both ranges
  6744. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6745. std::string::npos);
  6746. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6747. std::string::npos);
  6748. }
  6749. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6750. auto res = cli_.Get("/streamed-with-range",
  6751. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6753. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6754. EXPECT_EQ(269U, res->body.size());
  6755. // Check that both duplicate range contents are present
  6756. size_t first_abc = res->body.find("abc\r\n");
  6757. EXPECT_TRUE(first_abc != std::string::npos);
  6758. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6759. EXPECT_TRUE(second_abc != std::string::npos);
  6760. // Check that Content-Range headers are present for both ranges
  6761. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6762. EXPECT_TRUE(first_range != std::string::npos);
  6763. size_t second_range =
  6764. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6765. EXPECT_TRUE(second_range != std::string::npos);
  6766. }
  6767. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6768. auto res =
  6769. cli_.Get("/streamed-with-range?error",
  6770. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6773. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6774. EXPECT_EQ(false, res->has_header("Content-Range"));
  6775. EXPECT_EQ(0U, res->body.size());
  6776. }
  6777. TEST_F(ServerTest, GetStreamedEndless) {
  6778. uint64_t offset = 0;
  6779. auto res = cli_.Get("/streamed-cancel",
  6780. [&](const char * /*data*/, uint64_t data_length) {
  6781. if (offset < 100) {
  6782. offset += data_length;
  6783. return true;
  6784. }
  6785. return false;
  6786. });
  6787. ASSERT_TRUE(!res);
  6788. EXPECT_EQ(Error::Canceled, res.error());
  6789. }
  6790. TEST_F(ServerTest, ClientStop) {
  6791. std::atomic_size_t count{4};
  6792. std::vector<std::thread> threads;
  6793. for (auto i = count.load(); i != 0; --i) {
  6794. threads.emplace_back([&]() {
  6795. auto res = cli_.Get("/streamed-cancel",
  6796. [&](const char *, uint64_t) { return true; });
  6797. --count;
  6798. ASSERT_TRUE(!res);
  6799. EXPECT_TRUE(res.error() == Error::Canceled ||
  6800. res.error() == Error::Read || res.error() == Error::Write);
  6801. });
  6802. }
  6803. std::this_thread::sleep_for(std::chrono::seconds(2));
  6804. while (count != 0) {
  6805. cli_.stop();
  6806. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6807. }
  6808. for (auto &t : threads) {
  6809. t.join();
  6810. }
  6811. }
  6812. TEST_F(ServerTest, GetWithRange1) {
  6813. auto res = cli_.Get("/with-range", Headers{
  6814. make_range_header({{3, 5}}),
  6815. {"Accept-Encoding", ""},
  6816. });
  6817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6818. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6819. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6820. EXPECT_EQ(true, res->has_header("Content-Range"));
  6821. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6822. EXPECT_EQ(std::string("def"), res->body);
  6823. }
  6824. TEST_F(ServerTest, GetWithRange2) {
  6825. auto res = cli_.Get("/with-range", Headers{
  6826. make_range_header({{1, -1}}),
  6827. {"Accept-Encoding", ""},
  6828. });
  6829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6830. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6831. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6832. EXPECT_EQ(true, res->has_header("Content-Range"));
  6833. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6834. EXPECT_EQ(std::string("bcdefg"), res->body);
  6835. }
  6836. TEST_F(ServerTest, GetWithRange3) {
  6837. auto res = cli_.Get("/with-range", Headers{
  6838. make_range_header({{0, 0}}),
  6839. {"Accept-Encoding", ""},
  6840. });
  6841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6842. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6843. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6844. EXPECT_EQ(true, res->has_header("Content-Range"));
  6845. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6846. EXPECT_EQ(std::string("a"), res->body);
  6847. }
  6848. TEST_F(ServerTest, GetWithRange4) {
  6849. auto res = cli_.Get("/with-range", Headers{
  6850. make_range_header({{-1, 2}}),
  6851. {"Accept-Encoding", ""},
  6852. });
  6853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6854. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6855. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6856. EXPECT_EQ(true, res->has_header("Content-Range"));
  6857. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6858. EXPECT_EQ(std::string("fg"), res->body);
  6859. }
  6860. TEST_F(ServerTest, GetWithRange5) {
  6861. auto res = cli_.Get("/with-range", Headers{
  6862. make_range_header({{0, 5}}),
  6863. {"Accept-Encoding", ""},
  6864. });
  6865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6866. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6867. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6868. EXPECT_EQ(true, res->has_header("Content-Range"));
  6869. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6870. EXPECT_EQ(std::string("abcdef"), res->body);
  6871. }
  6872. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6873. auto res =
  6874. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6876. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6877. }
  6878. TEST_F(ServerTest, GetWithRangeMultipart) {
  6879. auto res =
  6880. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6883. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6884. EXPECT_EQ(false, res->has_header("Content-Range"));
  6885. EXPECT_EQ(267U, res->body.size());
  6886. }
  6887. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6888. auto res = cli_.Get("/with-range",
  6889. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6891. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6892. }
  6893. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6894. auto res = cli_.Get("/with-range-customized-response",
  6895. Headers{{make_range_header({{1, 2}})}});
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6898. EXPECT_EQ(true, res->has_header("Content-Length"));
  6899. EXPECT_EQ(false, res->has_header("Content-Range"));
  6900. EXPECT_EQ(JSON_DATA, res->body);
  6901. }
  6902. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6903. auto res = cli_.Get("/with-range-customized-response",
  6904. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6907. EXPECT_EQ(true, res->has_header("Content-Length"));
  6908. EXPECT_EQ(false, res->has_header("Content-Range"));
  6909. EXPECT_EQ(JSON_DATA, res->body);
  6910. }
  6911. TEST_F(ServerTest, Issue1772) {
  6912. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6914. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6915. }
  6916. TEST_F(ServerTest, Issue609) {
  6917. auto res = cli_.Delete("/issue609");
  6918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6919. EXPECT_EQ(StatusCode::OK_200, res->status);
  6920. EXPECT_EQ(std::string("ok"), res->body);
  6921. }
  6922. TEST_F(ServerTest, GetStreamedChunked) {
  6923. auto res = cli_.Get("/streamed-chunked");
  6924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6925. EXPECT_EQ(StatusCode::OK_200, res->status);
  6926. EXPECT_EQ(std::string("123456789"), res->body);
  6927. }
  6928. TEST_F(ServerTest, GetStreamedChunked2) {
  6929. auto res = cli_.Get("/streamed-chunked2");
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::OK_200, res->status);
  6932. EXPECT_EQ(std::string("123456789"), res->body);
  6933. }
  6934. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6935. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6937. EXPECT_EQ(StatusCode::OK_200, res->status);
  6938. EXPECT_EQ(std::string("123456789"), res->body);
  6939. EXPECT_TRUE(res->has_header("Trailer"));
  6940. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6941. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6942. // Trailers are now stored separately from headers (security fix)
  6943. EXPECT_EQ(2U, res->trailers.size());
  6944. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6945. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6946. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6947. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6948. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6949. // Verify trailers are NOT in headers (security verification)
  6950. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6951. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6952. }
  6953. TEST_F(ServerTest, LargeChunkedPost) {
  6954. Request req;
  6955. req.method = "POST";
  6956. req.path = "/large-chunked";
  6957. std::string host_and_port;
  6958. host_and_port += HOST;
  6959. host_and_port += ":";
  6960. host_and_port += std::to_string(PORT);
  6961. req.headers.emplace("Host", host_and_port.c_str());
  6962. req.headers.emplace("Accept", "*/*");
  6963. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6964. req.headers.emplace("Content-Type", "text/plain");
  6965. req.headers.emplace("Content-Length", "0");
  6966. req.headers.emplace("Transfer-Encoding", "chunked");
  6967. std::string long_string(30 * 1024u, 'a');
  6968. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6969. // Attempt to make a large enough post to exceed OS buffers, to test that
  6970. // the server handles short reads if the full chunk data isn't available.
  6971. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6972. auto res = std::make_shared<Response>();
  6973. auto error = Error::Success;
  6974. auto ret = cli_.send(req, *res, error);
  6975. ASSERT_TRUE(ret);
  6976. EXPECT_EQ(StatusCode::OK_200, res->status);
  6977. }
  6978. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6979. auto res = cli_.Get("/remote_addr");
  6980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6981. EXPECT_EQ(StatusCode::OK_200, res->status);
  6982. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6983. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6984. }
  6985. TEST_F(ServerTest, GetMethodLocalAddr) {
  6986. auto res = cli_.Get("/local_addr");
  6987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6988. EXPECT_EQ(StatusCode::OK_200, res->status);
  6989. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6990. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6991. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6992. }
  6993. TEST_F(ServerTest, HTTPResponseSplitting) {
  6994. auto res = cli_.Get("/http_response_splitting");
  6995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6996. EXPECT_EQ(StatusCode::OK_200, res->status);
  6997. }
  6998. TEST_F(ServerTest, SlowRequest) {
  6999. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7000. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7001. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7002. }
  7003. #if 0
  7004. TEST_F(ServerTest, SlowPost) {
  7005. char buffer[64 * 1024];
  7006. memset(buffer, 0x42, sizeof(buffer));
  7007. auto res = cli_.Post(
  7008. "/slowpost", 64 * 1024 * 1024,
  7009. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7010. auto ret = sink.write(buffer, sizeof(buffer));
  7011. EXPECT_TRUE(ret);
  7012. return true;
  7013. },
  7014. "text/plain");
  7015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7016. EXPECT_EQ(StatusCode::OK_200, res->status);
  7017. }
  7018. TEST_F(ServerTest, SlowPostFail) {
  7019. char buffer[64 * 1024];
  7020. memset(buffer, 0x42, sizeof(buffer));
  7021. cli_.set_write_timeout(std::chrono::seconds(0));
  7022. auto res = cli_.Post(
  7023. "/slowpost", 64 * 1024 * 1024,
  7024. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7025. sink.write(buffer, sizeof(buffer));
  7026. return true;
  7027. },
  7028. "text/plain");
  7029. ASSERT_TRUE(!res);
  7030. EXPECT_EQ(Error::Write, res.error());
  7031. }
  7032. #endif
  7033. TEST_F(ServerTest, Put) {
  7034. auto res = cli_.Put("/put", "PUT", "text/plain");
  7035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7036. EXPECT_EQ(StatusCode::OK_200, res->status);
  7037. EXPECT_EQ("PUT", res->body);
  7038. }
  7039. TEST_F(ServerTest, PutWithContentProvider) {
  7040. auto res = cli_.Put(
  7041. "/put", 3,
  7042. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7043. sink.os << "PUT";
  7044. return true;
  7045. },
  7046. "text/plain");
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. EXPECT_EQ("PUT", res->body);
  7050. }
  7051. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7052. auto res = cli_.Post(
  7053. "/post", 42,
  7054. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7055. return false;
  7056. },
  7057. "text/plain");
  7058. ASSERT_TRUE(!res);
  7059. EXPECT_EQ(Error::Canceled, res.error());
  7060. }
  7061. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7062. auto res = cli_.Put(
  7063. "/put",
  7064. [](size_t /*offset*/, DataSink &sink) {
  7065. sink.os << "PUT";
  7066. sink.done();
  7067. return true;
  7068. },
  7069. "text/plain");
  7070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7071. EXPECT_EQ(StatusCode::OK_200, res->status);
  7072. EXPECT_EQ("PUT", res->body);
  7073. }
  7074. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7075. auto res = cli_.Post(
  7076. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7077. "text/plain");
  7078. ASSERT_TRUE(!res);
  7079. EXPECT_EQ(Error::Canceled, res.error());
  7080. }
  7081. TEST_F(ServerTest, PostLoopBack) {
  7082. std::string body;
  7083. auto res = cli_.Post(
  7084. "/post-loopback", 9,
  7085. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7086. EXPECT_EQ(9u, length);
  7087. sink.write("123", 3);
  7088. sink.write("456", 3);
  7089. sink.write("789", 3);
  7090. return true;
  7091. },
  7092. "text/plain",
  7093. [&body](const char *data, size_t data_length) {
  7094. body.append(data, data_length);
  7095. return true;
  7096. });
  7097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7098. EXPECT_EQ(StatusCode::OK_200, res->status);
  7099. EXPECT_EQ("123456789", body);
  7100. }
  7101. TEST_F(ServerTest, PutLoopBack) {
  7102. std::string body;
  7103. auto res = cli_.Put(
  7104. "/put-loopback", 9,
  7105. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7106. EXPECT_EQ(9u, length);
  7107. sink.write("123", 3);
  7108. sink.write("456", 3);
  7109. sink.write("789", 3);
  7110. return true;
  7111. },
  7112. "text/plain",
  7113. [&body](const char *data, size_t data_length) {
  7114. body.append(data, data_length);
  7115. return true;
  7116. });
  7117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7118. EXPECT_EQ(StatusCode::OK_200, res->status);
  7119. EXPECT_EQ("123456789", body);
  7120. }
  7121. TEST_F(ServerTest, PatchLoopBack) {
  7122. std::string body;
  7123. auto res = cli_.Patch(
  7124. "/patch-loopback", 9,
  7125. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7126. EXPECT_EQ(9u, length);
  7127. sink.write("123", 3);
  7128. sink.write("456", 3);
  7129. sink.write("789", 3);
  7130. return true;
  7131. },
  7132. "text/plain",
  7133. [&body](const char *data, size_t data_length) {
  7134. body.append(data, data_length);
  7135. return true;
  7136. });
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::OK_200, res->status);
  7139. EXPECT_EQ("123456789", body);
  7140. }
  7141. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7142. std::string body;
  7143. auto res = cli_.Post(
  7144. "/post-loopback",
  7145. [](size_t /*offset*/, DataSink &sink) {
  7146. sink.write("123", 3);
  7147. sink.write("456", 3);
  7148. sink.write("789", 3);
  7149. sink.done();
  7150. return true;
  7151. },
  7152. "text/plain",
  7153. [&body](const char *data, size_t data_length) {
  7154. body.append(data, data_length);
  7155. return true;
  7156. });
  7157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7158. EXPECT_EQ(StatusCode::OK_200, res->status);
  7159. EXPECT_EQ("123456789", body);
  7160. }
  7161. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7162. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7163. cli_.set_compress(true);
  7164. auto res = cli_.Put(
  7165. "/put", 3,
  7166. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7167. sink.os << "PUT";
  7168. return true;
  7169. },
  7170. "text/plain");
  7171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7172. EXPECT_EQ(StatusCode::OK_200, res->status);
  7173. EXPECT_EQ("PUT", res->body);
  7174. }
  7175. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7176. cli_.set_compress(true);
  7177. auto res = cli_.Post(
  7178. "/post", 42,
  7179. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7180. return false;
  7181. },
  7182. "text/plain");
  7183. ASSERT_TRUE(!res);
  7184. EXPECT_EQ(Error::Canceled, res.error());
  7185. }
  7186. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7187. cli_.set_compress(true);
  7188. auto res = cli_.Put(
  7189. "/put",
  7190. [](size_t /*offset*/, DataSink &sink) {
  7191. sink.os << "PUT";
  7192. sink.done();
  7193. return true;
  7194. },
  7195. "text/plain");
  7196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7197. EXPECT_EQ(StatusCode::OK_200, res->status);
  7198. EXPECT_EQ("PUT", res->body);
  7199. }
  7200. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7201. cli_.set_compress(true);
  7202. auto res = cli_.Post(
  7203. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7204. "text/plain");
  7205. ASSERT_TRUE(!res);
  7206. EXPECT_EQ(Error::Canceled, res.error());
  7207. }
  7208. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7209. cli_.set_compress(true);
  7210. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7212. EXPECT_EQ(StatusCode::OK_200, res->status);
  7213. EXPECT_EQ(LARGE_DATA, res->body);
  7214. }
  7215. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7216. #ifdef CPPHTTPLIB_SSL_ENABLED
  7217. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7218. Client cli(s.c_str());
  7219. cli.enable_server_certificate_verification(false);
  7220. #else
  7221. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7222. Client cli(s.c_str());
  7223. #endif
  7224. cli.set_compress(true);
  7225. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7227. EXPECT_EQ(StatusCode::OK_200, res->status);
  7228. EXPECT_EQ(LARGE_DATA, res->body);
  7229. // The compressed size should be less than a 10th of the original. May vary
  7230. // depending on the zlib library.
  7231. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7232. static_cast<uint64_t>(10 * 1024 * 1024));
  7233. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7234. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7235. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7236. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7237. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7238. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7239. #endif
  7240. }
  7241. TEST_F(ServerTest, PutContentWithDeflate) {
  7242. cli_.set_compress(false);
  7243. Headers headers;
  7244. headers.emplace("Content-Encoding", "deflate");
  7245. // PUT in deflate format:
  7246. auto res = cli_.Put("/put", headers,
  7247. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7249. EXPECT_EQ(StatusCode::OK_200, res->status);
  7250. EXPECT_EQ("PUT", res->body);
  7251. }
  7252. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7253. Headers headers;
  7254. headers.emplace("Accept-Encoding", "gzip, deflate");
  7255. auto res = cli_.Get("/streamed-chunked", headers);
  7256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7257. EXPECT_EQ(StatusCode::OK_200, res->status);
  7258. EXPECT_EQ(std::string("123456789"), res->body);
  7259. }
  7260. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7261. Headers headers;
  7262. headers.emplace("Accept-Encoding", "gzip, deflate");
  7263. auto res = cli_.Get("/streamed-chunked2", headers);
  7264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7265. EXPECT_EQ(StatusCode::OK_200, res->status);
  7266. EXPECT_EQ(std::string("123456789"), res->body);
  7267. }
  7268. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7269. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. }
  7273. TEST(GzipDecompressor, ChunkedDecompression) {
  7274. std::string data;
  7275. for (size_t i = 0; i < 32 * 1024; ++i) {
  7276. data.push_back(static_cast<char>('a' + i % 26));
  7277. }
  7278. std::string compressed_data;
  7279. {
  7280. httplib::detail::gzip_compressor compressor;
  7281. bool result = compressor.compress(
  7282. data.data(), data.size(),
  7283. /*last=*/true,
  7284. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7285. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7286. compressed_data_size);
  7287. return true;
  7288. });
  7289. ASSERT_TRUE(result);
  7290. }
  7291. std::string decompressed_data;
  7292. {
  7293. httplib::detail::gzip_decompressor decompressor;
  7294. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7295. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7296. size_t chunk_size = 130;
  7297. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7298. chunk_begin += chunk_size) {
  7299. size_t current_chunk_size =
  7300. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7301. bool result = decompressor.decompress(
  7302. compressed_data.data() + chunk_begin, current_chunk_size,
  7303. [&](const char *decompressed_data_chunk,
  7304. size_t decompressed_data_chunk_size) {
  7305. decompressed_data.insert(decompressed_data.size(),
  7306. decompressed_data_chunk,
  7307. decompressed_data_chunk_size);
  7308. return true;
  7309. });
  7310. ASSERT_TRUE(result);
  7311. }
  7312. }
  7313. ASSERT_EQ(data, decompressed_data);
  7314. }
  7315. TEST(GzipDecompressor, DeflateDecompression) {
  7316. std::string original_text = "Raw deflate without gzip";
  7317. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7318. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7319. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7320. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7321. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7322. std::string decompressed_data;
  7323. {
  7324. httplib::detail::gzip_decompressor decompressor;
  7325. bool result = decompressor.decompress(
  7326. compressed_data.data(), compressed_data.size(),
  7327. [&](const char *decompressed_data_chunk,
  7328. size_t decompressed_data_chunk_size) {
  7329. decompressed_data.insert(decompressed_data.size(),
  7330. decompressed_data_chunk,
  7331. decompressed_data_chunk_size);
  7332. return true;
  7333. });
  7334. ASSERT_TRUE(result);
  7335. }
  7336. ASSERT_EQ(original_text, decompressed_data);
  7337. }
  7338. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7339. std::string original_text = "Raw deflate without gzip";
  7340. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7341. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7342. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7343. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7344. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7345. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7346. std::string decompressed_data;
  7347. {
  7348. httplib::detail::gzip_decompressor decompressor;
  7349. bool result = decompressor.decompress(
  7350. compressed_data.data(), compressed_data.size(),
  7351. [&](const char *decompressed_data_chunk,
  7352. size_t decompressed_data_chunk_size) {
  7353. decompressed_data.insert(decompressed_data.size(),
  7354. decompressed_data_chunk,
  7355. decompressed_data_chunk_size);
  7356. return true;
  7357. });
  7358. ASSERT_TRUE(result);
  7359. }
  7360. ASSERT_EQ(original_text, decompressed_data);
  7361. }
  7362. #endif
  7363. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7364. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7365. Headers headers;
  7366. headers.emplace("Accept-Encoding", "br");
  7367. auto res = cli_.Get("/streamed-chunked", headers);
  7368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7369. EXPECT_EQ(StatusCode::OK_200, res->status);
  7370. EXPECT_EQ(std::string("123456789"), res->body);
  7371. }
  7372. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7373. Headers headers;
  7374. headers.emplace("Accept-Encoding", "br");
  7375. auto res = cli_.Get("/streamed-chunked2", headers);
  7376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7377. EXPECT_EQ(StatusCode::OK_200, res->status);
  7378. EXPECT_EQ(std::string("123456789"), res->body);
  7379. }
  7380. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7381. cli_.set_compress(true);
  7382. auto res = cli_.Put(
  7383. "/put", 3,
  7384. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7385. sink.os << "PUT";
  7386. return true;
  7387. },
  7388. "text/plain");
  7389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7390. EXPECT_EQ(StatusCode::OK_200, res->status);
  7391. EXPECT_EQ("PUT", res->body);
  7392. }
  7393. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7394. cli_.set_compress(true);
  7395. auto res = cli_.Put(
  7396. "/put",
  7397. [](size_t /*offset*/, DataSink &sink) {
  7398. sink.os << "PUT";
  7399. sink.done();
  7400. return true;
  7401. },
  7402. "text/plain");
  7403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7404. EXPECT_EQ(StatusCode::OK_200, res->status);
  7405. EXPECT_EQ("PUT", res->body);
  7406. }
  7407. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7408. cli_.set_compress(true);
  7409. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7411. EXPECT_EQ(StatusCode::OK_200, res->status);
  7412. EXPECT_EQ(LARGE_DATA, res->body);
  7413. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7414. }
  7415. #endif
  7416. TEST_F(ServerTest, Patch) {
  7417. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7419. EXPECT_EQ(StatusCode::OK_200, res->status);
  7420. EXPECT_EQ("PATCH", res->body);
  7421. }
  7422. TEST_F(ServerTest, Delete) {
  7423. auto res = cli_.Delete("/delete");
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. EXPECT_EQ("DELETE", res->body);
  7427. }
  7428. TEST_F(ServerTest, DeleteContentReceiver) {
  7429. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7431. EXPECT_EQ(StatusCode::OK_200, res->status);
  7432. EXPECT_EQ("content", res->body);
  7433. }
  7434. TEST_F(ServerTest, Options) {
  7435. auto res = cli_.Options("*");
  7436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7437. EXPECT_EQ(StatusCode::OK_200, res->status);
  7438. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7439. EXPECT_TRUE(res->body.empty());
  7440. }
  7441. TEST_F(ServerTest, URL) {
  7442. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7444. EXPECT_EQ(StatusCode::OK_200, res->status);
  7445. }
  7446. TEST_F(ServerTest, ArrayParam) {
  7447. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7449. EXPECT_EQ(StatusCode::OK_200, res->status);
  7450. }
  7451. TEST_F(ServerTest, ArrayParamValues) {
  7452. auto res =
  7453. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7455. EXPECT_EQ(StatusCode::OK_200, res->status);
  7456. }
  7457. TEST_F(ServerTest, NoMultipleHeaders) {
  7458. Headers headers = {{"Content-Length", "5"}};
  7459. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7460. "text/plain");
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::OK_200, res->status);
  7463. }
  7464. TEST_F(ServerTest, PostContentReceiver) {
  7465. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. ASSERT_EQ(StatusCode::OK_200, res->status);
  7468. ASSERT_EQ("content", res->body);
  7469. }
  7470. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7471. UploadFormDataItems items = {
  7472. {"text1", "text default", "", ""},
  7473. {"text2", "aωb", "", ""},
  7474. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7475. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7476. {"file3", "", "", "application/octet-stream"},
  7477. };
  7478. auto res = cli_.Post("/content_receiver", items);
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_EQ(StatusCode::OK_200, res->status);
  7481. }
  7482. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7483. UploadFormDataItems items = {
  7484. {"text1", "text default", "", ""},
  7485. {"text2", "aωb", "", ""},
  7486. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7487. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7488. {"file3", "", "", "application/octet-stream"},
  7489. };
  7490. auto boundary = std::string("+++++");
  7491. std::string body;
  7492. for (const auto &item : items) {
  7493. body += "--" + boundary + "\r\n";
  7494. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7495. if (!item.filename.empty()) {
  7496. body += "; filename=\"" + item.filename + "\"";
  7497. }
  7498. body += "\r\n";
  7499. if (!item.content_type.empty()) {
  7500. body += "Content-Type: " + item.content_type + "\r\n";
  7501. }
  7502. body += "\r\n";
  7503. body += item.content + "\r\n";
  7504. }
  7505. body += "--" + boundary + "--\r\n";
  7506. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7507. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7509. EXPECT_EQ(StatusCode::OK_200, res->status);
  7510. }
  7511. TEST(MultipartFormDataTest, FieldEscaping) {
  7512. Server svr;
  7513. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7514. const ContentReader &content_reader) {
  7515. ASSERT_TRUE(req.is_multipart_form_data());
  7516. std::vector<FormData> received;
  7517. content_reader(
  7518. [&](const FormData &file) {
  7519. received.push_back(file);
  7520. return true;
  7521. },
  7522. [&](const char *data, size_t data_length) {
  7523. received.back().content.append(data, data_length);
  7524. return true;
  7525. });
  7526. // '"', CR and LF in names and filenames are escaped following the
  7527. // WHATWG HTML standard, so each part still parses as a single part
  7528. // with no injected headers. Content types get CR/LF escaped too,
  7529. // while '"' (legal there, e.g. quoted charset) is preserved.
  7530. ASSERT_EQ(4U, received.size());
  7531. EXPECT_EQ("na%22me", received[0].name);
  7532. EXPECT_EQ("quoted name", received[0].content);
  7533. EXPECT_EQ("file", received[1].name);
  7534. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7535. received[1].filename);
  7536. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7537. EXPECT_EQ("injected", received[1].content);
  7538. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7539. EXPECT_EQ("my%22file.txt", received[2].filename);
  7540. EXPECT_EQ("cr lf name", received[2].content);
  7541. EXPECT_EQ("typed", received[3].name);
  7542. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7543. received[3].content_type);
  7544. EXPECT_EQ("typed content", received[3].content);
  7545. });
  7546. auto port = svr.bind_to_any_port("localhost");
  7547. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7548. auto se = detail::scope_exit([&] {
  7549. svr.stop();
  7550. t.join();
  7551. ASSERT_FALSE(svr.is_running());
  7552. });
  7553. svr.wait_until_ready();
  7554. Client cli("localhost", port);
  7555. UploadFormDataItems items = {
  7556. {"na\"me", "quoted name", "", ""},
  7557. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7558. "application/octet-stream"},
  7559. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7560. {"typed", "typed content", "",
  7561. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7562. };
  7563. auto res = cli.Post("/post", items);
  7564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7565. EXPECT_EQ(StatusCode::OK_200, res->status);
  7566. }
  7567. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7568. const UploadFormDataItems items = {
  7569. {"name1", "Content 1", "", ""},
  7570. {"name2", "Content 2", "file2.txt", "text/plain"},
  7571. };
  7572. Server svr;
  7573. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7574. const ContentReader &content_reader) {
  7575. ASSERT_TRUE(req.is_multipart_form_data());
  7576. std::vector<FormData> received;
  7577. content_reader(
  7578. [&](const FormData &file) {
  7579. received.push_back(file);
  7580. return true;
  7581. },
  7582. [&](const char *data, size_t data_length) {
  7583. received.back().content.append(data, data_length);
  7584. return true;
  7585. });
  7586. ASSERT_EQ(2U, received.size());
  7587. EXPECT_EQ("name1", received[0].name);
  7588. EXPECT_EQ("Content 1", received[0].content);
  7589. EXPECT_EQ("name2", received[1].name);
  7590. EXPECT_EQ("Content 2", received[1].content);
  7591. EXPECT_EQ("file2.txt", received[1].filename);
  7592. EXPECT_EQ("text/plain", received[1].content_type);
  7593. });
  7594. auto port = svr.bind_to_any_port("localhost");
  7595. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7596. auto se = detail::scope_exit([&] {
  7597. svr.stop();
  7598. t.join();
  7599. ASSERT_FALSE(svr.is_running());
  7600. });
  7601. svr.wait_until_ready();
  7602. Client cli("localhost", port);
  7603. // Whole-body serialization with a generated boundary
  7604. {
  7605. MultipartFormDataWriter writer;
  7606. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7607. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7608. writer.content_type());
  7609. auto body = writer.serialize(items);
  7610. EXPECT_EQ(body.size(), writer.content_length(items));
  7611. auto res = cli.Post("/post", body, writer.content_type());
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ(StatusCode::OK_200, res->status);
  7614. }
  7615. // Per-part framing with a custom boundary via a content provider
  7616. {
  7617. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7618. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7619. MultipartFormDataWriter writer("custom-boundary_123");
  7620. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7621. std::string body;
  7622. for (const auto &item : items) {
  7623. body += writer.item_begin(item);
  7624. body += item.content;
  7625. body += MultipartFormDataWriter::item_end();
  7626. }
  7627. body += writer.finish();
  7628. EXPECT_EQ(body.size(), writer.content_length(items));
  7629. auto res = cli.Post(
  7630. "/post", body.size(),
  7631. [&](size_t offset, size_t length, DataSink &sink) {
  7632. sink.write(body.data() + offset, length);
  7633. return true;
  7634. },
  7635. writer.content_type());
  7636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7637. EXPECT_EQ(StatusCode::OK_200, res->status);
  7638. }
  7639. }
  7640. TEST_F(ServerTest, PostContentReceiverGzip) {
  7641. cli_.set_compress(true);
  7642. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7644. ASSERT_EQ(StatusCode::OK_200, res->status);
  7645. ASSERT_EQ("content", res->body);
  7646. }
  7647. TEST_F(ServerTest, PutContentReceiver) {
  7648. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7650. ASSERT_EQ(StatusCode::OK_200, res->status);
  7651. ASSERT_EQ("content", res->body);
  7652. }
  7653. TEST_F(ServerTest, PatchContentReceiver) {
  7654. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7656. ASSERT_EQ(StatusCode::OK_200, res->status);
  7657. ASSERT_EQ("content", res->body);
  7658. }
  7659. template <typename ClientType>
  7660. void TestWithHeadersAndContentReceiver(
  7661. ClientType &cli,
  7662. std::function<Result(ClientType &, const std::string &, const Headers &,
  7663. const std::string &, const std::string &,
  7664. ContentReceiver, DownloadProgress)>
  7665. request_func) {
  7666. Headers headers;
  7667. headers.emplace("X-Custom-Header", "test-value");
  7668. std::string received_body;
  7669. auto res = request_func(
  7670. cli, "/content_receiver", headers, "content", "application/json",
  7671. [&](const char *data, size_t data_length) {
  7672. received_body.append(data, data_length);
  7673. return true;
  7674. },
  7675. nullptr);
  7676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7677. EXPECT_EQ(StatusCode::OK_200, res->status);
  7678. EXPECT_EQ("content", received_body);
  7679. }
  7680. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7681. #ifdef CPPHTTPLIB_SSL_ENABLED
  7682. using ClientT = SSLClient;
  7683. #else
  7684. using ClientT = Client;
  7685. #endif
  7686. TestWithHeadersAndContentReceiver<ClientT>(
  7687. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7688. const std::string &body, const std::string &content_type,
  7689. ContentReceiver receiver, DownloadProgress progress) {
  7690. return cli.Post(path, headers, body, content_type, receiver, progress);
  7691. });
  7692. }
  7693. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7694. #ifdef CPPHTTPLIB_SSL_ENABLED
  7695. using ClientT = SSLClient;
  7696. #else
  7697. using ClientT = Client;
  7698. #endif
  7699. TestWithHeadersAndContentReceiver<ClientT>(
  7700. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7701. const std::string &body, const std::string &content_type,
  7702. ContentReceiver receiver, DownloadProgress progress) {
  7703. return cli.Put(path, headers, body, content_type, receiver, progress);
  7704. });
  7705. }
  7706. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7707. #ifdef CPPHTTPLIB_SSL_ENABLED
  7708. using ClientT = SSLClient;
  7709. #else
  7710. using ClientT = Client;
  7711. #endif
  7712. TestWithHeadersAndContentReceiver<ClientT>(
  7713. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7714. const std::string &body, const std::string &content_type,
  7715. ContentReceiver receiver, DownloadProgress progress) {
  7716. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7717. });
  7718. }
  7719. template <typename ClientType>
  7720. void TestWithHeadersAndContentReceiverWithProgress(
  7721. ClientType &cli,
  7722. std::function<Result(ClientType &, const std::string &, const Headers &,
  7723. const std::string &, const std::string &,
  7724. ContentReceiver, DownloadProgress)>
  7725. request_func) {
  7726. Headers headers;
  7727. headers.emplace("X-Test-Header", "progress-test");
  7728. std::string received_body;
  7729. auto progress_called = false;
  7730. auto res = request_func(
  7731. cli, "/content_receiver", headers, "content", "text/plain",
  7732. [&](const char *data, size_t data_length) {
  7733. received_body.append(data, data_length);
  7734. return true;
  7735. },
  7736. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7737. progress_called = true;
  7738. return true;
  7739. });
  7740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7741. EXPECT_EQ(StatusCode::OK_200, res->status);
  7742. EXPECT_EQ("content", received_body);
  7743. EXPECT_TRUE(progress_called);
  7744. }
  7745. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7746. #ifdef CPPHTTPLIB_SSL_ENABLED
  7747. using ClientT = SSLClient;
  7748. #else
  7749. using ClientT = Client;
  7750. #endif
  7751. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7752. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7753. const std::string &body, const std::string &content_type,
  7754. ContentReceiver receiver, DownloadProgress progress) {
  7755. return cli.Post(path, headers, body, content_type, receiver, progress);
  7756. });
  7757. }
  7758. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7759. #ifdef CPPHTTPLIB_SSL_ENABLED
  7760. using ClientT = SSLClient;
  7761. #else
  7762. using ClientT = Client;
  7763. #endif
  7764. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7765. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7766. const std::string &body, const std::string &content_type,
  7767. ContentReceiver receiver, DownloadProgress progress) {
  7768. return cli.Put(path, headers, body, content_type, receiver, progress);
  7769. });
  7770. }
  7771. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7772. #ifdef CPPHTTPLIB_SSL_ENABLED
  7773. using ClientT = SSLClient;
  7774. #else
  7775. using ClientT = Client;
  7776. #endif
  7777. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7778. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7779. const std::string &body, const std::string &content_type,
  7780. ContentReceiver receiver, DownloadProgress progress) {
  7781. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7782. });
  7783. }
  7784. template <typename ClientType>
  7785. void TestWithHeadersAndContentReceiverError(
  7786. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7787. const Headers &, const std::string &,
  7788. const std::string &, ContentReceiver)>
  7789. request_func) {
  7790. Headers headers;
  7791. headers.emplace("X-Error-Test", "true");
  7792. std::string received_body;
  7793. auto receiver_failed = false;
  7794. auto res =
  7795. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7796. [&](const char *data, size_t data_length) {
  7797. received_body.append(data, data_length);
  7798. receiver_failed = true;
  7799. return false;
  7800. });
  7801. ASSERT_FALSE(res);
  7802. EXPECT_TRUE(receiver_failed);
  7803. }
  7804. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7805. #ifdef CPPHTTPLIB_SSL_ENABLED
  7806. using ClientT = SSLClient;
  7807. #else
  7808. using ClientT = Client;
  7809. #endif
  7810. TestWithHeadersAndContentReceiverError<ClientT>(
  7811. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7812. const std::string &body, const std::string &content_type,
  7813. ContentReceiver receiver) {
  7814. return cli.Post(path, headers, body, content_type, receiver);
  7815. });
  7816. }
  7817. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7818. #ifdef CPPHTTPLIB_SSL_ENABLED
  7819. using ClientT = SSLClient;
  7820. #else
  7821. using ClientT = Client;
  7822. #endif
  7823. TestWithHeadersAndContentReceiverError<ClientT>(
  7824. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7825. const std::string &body, const std::string &content_type,
  7826. ContentReceiver receiver) {
  7827. return cli.Put(path, headers, body, content_type, receiver);
  7828. });
  7829. }
  7830. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7831. #ifdef CPPHTTPLIB_SSL_ENABLED
  7832. using ClientT = SSLClient;
  7833. #else
  7834. using ClientT = Client;
  7835. #endif
  7836. TestWithHeadersAndContentReceiverError<ClientT>(
  7837. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7838. const std::string &body, const std::string &content_type,
  7839. ContentReceiver receiver) {
  7840. return cli.Patch(path, headers, body, content_type, receiver);
  7841. });
  7842. }
  7843. TEST_F(ServerTest, PostQueryStringAndBody) {
  7844. auto res =
  7845. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7847. ASSERT_EQ(StatusCode::OK_200, res->status);
  7848. }
  7849. TEST_F(ServerTest, HTTP2Magic) {
  7850. Request req;
  7851. req.method = "PRI";
  7852. req.path = "*";
  7853. req.body = "SM";
  7854. auto res = std::make_shared<Response>();
  7855. auto error = Error::Success;
  7856. auto ret = cli_.send(req, *res, error);
  7857. ASSERT_TRUE(ret);
  7858. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7859. }
  7860. TEST_F(ServerTest, KeepAlive) {
  7861. auto res = cli_.Get("/hi");
  7862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7863. EXPECT_EQ(StatusCode::OK_200, res->status);
  7864. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7865. EXPECT_EQ("Hello World!", res->body);
  7866. res = cli_.Get("/hi");
  7867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7868. EXPECT_EQ(StatusCode::OK_200, res->status);
  7869. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7870. EXPECT_EQ("Hello World!", res->body);
  7871. res = cli_.Get("/hi");
  7872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7873. EXPECT_EQ(StatusCode::OK_200, res->status);
  7874. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7875. EXPECT_EQ("Hello World!", res->body);
  7876. res = cli_.Get("/not-exist");
  7877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7878. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7879. res = cli_.Post("/empty", "", "text/plain");
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ(StatusCode::OK_200, res->status);
  7882. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7883. EXPECT_EQ("empty", res->body);
  7884. EXPECT_EQ("close", res->get_header_value("Connection"));
  7885. res = cli_.Post(
  7886. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7887. "text/plain");
  7888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7889. EXPECT_EQ(StatusCode::OK_200, res->status);
  7890. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7891. EXPECT_EQ("empty", res->body);
  7892. cli_.set_keep_alive(false);
  7893. res = cli_.Get("/last-request");
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ(StatusCode::OK_200, res->status);
  7896. EXPECT_EQ("close", res->get_header_value("Connection"));
  7897. }
  7898. TEST_F(ServerTest, TooManyRedirect) {
  7899. cli_.set_follow_location(true);
  7900. auto res = cli_.Get("/redirect/0");
  7901. ASSERT_TRUE(!res);
  7902. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7903. }
  7904. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7905. Request req;
  7906. req.method = "FOOBAR";
  7907. req.path = "/hi";
  7908. cli_.set_keep_alive(true);
  7909. auto res = cli_.send(req);
  7910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7911. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7912. EXPECT_EQ("close", res->get_header_value("Connection"));
  7913. EXPECT_FALSE(cli_.is_socket_open());
  7914. }
  7915. TEST_F(ServerTest, CustomRouteReadsBody) {
  7916. const std::string xml =
  7917. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7918. Request req;
  7919. req.method = "PROPFIND";
  7920. req.path = "/dav/dir";
  7921. req.set_header("Depth", "1");
  7922. req.body = xml;
  7923. auto res = cli_.send(req);
  7924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7925. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7926. EXPECT_EQ(xml, res->body);
  7927. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7928. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7929. }
  7930. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7931. Request req;
  7932. req.method = "PROPFIND";
  7933. req.path = "/dav/42";
  7934. auto res = cli_.send(req);
  7935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7936. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7937. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7938. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7939. }
  7940. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7941. Request req;
  7942. req.method = "PROPFIND";
  7943. req.path = "/dav-re/123";
  7944. auto res = cli_.send(req);
  7945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7946. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7947. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7948. }
  7949. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7950. Request req;
  7951. req.method = "MKCOL";
  7952. req.path = "/dav-mkcol";
  7953. auto res = cli_.send(req);
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(StatusCode::Created_201, res->status);
  7956. }
  7957. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7958. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7959. Request req;
  7960. req.method = "REPORT";
  7961. req.path = "/dav-report";
  7962. req.body = xml;
  7963. auto res = cli_.send(req);
  7964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7965. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7966. EXPECT_EQ(xml, res->body);
  7967. }
  7968. // A content reader route must fire even when the request carries no body,
  7969. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7970. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7971. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7972. Request req;
  7973. req.method = "REPORT";
  7974. req.path = "/dav-report";
  7975. auto res = cli_.send(req);
  7976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7977. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7978. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7979. }
  7980. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7981. Request req;
  7982. req.method = "PROPFIND";
  7983. req.path = "/not-dav";
  7984. auto res = cli_.send(req);
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7987. }
  7988. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7989. Request req;
  7990. req.method = "UNLOCK";
  7991. req.path = "/dav/dir";
  7992. cli_.set_keep_alive(true);
  7993. auto res = cli_.send(req);
  7994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7995. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7996. EXPECT_EQ("close", res->get_header_value("Connection"));
  7997. EXPECT_FALSE(cli_.is_socket_open());
  7998. }
  7999. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8000. // The mount point serves this path, but only for GET and HEAD.
  8001. auto get_res = cli_.Get("/dir/index.html");
  8002. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8003. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8004. Request req;
  8005. req.method = "PROPFIND";
  8006. req.path = "/dir/index.html";
  8007. auto res = cli_.send(req);
  8008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8009. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8010. }
  8011. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8012. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8013. cli_.set_keep_alive(true);
  8014. for (auto i = 0; i < 2; i++) {
  8015. Request req;
  8016. req.method = "PROPFIND";
  8017. req.path = "/dav/dir";
  8018. req.body = xml;
  8019. auto res = cli_.send(req);
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8022. EXPECT_EQ(xml, res->body);
  8023. EXPECT_TRUE(cli_.is_socket_open());
  8024. }
  8025. // A built-in method must still be served on the same connection.
  8026. cli_.set_keep_alive(false);
  8027. auto res = cli_.Get("/hi");
  8028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8029. EXPECT_EQ(StatusCode::OK_200, res->status);
  8030. EXPECT_EQ("close", res->get_header_value("Connection"));
  8031. }
  8032. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8033. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8034. Request req;
  8035. req.method = "PROPFIND";
  8036. req.path = "/dav/dir";
  8037. req.set_header("Expect", "100-continue");
  8038. req.body = xml;
  8039. auto res = cli_.send(req);
  8040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8041. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8042. EXPECT_EQ(xml, res->body);
  8043. }
  8044. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8045. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8046. TEST_F(ServerTest, Gzip) {
  8047. Headers headers;
  8048. headers.emplace("Accept-Encoding", "gzip, deflate");
  8049. auto res = cli_.Get("/compress", headers);
  8050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8051. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8052. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8053. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8054. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8055. "7890123456789012345678901234567890",
  8056. res->body);
  8057. EXPECT_EQ(StatusCode::OK_200, res->status);
  8058. }
  8059. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8060. Headers headers;
  8061. headers.emplace("Accept-Encoding", "gzip, deflate");
  8062. auto res = cli_.Get("/compress-with-charset", headers);
  8063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8064. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8065. EXPECT_EQ("application/json; charset=utf-8",
  8066. res->get_header_value("Content-Type"));
  8067. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8068. "7890123456789012345678901234567890",
  8069. res->body);
  8070. EXPECT_EQ(StatusCode::OK_200, res->status);
  8071. }
  8072. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8073. Headers headers;
  8074. headers.emplace("Accept-Encoding", "");
  8075. auto res = cli_.Get("/compress", headers);
  8076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8077. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8079. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8080. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8081. "7890123456789012345678901234567890",
  8082. res->body);
  8083. EXPECT_EQ(StatusCode::OK_200, res->status);
  8084. }
  8085. TEST_F(ServerTest, GzipWithContentReceiver) {
  8086. Headers headers;
  8087. headers.emplace("Accept-Encoding", "gzip, deflate");
  8088. std::string body;
  8089. auto res = cli_.Get("/compress", headers,
  8090. [&](const char *data, uint64_t data_length) {
  8091. EXPECT_EQ(100U, data_length);
  8092. body.append(data, data_length);
  8093. return true;
  8094. });
  8095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8096. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8097. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8098. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8099. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8100. "7890123456789012345678901234567890",
  8101. body);
  8102. EXPECT_EQ(StatusCode::OK_200, res->status);
  8103. }
  8104. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8105. Headers headers;
  8106. headers.emplace("Accept-Encoding", "gzip, deflate");
  8107. cli_.set_decompress(false);
  8108. auto res = cli_.Get("/compress", headers);
  8109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8110. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8111. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8112. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8113. EXPECT_EQ(33U, res->body.size());
  8114. EXPECT_EQ(StatusCode::OK_200, res->status);
  8115. }
  8116. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8117. Headers headers;
  8118. headers.emplace("Accept-Encoding", "");
  8119. std::string body;
  8120. auto res = cli_.Get("/compress", headers,
  8121. [&](const char *data, uint64_t data_length) {
  8122. EXPECT_EQ(100U, data_length);
  8123. body.append(data, data_length);
  8124. return true;
  8125. });
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8128. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8129. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8130. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8131. "7890123456789012345678901234567890",
  8132. body);
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. }
  8135. TEST_F(ServerTest, NoGzip) {
  8136. Headers headers;
  8137. headers.emplace("Accept-Encoding", "gzip, deflate");
  8138. auto res = cli_.Get("/nocompress", headers);
  8139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8140. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8141. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8142. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8143. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8144. "7890123456789012345678901234567890",
  8145. res->body);
  8146. EXPECT_EQ(StatusCode::OK_200, res->status);
  8147. }
  8148. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8149. Headers headers;
  8150. headers.emplace("Accept-Encoding", "gzip, deflate");
  8151. std::string body;
  8152. auto res = cli_.Get("/nocompress", headers,
  8153. [&](const char *data, uint64_t data_length) {
  8154. EXPECT_EQ(100U, data_length);
  8155. body.append(data, data_length);
  8156. return true;
  8157. });
  8158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8159. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8160. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8161. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8162. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8163. "7890123456789012345678901234567890",
  8164. body);
  8165. EXPECT_EQ(StatusCode::OK_200, res->status);
  8166. }
  8167. TEST_F(ServerTest, MultipartFormDataGzip) {
  8168. UploadFormDataItems items = {
  8169. {"key1", "test", "", ""},
  8170. {"key2", "--abcdefg123", "", ""},
  8171. };
  8172. cli_.set_compress(true);
  8173. auto res = cli_.Post("/compress-multipart", items);
  8174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8175. EXPECT_EQ(StatusCode::OK_200, res->status);
  8176. }
  8177. #endif
  8178. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8179. // Static file compression is opt-in, so these run their own server rather than
  8180. // flipping it on for the shared ServerTest fixture, which would silently
  8181. // rewrite what every other static file test is asserting.
  8182. class StaticFileCompressionTest : public ::testing::Test {
  8183. protected:
  8184. void TearDown() override {
  8185. if (t_.joinable()) {
  8186. svr_.stop();
  8187. t_.join();
  8188. }
  8189. }
  8190. int start(const std::function<void(Server &)> &configure = nullptr) {
  8191. // Serves the same tree as a directory of build-time compressed assets
  8192. // would be served: the mount point names the coding the files are already
  8193. // stored in. Registered before "/" so it is the one that matches.
  8194. svr_.set_mount_point("/pre-encoded", "./www",
  8195. {{"Content-Encoding", "gzip"}});
  8196. svr_.set_mount_point("/", "./www");
  8197. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8198. res.set_file_content("./www/dir/index.html", "text/html");
  8199. });
  8200. svr_.Get("/pre-encoded-file-content",
  8201. [](const Request & /*req*/, Response &res) {
  8202. res.set_header("Content-Encoding", "gzip");
  8203. res.set_file_content("./www/dir/index.html", "text/html");
  8204. });
  8205. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8206. res.set_content_provider(
  8207. 6, "text/plain",
  8208. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8209. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8210. return true;
  8211. });
  8212. });
  8213. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8214. res.set_content_provider(
  8215. 1000, "text/plain",
  8216. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8217. if (offset < 100) {
  8218. std::string data(100, 'A');
  8219. sink.write(data.data(), data.size());
  8220. return true;
  8221. }
  8222. std::this_thread::sleep_for(std::chrono::seconds(2));
  8223. std::string data(900, 'B');
  8224. sink.write(data.data(), data.size());
  8225. return true;
  8226. });
  8227. });
  8228. if (configure) { configure(svr_); }
  8229. auto port = svr_.bind_to_any_port(HOST);
  8230. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8231. svr_.wait_until_ready();
  8232. return port;
  8233. }
  8234. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8235. // Every file under ./www except 1MB.txt is smaller than the default
  8236. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8237. // it out of the way.
  8238. static void enable_without_floor(Server &svr) {
  8239. svr.set_static_file_compression(true);
  8240. svr.set_static_file_compression_min_length(0);
  8241. }
  8242. Server svr_;
  8243. std::thread t_;
  8244. };
  8245. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8246. auto port = start();
  8247. Client cli(HOST, port);
  8248. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8250. EXPECT_EQ(StatusCode::OK_200, res->status);
  8251. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8252. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8253. EXPECT_EQ(1048576U, res->body.size());
  8254. }
  8255. TEST_F(StaticFileCompressionTest, MountPoint) {
  8256. auto port = start(enable);
  8257. Client cli(HOST, port);
  8258. cli.set_decompress(false);
  8259. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8261. EXPECT_EQ(StatusCode::OK_200, res->status);
  8262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8263. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8264. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8265. // The response stays self-delimiting: a length, not a chunked body.
  8266. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8267. EXPECT_EQ(std::to_string(res->body.size()),
  8268. res->get_header_value("Content-Length"));
  8269. EXPECT_LT(res->body.size(), 1048576U);
  8270. EXPECT_FALSE(res->body.empty());
  8271. }
  8272. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8273. auto port = start(enable);
  8274. Client cli(HOST, port);
  8275. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8277. EXPECT_EQ(StatusCode::OK_200, res->status);
  8278. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8279. EXPECT_EQ(1048576U, res->body.size());
  8280. }
  8281. TEST_F(StaticFileCompressionTest, FileContent) {
  8282. auto port = start(enable_without_floor);
  8283. Client cli(HOST, port);
  8284. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8286. EXPECT_EQ(StatusCode::OK_200, res->status);
  8287. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8288. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8289. EXPECT_EQ(104U, res->body.size());
  8290. }
  8291. // A handler that serves an already-encoded file names the coding itself. The
  8292. // file-backed path decided its coding from Accept-Encoding and the content
  8293. // type alone, so it compressed the stored bytes a second time and appended a
  8294. // second Content-Encoding field line.
  8295. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8296. auto port = start(enable_without_floor);
  8297. Client cli(HOST, port);
  8298. cli.set_decompress(false);
  8299. auto res = cli.Get("/pre-encoded-file-content",
  8300. Headers{{"Accept-Encoding", "gzip"}});
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(StatusCode::OK_200, res->status);
  8303. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8304. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8305. // Vary belongs to a coding the server chose, and it chose none here.
  8306. EXPECT_FALSE(res->has_header("Vary"));
  8307. // The file travels exactly as it is stored on disk.
  8308. EXPECT_EQ(104U, res->body.size());
  8309. }
  8310. // The 1MB file clears the default floor, so this one runs the configuration a
  8311. // deployment would actually have.
  8312. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8313. auto port = start(enable);
  8314. Client cli(HOST, port);
  8315. cli.set_decompress(false);
  8316. auto res =
  8317. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8319. EXPECT_EQ(StatusCode::OK_200, res->status);
  8320. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8321. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8322. EXPECT_FALSE(res->has_header("Vary"));
  8323. EXPECT_EQ(1048576U, res->body.size());
  8324. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8325. }
  8326. TEST_F(StaticFileCompressionTest, Head) {
  8327. auto port = start(enable);
  8328. Client cli(HOST, port);
  8329. cli.set_decompress(false);
  8330. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8331. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8332. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8334. EXPECT_EQ(StatusCode::OK_200, res->status);
  8335. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8336. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8337. // HEAD still reports the size a GET would return.
  8338. EXPECT_EQ(get->get_header_value("Content-Length"),
  8339. res->get_header_value("Content-Length"));
  8340. EXPECT_TRUE(res->body.empty());
  8341. }
  8342. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8343. auto port = start(enable);
  8344. Client cli(HOST, port);
  8345. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8346. {"Accept-Encoding", "gzip"}});
  8347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8348. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8349. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8350. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8351. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8352. EXPECT_EQ("cd", res->body);
  8353. }
  8354. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8355. auto port = start(enable);
  8356. Client cli(HOST, port);
  8357. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8359. EXPECT_EQ(StatusCode::OK_200, res->status);
  8360. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8361. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8362. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8363. }
  8364. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8365. auto port = start(enable);
  8366. Client cli(HOST, port);
  8367. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8369. EXPECT_EQ(StatusCode::OK_200, res->status);
  8370. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8371. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8372. EXPECT_TRUE(res->body.empty());
  8373. }
  8374. TEST_F(StaticFileCompressionTest, MinLength) {
  8375. auto port = start(enable);
  8376. Client cli(HOST, port);
  8377. // 104 bytes, well under the default floor. Compressing it would add the
  8378. // gzip header and trailer to a body that already fits in one packet.
  8379. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8381. EXPECT_EQ(StatusCode::OK_200, res->status);
  8382. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8383. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8384. }
  8385. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8386. auto port = start([](Server &svr) {
  8387. svr.set_static_file_compression(true);
  8388. svr.set_static_file_compression_min_length(1);
  8389. });
  8390. Client cli(HOST, port);
  8391. cli.set_decompress(false);
  8392. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8394. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8395. // A 9-byte file comes back larger than it went in, because gzip's header and
  8396. // trailer outweigh anything deflate can save. That is the end of the range
  8397. // the floor exists to keep out.
  8398. EXPECT_GT(res->body.size(), 9U);
  8399. }
  8400. TEST_F(StaticFileCompressionTest, MaxLength) {
  8401. auto port = start([](Server &svr) {
  8402. svr.set_static_file_compression(true);
  8403. svr.set_static_file_compression_min_length(0);
  8404. svr.set_static_file_compression_max_length(1024);
  8405. });
  8406. Client cli(HOST, port);
  8407. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8408. // defines `small` as a macro on Windows.
  8409. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8410. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8411. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8412. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8413. // Under it: compressed.
  8414. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8415. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8416. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8417. }
  8418. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8419. auto port = start(enable_without_floor);
  8420. Client cli(HOST, port);
  8421. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8422. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8423. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8424. auto identity_etag = identity->get_header_value("ETag");
  8425. ASSERT_FALSE(identity_etag.empty());
  8426. auto gzipped =
  8427. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8428. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8429. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8430. auto gzip_etag = gzipped->get_header_value("ETag");
  8431. ASSERT_FALSE(gzip_etag.empty());
  8432. // Two representations, two validators.
  8433. EXPECT_NE(identity_etag, gzip_etag);
  8434. // Each one revalidates against the request that would produce it...
  8435. auto fresh =
  8436. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8437. {"If-None-Match", gzip_etag}});
  8438. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8439. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8440. auto fresh_identity =
  8441. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8442. {"If-None-Match", identity_etag}});
  8443. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8444. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8445. // ...and not against the other representation.
  8446. auto crossed =
  8447. cli.Get("/dir/index.html",
  8448. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8449. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8450. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8451. }
  8452. // The opt-in covers responses the server reads off disk itself. A caller's own
  8453. // known-length provider keeps its Content-Length and, more importantly, keeps
  8454. // delivering incrementally: routing it through a compressor would hold every
  8455. // write back until zlib's window filled.
  8456. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8457. auto port = start(enable);
  8458. Client cli(HOST, port);
  8459. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8461. EXPECT_EQ(StatusCode::OK_200, res->status);
  8462. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8463. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8464. EXPECT_EQ("aaabbb", res->body);
  8465. }
  8466. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8467. auto port = start(enable);
  8468. Client cli(HOST, port);
  8469. cli.set_read_timeout(1, 0);
  8470. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8471. Headers{{"Accept-Encoding", "gzip"}});
  8472. ASSERT_TRUE(handle.is_valid());
  8473. // The provider writes 100 bytes and then stalls for longer than the read
  8474. // timeout. Those first bytes have to arrive anyway: run the response through
  8475. // a compressor and zlib holds them until its window fills, so the read would
  8476. // come back empty instead.
  8477. char buf[256];
  8478. auto n = handle.read(buf, sizeof(buf));
  8479. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8480. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8481. }
  8482. #endif
  8483. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8484. TEST_F(ServerTest, Brotli) {
  8485. Headers headers;
  8486. headers.emplace("Accept-Encoding", "br");
  8487. auto res = cli_.Get("/compress", headers);
  8488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8489. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8490. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8491. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8492. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8493. "7890123456789012345678901234567890",
  8494. res->body);
  8495. EXPECT_EQ(StatusCode::OK_200, res->status);
  8496. }
  8497. #endif
  8498. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8499. TEST_F(ServerTest, Zstd) {
  8500. Headers headers;
  8501. headers.emplace("Accept-Encoding", "zstd");
  8502. auto res = cli_.Get("/compress", headers);
  8503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8504. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8505. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8506. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8507. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8508. "7890123456789012345678901234567890",
  8509. res->body);
  8510. EXPECT_EQ(StatusCode::OK_200, res->status);
  8511. }
  8512. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8513. Headers headers;
  8514. headers.emplace("Accept-Encoding", "");
  8515. auto res = cli_.Get("/compress", headers);
  8516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8517. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8518. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8519. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8520. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8521. "7890123456789012345678901234567890",
  8522. res->body);
  8523. EXPECT_EQ(StatusCode::OK_200, res->status);
  8524. }
  8525. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8526. Headers headers;
  8527. headers.emplace("Accept-Encoding", "zstd");
  8528. std::string body;
  8529. auto res = cli_.Get("/compress", headers,
  8530. [&](const char *data, uint64_t data_length) {
  8531. EXPECT_EQ(100U, data_length);
  8532. body.append(data, data_length);
  8533. return true;
  8534. });
  8535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8536. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8537. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8538. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8539. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8540. "7890123456789012345678901234567890",
  8541. body);
  8542. EXPECT_EQ(StatusCode::OK_200, res->status);
  8543. }
  8544. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8545. Headers headers;
  8546. headers.emplace("Accept-Encoding", "zstd");
  8547. cli_.set_decompress(false);
  8548. auto res = cli_.Get("/compress", headers);
  8549. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8550. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8551. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8552. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8554. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8556. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8557. EXPECT_EQ(StatusCode::OK_200, res->status);
  8558. ASSERT_EQ(26U, res->body.size());
  8559. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8560. 0);
  8561. }
  8562. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8563. Headers headers;
  8564. headers.emplace("Accept-Encoding", "");
  8565. std::string body;
  8566. auto res = cli_.Get("/compress", headers,
  8567. [&](const char *data, uint64_t data_length) {
  8568. EXPECT_EQ(100U, data_length);
  8569. body.append(data, data_length);
  8570. return true;
  8571. });
  8572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8573. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8575. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8576. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8577. "7890123456789012345678901234567890",
  8578. body);
  8579. EXPECT_EQ(StatusCode::OK_200, res->status);
  8580. }
  8581. TEST_F(ServerTest, NoZstd) {
  8582. Headers headers;
  8583. headers.emplace("Accept-Encoding", "zstd");
  8584. auto res = cli_.Get("/nocompress", headers);
  8585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8586. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8587. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8588. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8589. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8590. "7890123456789012345678901234567890",
  8591. res->body);
  8592. EXPECT_EQ(StatusCode::OK_200, res->status);
  8593. }
  8594. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8595. Headers headers;
  8596. headers.emplace("Accept-Encoding", "zstd");
  8597. std::string body;
  8598. auto res = cli_.Get("/nocompress", headers,
  8599. [&](const char *data, uint64_t data_length) {
  8600. EXPECT_EQ(100U, data_length);
  8601. body.append(data, data_length);
  8602. return true;
  8603. });
  8604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8605. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8606. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8607. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8608. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8609. "7890123456789012345678901234567890",
  8610. body);
  8611. EXPECT_EQ(StatusCode::OK_200, res->status);
  8612. }
  8613. // TODO: How to enable zstd ??
  8614. TEST_F(ServerTest, MultipartFormDataZstd) {
  8615. UploadFormDataItems items = {
  8616. {"key1", "test", "", ""},
  8617. {"key2", "--abcdefg123", "", ""},
  8618. };
  8619. Headers headers;
  8620. headers.emplace("Accept-Encoding", "zstd");
  8621. cli_.set_compress(true);
  8622. auto res = cli_.Post("/compress-multipart", headers, items);
  8623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8624. EXPECT_EQ(StatusCode::OK_200, res->status);
  8625. }
  8626. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8627. Headers headers;
  8628. headers.emplace("Accept-Encoding", "zstd");
  8629. cli_.set_compress(true);
  8630. auto res = cli_.Put(
  8631. "/put", headers, 3,
  8632. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8633. sink.os << "PUT";
  8634. return true;
  8635. },
  8636. "text/plain");
  8637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8638. EXPECT_EQ(StatusCode::OK_200, res->status);
  8639. EXPECT_EQ("PUT", res->body);
  8640. }
  8641. // Pre-compression logging tests
  8642. TEST_F(ServerTest, PreCompressionLogging) {
  8643. // Test data for compression (matches the actual /compress endpoint content)
  8644. const std::string test_content =
  8645. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8646. "3456789012345678901234567890";
  8647. // Variables to capture logging data
  8648. std::string pre_compression_body;
  8649. std::string pre_compression_content_type;
  8650. std::string pre_compression_content_encoding;
  8651. std::string post_compression_body;
  8652. std::string post_compression_content_type;
  8653. std::string post_compression_content_encoding;
  8654. // Set up pre-compression logger
  8655. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8656. const Response &res) {
  8657. pre_compression_body = res.body;
  8658. pre_compression_content_type = res.get_header_value("Content-Type");
  8659. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8660. });
  8661. // Set up post-compression logger
  8662. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8663. post_compression_body = res.body;
  8664. post_compression_content_type = res.get_header_value("Content-Type");
  8665. post_compression_content_encoding =
  8666. res.get_header_value("Content-Encoding");
  8667. });
  8668. // Test with gzip compression
  8669. Headers headers;
  8670. headers.emplace("Accept-Encoding", "gzip");
  8671. auto res = cli_.Get("/compress", headers);
  8672. // Verify response was compressed
  8673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8674. EXPECT_EQ(StatusCode::OK_200, res->status);
  8675. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8676. // Verify pre-compression logger captured uncompressed content
  8677. EXPECT_EQ(test_content, pre_compression_body);
  8678. EXPECT_EQ("text/plain", pre_compression_content_type);
  8679. EXPECT_TRUE(pre_compression_content_encoding
  8680. .empty()); // No encoding header before compression
  8681. // Verify post-compression logger captured compressed content
  8682. EXPECT_NE(test_content,
  8683. post_compression_body); // Should be different after compression
  8684. EXPECT_EQ("text/plain", post_compression_content_type);
  8685. EXPECT_EQ("gzip", post_compression_content_encoding);
  8686. // Verify compressed content is smaller
  8687. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8688. }
  8689. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8690. const std::string test_content =
  8691. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8692. "3456789012345678901234567890";
  8693. std::string pre_compression_body;
  8694. std::string post_compression_body;
  8695. svr_.set_pre_compression_logger(
  8696. [&](const Request & /*req*/, const Response &res) {
  8697. pre_compression_body = res.body;
  8698. });
  8699. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8700. post_compression_body = res.body;
  8701. });
  8702. Headers headers;
  8703. headers.emplace("Accept-Encoding", "br");
  8704. auto res = cli_.Get("/compress", headers);
  8705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8706. EXPECT_EQ(StatusCode::OK_200, res->status);
  8707. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8708. // Verify pre-compression content is uncompressed
  8709. EXPECT_EQ(test_content, pre_compression_body);
  8710. // Verify post-compression content is compressed
  8711. EXPECT_NE(test_content, post_compression_body);
  8712. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8713. }
  8714. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8715. const std::string test_content =
  8716. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8717. "3456789012345678901234567890";
  8718. std::string pre_compression_body;
  8719. std::string post_compression_body;
  8720. svr_.set_pre_compression_logger(
  8721. [&](const Request & /*req*/, const Response &res) {
  8722. pre_compression_body = res.body;
  8723. });
  8724. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8725. post_compression_body = res.body;
  8726. });
  8727. // Request without compression (use /nocompress endpoint)
  8728. Headers headers;
  8729. auto res = cli_.Get("/nocompress", headers);
  8730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8731. EXPECT_EQ(StatusCode::OK_200, res->status);
  8732. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8733. // Pre-compression logger should not be called when no compression is applied
  8734. EXPECT_TRUE(
  8735. pre_compression_body.empty()); // Pre-compression logger not called
  8736. EXPECT_EQ(
  8737. test_content,
  8738. post_compression_body); // Post-compression logger captures final content
  8739. }
  8740. TEST_F(ServerTest, LoggerSeesContentLength) {
  8741. size_t logged_content_length = 0;
  8742. std::string logged_content_length_header;
  8743. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8744. logged_content_length = res.content_length_;
  8745. logged_content_length_header = res.get_header_value("Content-Length");
  8746. });
  8747. auto res = cli_.Get("/nocompress");
  8748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8749. EXPECT_EQ(StatusCode::OK_200, res->status);
  8750. EXPECT_EQ(res->body.size(), logged_content_length);
  8751. EXPECT_EQ(std::to_string(logged_content_length),
  8752. logged_content_length_header);
  8753. }
  8754. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8755. const std::string test_content =
  8756. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8757. "3456789012345678901234567890";
  8758. std::string pre_compression_body;
  8759. bool pre_logger_called = false;
  8760. // Set only pre-compression logger
  8761. svr_.set_pre_compression_logger(
  8762. [&](const Request & /*req*/, const Response &res) {
  8763. pre_compression_body = res.body;
  8764. pre_logger_called = true;
  8765. });
  8766. Headers headers;
  8767. headers.emplace("Accept-Encoding", "gzip");
  8768. auto res = cli_.Get("/compress", headers);
  8769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8770. EXPECT_EQ(StatusCode::OK_200, res->status);
  8771. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8772. // Verify pre-compression logger was called
  8773. EXPECT_TRUE(pre_logger_called);
  8774. EXPECT_EQ(test_content, pre_compression_body);
  8775. }
  8776. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8777. {
  8778. // Test with Expect: 100-continue header - success case
  8779. // Server returns 100 Continue, client sends body, server returns 200 OK
  8780. Request req;
  8781. req.method = "POST";
  8782. req.path = "/post-large";
  8783. req.set_header("Expect", "100-continue");
  8784. req.body = LARGE_DATA;
  8785. Response res;
  8786. auto error = Error::Success;
  8787. cli_.set_keep_alive(true);
  8788. auto ret = cli_.send(req, res, error);
  8789. EXPECT_TRUE(ret);
  8790. EXPECT_EQ(StatusCode::OK_200, res.status);
  8791. EXPECT_EQ(LARGE_DATA, res.body);
  8792. }
  8793. {
  8794. // Test with Expect: 100-continue header - error case
  8795. // Client should not send the body when server returns an error
  8796. Request req;
  8797. req.method = "POST";
  8798. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8799. req.set_header("Expect", "100-continue");
  8800. req.body = LARGE_DATA;
  8801. Response res;
  8802. auto error = Error::Success;
  8803. auto start = std::chrono::high_resolution_clock::now();
  8804. cli_.set_keep_alive(true);
  8805. auto ret = cli_.send(req, res, error);
  8806. auto end = std::chrono::high_resolution_clock::now();
  8807. auto elapsed =
  8808. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8809. .count();
  8810. // With Expect: 100-continue, request completes successfully but with error
  8811. EXPECT_TRUE(ret);
  8812. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8813. EXPECT_EQ("close", res.get_header_value("Connection"));
  8814. EXPECT_FALSE(cli_.is_socket_open());
  8815. EXPECT_LE(elapsed, 2000);
  8816. }
  8817. {
  8818. // Send an extra GET request to ensure error recovery without hanging
  8819. Request req;
  8820. req.method = "GET";
  8821. req.path = "/hi";
  8822. auto start = std::chrono::high_resolution_clock::now();
  8823. auto res = cli_.send(req);
  8824. auto end = std::chrono::high_resolution_clock::now();
  8825. auto elapsed =
  8826. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8827. .count();
  8828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8829. EXPECT_EQ(StatusCode::OK_200, res->status);
  8830. EXPECT_EQ("Hello World!", res->body);
  8831. EXPECT_LE(elapsed, 500);
  8832. }
  8833. }
  8834. TEST(ZstdDecompressor, ChunkedDecompression) {
  8835. std::string data;
  8836. for (size_t i = 0; i < 32 * 1024; ++i) {
  8837. data.push_back(static_cast<char>('a' + i % 26));
  8838. }
  8839. std::string compressed_data;
  8840. {
  8841. httplib::detail::zstd_compressor compressor;
  8842. bool result = compressor.compress(
  8843. data.data(), data.size(),
  8844. /*last=*/true,
  8845. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8846. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8847. compressed_data_size);
  8848. return true;
  8849. });
  8850. ASSERT_TRUE(result);
  8851. }
  8852. std::string decompressed_data;
  8853. {
  8854. httplib::detail::zstd_decompressor decompressor;
  8855. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8856. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8857. size_t chunk_size = 130;
  8858. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8859. chunk_begin += chunk_size) {
  8860. size_t current_chunk_size =
  8861. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8862. bool result = decompressor.decompress(
  8863. compressed_data.data() + chunk_begin, current_chunk_size,
  8864. [&](const char *decompressed_data_chunk,
  8865. size_t decompressed_data_chunk_size) {
  8866. decompressed_data.insert(decompressed_data.size(),
  8867. decompressed_data_chunk,
  8868. decompressed_data_chunk_size);
  8869. return true;
  8870. });
  8871. ASSERT_TRUE(result);
  8872. }
  8873. }
  8874. ASSERT_EQ(data, decompressed_data);
  8875. }
  8876. TEST(ZstdDecompressor, Decompress) {
  8877. std::string original_text = "Compressed with ZSTD";
  8878. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8879. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8880. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8881. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8882. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8883. std::string decompressed_data;
  8884. {
  8885. httplib::detail::zstd_decompressor decompressor;
  8886. bool result = decompressor.decompress(
  8887. compressed_data.data(), compressed_data.size(),
  8888. [&](const char *decompressed_data_chunk,
  8889. size_t decompressed_data_chunk_size) {
  8890. decompressed_data.insert(decompressed_data.size(),
  8891. decompressed_data_chunk,
  8892. decompressed_data_chunk_size);
  8893. return true;
  8894. });
  8895. ASSERT_TRUE(result);
  8896. }
  8897. ASSERT_EQ(original_text, decompressed_data);
  8898. }
  8899. #endif
  8900. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8901. // separate chunks so that the server sees each part in its own read(). Used to
  8902. // place a read boundary at a specific offset of a request body.
  8903. static bool send_request_in_parts(time_t read_timeout_sec,
  8904. const std::vector<std::string> &parts,
  8905. std::string *resp = nullptr,
  8906. int port = PORT) {
  8907. auto error = Error::Success;
  8908. auto client_sock = detail::create_client_socket(
  8909. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8910. /*connection_timeout_sec=*/5, 0,
  8911. /*read_timeout_sec=*/5, 0,
  8912. /*write_timeout_sec=*/5, 0, std::string(), error);
  8913. if (client_sock == INVALID_SOCKET) { return false; }
  8914. auto ret = detail::process_client_socket(
  8915. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8916. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8917. for (size_t i = 0; i < parts.size(); i++) {
  8918. const auto &part = parts[i];
  8919. if (part.size() !=
  8920. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8921. return false;
  8922. }
  8923. if (i + 1 < parts.size()) {
  8924. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8925. }
  8926. }
  8927. char buf[512];
  8928. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8929. while (line_reader.getline()) {
  8930. if (resp) { *resp += line_reader.ptr(); }
  8931. }
  8932. return true;
  8933. });
  8934. detail::close_socket(client_sock);
  8935. return ret;
  8936. }
  8937. // Sends a raw request to a server listening at HOST:PORT.
  8938. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8939. std::string *resp = nullptr, int port = PORT) {
  8940. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8941. }
  8942. #ifdef CPPHTTPLIB_SSL_ENABLED
  8943. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8944. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8945. ASSERT_TRUE(svr.is_valid());
  8946. svr.set_read_timeout(1, 0);
  8947. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8948. auto se = detail::scope_exit([&] {
  8949. svr.stop();
  8950. t.join();
  8951. ASSERT_FALSE(svr.is_running());
  8952. });
  8953. svr.wait_until_ready();
  8954. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8955. // keeps each wait well within the read timeout. The server gives up a
  8956. // second in, so the bytes sent after that fail.
  8957. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8958. parts.resize(26, std::string(1, '\0'));
  8959. EXPECT_FALSE(send_request_in_parts(5, parts));
  8960. }
  8961. #endif
  8962. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8963. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  8964. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  8965. const std::vector<std::string> &parts,
  8966. std::string *resp = nullptr,
  8967. int port = PORT) {
  8968. auto error = Error::Success;
  8969. auto sock = detail::create_client_socket(
  8970. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8971. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  8972. /*write_timeout_sec=*/5, 0, std::string(), error);
  8973. if (sock == INVALID_SOCKET) { return false; }
  8974. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  8975. auto ctx = SSL_CTX_new(TLS_client_method());
  8976. auto ssl = SSL_new(ctx);
  8977. auto ssl_se = detail::scope_exit([&] {
  8978. SSL_free(ssl);
  8979. SSL_CTX_free(ctx);
  8980. });
  8981. SSL_set_fd(ssl, static_cast<int>(sock));
  8982. if (SSL_connect(ssl) != 1) { return false; }
  8983. for (size_t i = 0; i < parts.size(); i++) {
  8984. const auto &part = parts[i];
  8985. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  8986. static_cast<int>(part.size())) {
  8987. return false;
  8988. }
  8989. if (i + 1 < parts.size()) {
  8990. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8991. }
  8992. }
  8993. char buf[512];
  8994. int n;
  8995. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  8996. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  8997. }
  8998. return true;
  8999. }
  9000. #endif
  9001. // The request line, then a header value a byte at a time.
  9002. static std::vector<std::string> slow_request_head_parts() {
  9003. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9004. parts.resize(26, "a");
  9005. parts.emplace_back("\r\n\r\n");
  9006. return parts;
  9007. }
  9008. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9009. // within the one-second read timeout. The server gives up a second in, before
  9010. // the head is complete.
  9011. static void
  9012. expect_slow_request_head_dropped(Server &svr,
  9013. const std::function<std::string()> &send) {
  9014. std::atomic<bool> handled(false);
  9015. svr.Get("/", [&](const Request &, Response &res) {
  9016. handled = true;
  9017. res.set_content("ok", "text/plain");
  9018. });
  9019. svr.set_read_timeout(1, 0);
  9020. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9021. auto se = detail::scope_exit([&] {
  9022. svr.stop();
  9023. t.join();
  9024. ASSERT_FALSE(svr.is_running());
  9025. });
  9026. svr.wait_until_ready();
  9027. auto resp = send();
  9028. EXPECT_FALSE(handled);
  9029. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9030. }
  9031. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9032. Server svr;
  9033. expect_slow_request_head_dropped(svr, [] {
  9034. std::string resp;
  9035. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9036. return resp;
  9037. });
  9038. }
  9039. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9040. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9042. ASSERT_TRUE(svr.is_valid());
  9043. expect_slow_request_head_dropped(svr, [] {
  9044. std::string resp;
  9045. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9046. return resp;
  9047. });
  9048. }
  9049. #endif
  9050. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9051. Server svr;
  9052. std::string header_value;
  9053. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9054. header_value = req.get_header_value("foo");
  9055. res.set_content("ok", "text/plain");
  9056. });
  9057. thread t = thread([&] { svr.listen(HOST, PORT); });
  9058. auto se = detail::scope_exit([&] {
  9059. svr.stop();
  9060. t.join();
  9061. ASSERT_FALSE(svr.is_running());
  9062. });
  9063. svr.wait_until_ready();
  9064. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9065. // like characters are not treated the same - use vertical tab and escape.
  9066. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9067. "foo: \t \v bar \x1B\t \r\n"
  9068. "Connection: close\r\n"
  9069. "\r\n";
  9070. std::string res;
  9071. ASSERT_TRUE(send_request(5, req, &res));
  9072. EXPECT_EQ(header_value, "");
  9073. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9074. }
  9075. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9076. Server svr;
  9077. std::string received;
  9078. svr.Get("/order", [&](const Request &req, Response &res) {
  9079. received = entries_to_string(req.headers);
  9080. res.set_content("ok", "text/plain");
  9081. });
  9082. auto port = svr.bind_to_any_port(HOST);
  9083. thread t = thread([&] { svr.listen_after_bind(); });
  9084. auto se = detail::scope_exit([&] {
  9085. svr.stop();
  9086. t.join();
  9087. ASSERT_FALSE(svr.is_running());
  9088. });
  9089. svr.wait_until_ready();
  9090. const std::string req = "GET /order HTTP/1.1\r\n"
  9091. "Host: localhost\r\n"
  9092. "X-First: 1\r\n"
  9093. "X-Dup: a\r\n"
  9094. "X-Second: 2\r\n"
  9095. "X-Dup: b\r\n"
  9096. "Connection: close\r\n"
  9097. "\r\n";
  9098. std::string res;
  9099. ASSERT_TRUE(send_request(5, req, &res, port));
  9100. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9101. EXPECT_EQ(
  9102. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9103. received);
  9104. }
  9105. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9106. Server svr;
  9107. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9108. res.set_header("Set-Cookie", "first=1");
  9109. res.set_header("X-Between", "y");
  9110. res.set_header("Set-Cookie", "second=2");
  9111. res.set_content("ok", "text/plain");
  9112. });
  9113. auto port = svr.bind_to_any_port(HOST);
  9114. thread t = thread([&] { svr.listen_after_bind(); });
  9115. auto se = detail::scope_exit([&] {
  9116. svr.stop();
  9117. t.join();
  9118. ASSERT_FALSE(svr.is_running());
  9119. });
  9120. svr.wait_until_ready();
  9121. Client cli(HOST, port);
  9122. auto res = cli.Get("/cookies");
  9123. ASSERT_TRUE(res);
  9124. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9125. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9126. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9127. }
  9128. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9129. Server svr;
  9130. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9131. auto i = new int(0);
  9132. res.set_header("Trailer", "X-Safe, X-Reflected");
  9133. res.set_chunked_content_provider(
  9134. "text/plain",
  9135. [i](size_t /*offset*/, DataSink &sink) {
  9136. if (*i == 0) {
  9137. sink.os << "body";
  9138. } else {
  9139. Headers trailer;
  9140. // A valid trailer that must survive.
  9141. trailer.emplace("X-Safe", "safe");
  9142. // Attacker-controlled value carrying CR/LF (response splitting).
  9143. trailer.emplace("X-Reflected",
  9144. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9145. // Attacker-controlled name carrying CR/LF.
  9146. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9147. sink.done_with_trailer(trailer);
  9148. }
  9149. (*i)++;
  9150. return true;
  9151. },
  9152. [i](bool /*success*/) { delete i; });
  9153. });
  9154. thread t = thread([&] { svr.listen(HOST, PORT); });
  9155. auto se = detail::scope_exit([&] {
  9156. svr.stop();
  9157. t.join();
  9158. ASSERT_FALSE(svr.is_running());
  9159. });
  9160. svr.wait_until_ready();
  9161. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9162. "Host: " + HOST +
  9163. "\r\n"
  9164. "Connection: close\r\n"
  9165. "\r\n";
  9166. std::string res;
  9167. ASSERT_TRUE(send_request(5, req, &res));
  9168. // The injected fields must not appear anywhere in the raw response.
  9169. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9170. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9171. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9172. // Invalid trailers are dropped entirely, matching set_header().
  9173. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9174. // The valid trailer still passes through.
  9175. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9176. }
  9177. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9178. Server svr;
  9179. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9180. // res.headers is a public field an application can populate directly,
  9181. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9182. // A valid header that must survive.
  9183. res.headers.emplace("X-Safe", "safe");
  9184. // Attacker-controlled value carrying CR/LF (response splitting).
  9185. res.headers.emplace("X-Reflected",
  9186. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9187. // Attacker-controlled name carrying CR/LF.
  9188. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9189. res.set_content("body", "text/plain");
  9190. });
  9191. thread t = thread([&] { svr.listen(HOST, PORT); });
  9192. auto se = detail::scope_exit([&] {
  9193. svr.stop();
  9194. t.join();
  9195. ASSERT_FALSE(svr.is_running());
  9196. });
  9197. svr.wait_until_ready();
  9198. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9199. "Host: " + HOST +
  9200. "\r\n"
  9201. "Connection: close\r\n"
  9202. "\r\n";
  9203. std::string res;
  9204. ASSERT_TRUE(send_request(5, req, &res));
  9205. // The injected fields must not appear anywhere in the raw response.
  9206. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9207. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9208. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9209. // Invalid headers are dropped entirely, matching set_header().
  9210. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9211. // The valid header still passes through.
  9212. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9213. }
  9214. // Forward declaration: in split builds split.py strips `inline` and moves the
  9215. // definition into httplib.cc, so detail::write_request_line is not visible from
  9216. // the public httplib.h. Re-declaring it here lets the tests link against the
  9217. // symbol in both header-only and split builds.
  9218. namespace httplib {
  9219. namespace detail {
  9220. ssize_t write_request_line(Stream &strm, const std::string &method,
  9221. const std::string &path);
  9222. } // namespace detail
  9223. } // namespace httplib
  9224. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9225. // A well-formed target is written verbatim.
  9226. {
  9227. detail::BufferStream strm;
  9228. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9229. EXPECT_GT(n, 0);
  9230. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9231. }
  9232. // A target carrying CR/LF, SP or other control octets must be rejected
  9233. // before anything reaches the wire, otherwise it splits the request line and
  9234. // injects a header or a whole request.
  9235. const std::string evil_targets[] = {
  9236. "/a\r\nInjected: pwned",
  9237. "/a\rInjected",
  9238. "/a\nInjected",
  9239. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9240. "/a b",
  9241. "/a\tb",
  9242. "/a\x7f",
  9243. };
  9244. for (const auto &evil : evil_targets) {
  9245. detail::BufferStream strm;
  9246. auto n = detail::write_request_line(strm, "GET", evil);
  9247. EXPECT_LT(n, 0);
  9248. EXPECT_TRUE(strm.get_buffer().empty());
  9249. }
  9250. }
  9251. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9252. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9253. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9254. // target reaches write_request. The client must fail cleanly with
  9255. // Error::Write instead of putting a request-line-less, header-injecting
  9256. // request on the wire.
  9257. Server svr;
  9258. svr.Get("/a", [](const Request &, Response &res) {
  9259. res.set_content("ok", "text/plain");
  9260. });
  9261. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9262. auto se = detail::scope_exit([&] {
  9263. svr.stop();
  9264. thread.join();
  9265. ASSERT_FALSE(svr.is_running());
  9266. });
  9267. svr.wait_until_ready();
  9268. {
  9269. Client cli(HOST, PORT);
  9270. cli.set_path_encode(false);
  9271. // The request is rejected before anything is written, so the connection
  9272. // stays silent and the subsequent response read would otherwise block for
  9273. // the full default read timeout. Shorten it -- the assertion is on the
  9274. // error, not the timeout.
  9275. cli.set_read_timeout(1, 0);
  9276. auto res = cli.Get("/a\r\nInjected: pwned");
  9277. EXPECT_FALSE(res);
  9278. EXPECT_EQ(Error::Write, res.error());
  9279. }
  9280. }
  9281. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9282. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9283. // including extension methods.
  9284. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9285. for (const auto &method : good_methods) {
  9286. detail::BufferStream strm;
  9287. auto n = detail::write_request_line(strm, method, "/");
  9288. EXPECT_GT(n, 0);
  9289. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9290. }
  9291. // A method carrying CR/LF would split the request line and smuggle a whole
  9292. // request ahead of the real one. A space or an empty method corrupts the
  9293. // request line. All must be rejected before anything reaches the wire.
  9294. const std::string evil_methods[] = {
  9295. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9296. "GET\r\nInjected: pwned",
  9297. "GET\r",
  9298. "GET\n",
  9299. "GE T",
  9300. "",
  9301. };
  9302. for (const auto &evil : evil_methods) {
  9303. detail::BufferStream strm;
  9304. auto n = detail::write_request_line(strm, evil, "/");
  9305. EXPECT_LT(n, 0);
  9306. EXPECT_TRUE(strm.get_buffer().empty());
  9307. }
  9308. }
  9309. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9310. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9311. // through Client::send must fail with Error::Write and no request, neither
  9312. // the smuggled one nor the real one, may reach the server.
  9313. Server svr;
  9314. std::atomic<int> request_count(0);
  9315. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9316. request_count++;
  9317. res.status = StatusCode::OK_200;
  9318. return Server::HandlerResponse::Handled;
  9319. });
  9320. auto port = svr.bind_to_any_port(HOST);
  9321. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9322. auto se = detail::scope_exit([&] {
  9323. svr.stop();
  9324. thread.join();
  9325. ASSERT_FALSE(svr.is_running());
  9326. });
  9327. svr.wait_until_ready();
  9328. {
  9329. Client cli(HOST, port);
  9330. const std::string evil_methods[] = {
  9331. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9332. "GE T",
  9333. "",
  9334. };
  9335. for (const auto &evil : evil_methods) {
  9336. Request req;
  9337. req.method = evil;
  9338. req.path = "/";
  9339. auto res = cli.send(req);
  9340. EXPECT_FALSE(res);
  9341. EXPECT_EQ(Error::Write, res.error());
  9342. }
  9343. auto handle =
  9344. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9345. EXPECT_FALSE(handle.is_valid());
  9346. EXPECT_EQ(Error::Write, handle.error);
  9347. // A valid request on the same client still goes through.
  9348. auto res = cli.Get("/");
  9349. ASSERT_TRUE(res);
  9350. EXPECT_EQ(StatusCode::OK_200, res->status);
  9351. }
  9352. EXPECT_EQ(1, request_count.load());
  9353. }
  9354. // Sends a raw request and verifies that there isn't a crash or exception.
  9355. static void test_raw_request(const std::string &req,
  9356. std::string *out = nullptr) {
  9357. Server svr;
  9358. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9359. res.set_content("ok", "text/plain");
  9360. });
  9361. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9362. res.set_content("ok", "text/plain");
  9363. });
  9364. svr.Get("/header_field_value_check",
  9365. [&](const Request & /*req*/, Response &res) {
  9366. res.set_content("ok", "text/plain");
  9367. });
  9368. svr.CustomRoute("PROPFIND", "/dav",
  9369. [&](const Request & /*req*/, Response &res) {
  9370. res.status = StatusCode::MultiStatus_207;
  9371. });
  9372. // Server read timeout must be longer than the client read timeout for the
  9373. // bug to reproduce, probably to force the server to process a request
  9374. // without a trailing blank line.
  9375. const time_t client_read_timeout_sec = 1;
  9376. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9377. bool listen_thread_ok = false;
  9378. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9379. auto se = detail::scope_exit([&] {
  9380. svr.stop();
  9381. t.join();
  9382. ASSERT_FALSE(svr.is_running());
  9383. EXPECT_TRUE(listen_thread_ok);
  9384. });
  9385. svr.wait_until_ready();
  9386. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9387. }
  9388. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9389. // A certain header line causes an exception if the header property is parsed
  9390. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9391. test_raw_request(
  9392. "GET /hi HTTP/1.1\r\n"
  9393. " : "
  9394. " "
  9395. " ");
  9396. }
  9397. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9398. // A certain header line causes an exception if the header property *name* is
  9399. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9400. // greedy matcher and requires backtracking when there are a lot of ":"
  9401. // characters.
  9402. // This occurs with libc++ but not libstdc++.
  9403. test_raw_request(
  9404. "GET /hi HTTP/1.1\r\n"
  9405. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9406. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9407. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9408. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9409. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9410. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9411. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9412. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9413. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9414. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9415. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9416. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9417. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9418. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9419. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9420. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9421. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9422. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9423. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9424. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9425. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9426. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9427. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9428. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9429. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9430. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9431. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9432. "&&&%%%");
  9433. }
  9434. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9435. // Make sure this doesn't crash the server.
  9436. // In a previous version of the header line regex, the "\r" rendered the line
  9437. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9438. // a new position where the leading white space ended and the field value
  9439. // began.
  9440. // The crash occurs with libc++ but not libstdc++.
  9441. test_raw_request("GET /hi HTTP/1.1\r\n"
  9442. "a:" +
  9443. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9444. "\r\n"
  9445. "\r\n");
  9446. }
  9447. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9448. const char *rejected[] = {
  9449. // RFC 9112 §3: one SP between the parts, and nothing else
  9450. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9451. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9452. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9453. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9454. // A request-target has no fragment
  9455. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9456. // An HTTP/1.1 request needs a Host
  9457. "GET /hi HTTP/1.1\r\n\r\n",
  9458. };
  9459. for (auto request : rejected) {
  9460. std::string out;
  9461. test_raw_request(request, &out);
  9462. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9463. }
  9464. std::string out;
  9465. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9466. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9467. }
  9468. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9469. // RFC 9112 §6.1
  9470. const char *requests[] = {
  9471. "PUT /put_hi HTTP/1.1\r\n"
  9472. "Host: localhost\r\n"
  9473. "Content-Length: 0\r\n"
  9474. "Transfer-Encoding: chunked\r\n"
  9475. "\r\n"
  9476. "0\r\n\r\n",
  9477. "PUT /put_hi HTTP/1.0\r\n"
  9478. "Connection: keep-alive\r\n"
  9479. "Transfer-Encoding: chunked\r\n"
  9480. "\r\n"
  9481. "0\r\n\r\n",
  9482. };
  9483. for (auto request : requests) {
  9484. std::string out;
  9485. test_raw_request(request, &out);
  9486. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9487. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9488. }
  9489. }
  9490. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9491. std::string out;
  9492. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9493. "Content-Type: text/plain\r\n"
  9494. "Transfer-Encoding: chunked\r\n"
  9495. "\r\n"
  9496. "nothex\r\n",
  9497. &out);
  9498. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9499. }
  9500. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9501. std::string out;
  9502. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9503. "Content-Type: text/plain\r\n"
  9504. "Transfer-Encoding: chunked\r\n"
  9505. "\r\n"
  9506. "3\r\n"
  9507. "xyz\r\n"
  9508. "NaN\r\n",
  9509. &out);
  9510. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9511. }
  9512. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9513. std::string out;
  9514. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9515. "Content-Type: text/plain\r\n"
  9516. "Transfer-Encoding: chunked\r\n"
  9517. "\r\n"
  9518. // Length is too large for 64 bits.
  9519. "1ffffffffffffffff\r\n"
  9520. "xyz\r\n",
  9521. &out);
  9522. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9523. }
  9524. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9525. test_raw_request("GET /hi HTTP/1.1\r\n"
  9526. "Content-Type: text/plain\r\n\r");
  9527. }
  9528. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9529. std::string out;
  9530. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9531. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9532. }
  9533. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9534. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9535. std::string out;
  9536. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9537. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9538. }
  9539. }
  9540. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9541. std::string out;
  9542. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9543. "Host: localhost\r\n"
  9544. "Connection: close\r\n\r\n",
  9545. &out);
  9546. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9547. }
  9548. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9549. Server svr;
  9550. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9551. EXPECT_TRUE(!req.remote_addr.empty());
  9552. });
  9553. thread t = thread([&] { svr.listen(HOST, PORT); });
  9554. auto se = detail::scope_exit([&] {
  9555. svr.stop();
  9556. t.join();
  9557. ASSERT_FALSE(svr.is_running());
  9558. });
  9559. svr.wait_until_ready();
  9560. // Send an invalid request line to trigger Bad Request
  9561. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9562. std::string out;
  9563. ASSERT_TRUE(send_request(5, bad_req, &out));
  9564. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9565. }
  9566. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9567. // answered right away rather than blocking on a read that waits for EOF.
  9568. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9569. std::string out;
  9570. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9571. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9572. }
  9573. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9574. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9575. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9576. for (const auto *method : methods) {
  9577. Server svr;
  9578. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9579. EXPECT_FALSE(svr.is_valid()) << method;
  9580. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9581. }
  9582. }
  9583. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9584. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9585. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9586. for (const auto *method : methods) {
  9587. Server svr;
  9588. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9589. EXPECT_FALSE(svr.is_valid()) << method;
  9590. }
  9591. }
  9592. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9593. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9594. "COPY", "MOVE", "LOCK",
  9595. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9596. Server svr;
  9597. for (const auto *method : methods) {
  9598. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9599. }
  9600. EXPECT_TRUE(svr.is_valid());
  9601. }
  9602. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9603. Server svr;
  9604. svr.CustomRoute("POST", "/x",
  9605. [](const Request &, Response &, const ContentReader &) {});
  9606. EXPECT_FALSE(svr.is_valid());
  9607. }
  9608. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9609. Server svr;
  9610. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9611. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9612. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9613. EXPECT_FALSE(svr.is_valid());
  9614. }
  9615. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9616. Server svr;
  9617. auto captured = Error::Success;
  9618. svr.set_error_logger(
  9619. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9620. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9621. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9622. }
  9623. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9624. std::string out;
  9625. std::string request(
  9626. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9627. test_raw_request(request, &out);
  9628. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9629. }
  9630. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9631. std::string out;
  9632. std::string request(
  9633. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9634. test_raw_request(request, &out);
  9635. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9636. }
  9637. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9638. std::string out;
  9639. std::string request(
  9640. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9641. test_raw_request(request, &out);
  9642. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9643. }
  9644. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9645. std::string out;
  9646. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9647. "Host: localhost\r\n"
  9648. "Test: \r\n\r\n",
  9649. &out);
  9650. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9651. }
  9652. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9653. Server svr;
  9654. std::string x_custom;
  9655. std::string cookie;
  9656. std::string xff;
  9657. std::string x_unicode;
  9658. std::string x_iis;
  9659. svr.Get("/check", [&](const Request &req, Response &res) {
  9660. x_custom = req.get_header_value("X-Custom");
  9661. cookie = req.get_header_value("Cookie");
  9662. xff = req.get_header_value("X-Forwarded-For");
  9663. x_unicode = req.get_header_value("X-Unicode");
  9664. x_iis = req.get_header_value("X-IIS");
  9665. res.set_content("ok", "text/plain");
  9666. });
  9667. thread t = thread([&] { svr.listen(HOST, PORT); });
  9668. auto se = detail::scope_exit([&] {
  9669. svr.stop();
  9670. t.join();
  9671. ASSERT_FALSE(svr.is_running());
  9672. });
  9673. svr.wait_until_ready();
  9674. const std::string req = "GET /check HTTP/1.1\r\n"
  9675. "Host: localhost\r\n"
  9676. "X-Custom: a%0D%0AInjected: b\r\n"
  9677. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9678. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9679. "X-Unicode: %E3%81%82\r\n"
  9680. "X-IIS: %u00E9\r\n"
  9681. "Connection: close\r\n"
  9682. "\r\n";
  9683. std::string res;
  9684. ASSERT_TRUE(send_request(5, req, &res));
  9685. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9686. // Every value must be returned verbatim (wire form), with no decoding.
  9687. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9688. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9689. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9690. EXPECT_EQ("%E3%81%82", x_unicode);
  9691. EXPECT_EQ("%u00E9", x_iis);
  9692. }
  9693. // Applications that previously relied on automatic percent-decoding can
  9694. // reproduce the old behavior by explicitly calling decode_path_component()
  9695. // or, for RFC 3986 conformance, decode_uri_component().
  9696. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9697. Server svr;
  9698. std::string decoded;
  9699. svr.Get("/check", [&](const Request &req, Response &res) {
  9700. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9701. res.set_content("ok", "text/plain");
  9702. });
  9703. thread t = thread([&] { svr.listen(HOST, PORT); });
  9704. auto se = detail::scope_exit([&] {
  9705. svr.stop();
  9706. t.join();
  9707. ASSERT_FALSE(svr.is_running());
  9708. });
  9709. svr.wait_until_ready();
  9710. const std::string req = "GET /check HTTP/1.1\r\n"
  9711. "Host: localhost\r\n"
  9712. "X-Custom: hello%20world\r\n"
  9713. "Connection: close\r\n"
  9714. "\r\n";
  9715. std::string res;
  9716. ASSERT_TRUE(send_request(5, req, &res));
  9717. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9718. EXPECT_EQ("hello world", decoded);
  9719. }
  9720. // Regression test for #2033. Browsers send Referer values that include
  9721. // percent-encoded characters such as %0A inside the URL. Decoding the
  9722. // header value would either trip the post-decode CR/LF/NUL guard (the
  9723. // original bug, returning 400) or, after that guard was relaxed, silently
  9724. // store a literal LF — both unacceptable. The wire form must round-trip.
  9725. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9726. Server svr;
  9727. std::string referer;
  9728. svr.Get("/check", [&](const Request &req, Response &res) {
  9729. referer = req.get_header_value("Referer");
  9730. res.set_content("ok", "text/plain");
  9731. });
  9732. thread t = thread([&] { svr.listen(HOST, PORT); });
  9733. auto se = detail::scope_exit([&] {
  9734. svr.stop();
  9735. t.join();
  9736. ASSERT_FALSE(svr.is_running());
  9737. });
  9738. svr.wait_until_ready();
  9739. const std::string req = "GET /check HTTP/1.1\r\n"
  9740. "Host: localhost\r\n"
  9741. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9742. "Connection: close\r\n"
  9743. "\r\n";
  9744. std::string res;
  9745. ASSERT_TRUE(send_request(5, req, &res));
  9746. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9747. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9748. }
  9749. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9750. Server svr;
  9751. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9752. res.set_header("Cache-Control", "no-cache");
  9753. res.set_chunked_content_provider(
  9754. "text/event-stream", [](size_t offset, DataSink &sink) {
  9755. std::string s = "data:";
  9756. s += std::to_string(offset);
  9757. s += "\n\n";
  9758. auto ret = sink.write(s.data(), s.size());
  9759. EXPECT_TRUE(ret);
  9760. std::this_thread::sleep_for(std::chrono::seconds(1));
  9761. return true;
  9762. });
  9763. });
  9764. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9765. svr.wait_until_ready();
  9766. Client client(HOST, PORT);
  9767. const Headers headers = {{"Accept", "text/event-stream"}};
  9768. auto get_thread = std::thread([&client, &headers]() {
  9769. auto res = client.Get(
  9770. "/events", headers,
  9771. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9772. });
  9773. auto se = detail::scope_exit([&] {
  9774. svr.stop();
  9775. get_thread.join();
  9776. listen_thread.join();
  9777. ASSERT_FALSE(svr.is_running());
  9778. });
  9779. // Give GET time to get a few messages.
  9780. std::this_thread::sleep_for(std::chrono::seconds(2));
  9781. }
  9782. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9783. httplib::Server svr;
  9784. svr.Post("/hi",
  9785. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9786. res.status = StatusCode::OK_200;
  9787. });
  9788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9789. svr.wait_until_ready();
  9790. Client cli(HOST, PORT);
  9791. auto res = cli.Post("/hi", "data", "text/plain");
  9792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9793. EXPECT_EQ(StatusCode::OK_200, res->status);
  9794. svr.stop();
  9795. thread.join();
  9796. ASSERT_FALSE(svr.is_running());
  9797. res = cli.Post("/hi", "data", "text/plain");
  9798. ASSERT_FALSE(res);
  9799. }
  9800. TEST(ServerStopTest, ListenFailure) {
  9801. Server svr;
  9802. auto t = thread([&]() {
  9803. auto ret = svr.listen("????", PORT);
  9804. EXPECT_FALSE(ret);
  9805. });
  9806. svr.wait_until_ready();
  9807. svr.stop();
  9808. t.join();
  9809. }
  9810. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9811. TEST(ServerStopTest, Decommision) {
  9812. Server svr;
  9813. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9814. for (int i = 0; i < 4; i++) {
  9815. auto is_even = !(i % 2);
  9816. std::thread t{[&] {
  9817. try {
  9818. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9819. if (is_even) {
  9820. throw std::runtime_error("Some thing that happens to go wrong.");
  9821. }
  9822. svr.listen(HOST, PORT);
  9823. } catch (...) { svr.decommission(); }
  9824. }};
  9825. svr.wait_until_ready();
  9826. // Server is up
  9827. {
  9828. Client cli(HOST, PORT);
  9829. auto res = cli.Get("/hi");
  9830. if (is_even) {
  9831. EXPECT_FALSE(res);
  9832. } else {
  9833. EXPECT_TRUE(res);
  9834. EXPECT_EQ("hi...", res->body);
  9835. }
  9836. }
  9837. svr.stop();
  9838. t.join();
  9839. // Server is down...
  9840. {
  9841. Client cli(HOST, PORT);
  9842. auto res = cli.Get("/hi");
  9843. EXPECT_FALSE(res);
  9844. }
  9845. }
  9846. }
  9847. #endif
  9848. // Helper function for string body upload progress tests
  9849. template <typename SetupHandler, typename ClientCall>
  9850. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9851. ClientCall &&client_call,
  9852. const string &body) {
  9853. Server svr;
  9854. setup_handler(svr);
  9855. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9856. auto se = detail::scope_exit([&] {
  9857. svr.stop();
  9858. t.join();
  9859. });
  9860. svr.wait_until_ready();
  9861. Client cli(HOST, PORT);
  9862. vector<uint64_t> progress_values;
  9863. bool progress_called = false;
  9864. auto res =
  9865. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9866. progress_values.push_back(current);
  9867. progress_called = true;
  9868. return true;
  9869. });
  9870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9871. EXPECT_EQ(200, res->status);
  9872. EXPECT_TRUE(progress_called);
  9873. }
  9874. TEST(UploadProgressTest, PostStringBodyBasic) {
  9875. TestStringBodyUploadProgress(
  9876. [](Server &svr) {
  9877. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9878. res.set_content("received", "text/plain");
  9879. });
  9880. },
  9881. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9882. return cli.Post("/test", body, "text/plain", progress_callback);
  9883. },
  9884. "test data for upload progress");
  9885. }
  9886. TEST(UploadProgressTest, PutStringBodyBasic) {
  9887. TestStringBodyUploadProgress(
  9888. [](Server &svr) {
  9889. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9890. res.set_content("put received", "text/plain");
  9891. });
  9892. },
  9893. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9894. return cli.Put("/test", body, "text/plain", progress_callback);
  9895. },
  9896. "put test data for upload progress");
  9897. }
  9898. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9899. TestStringBodyUploadProgress(
  9900. [](Server &svr) {
  9901. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9902. res.set_content("patch received", "text/plain");
  9903. });
  9904. },
  9905. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9906. return cli.Patch("/test", body, "text/plain", progress_callback);
  9907. },
  9908. "patch test data for upload progress");
  9909. }
  9910. // Helper function for content provider upload progress tests
  9911. template <typename SetupHandler, typename ClientCall>
  9912. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9913. ClientCall &&client_call) {
  9914. Server svr;
  9915. setup_handler(svr);
  9916. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9917. auto se = detail::scope_exit([&] {
  9918. svr.stop();
  9919. t.join();
  9920. });
  9921. svr.wait_until_ready();
  9922. Client cli(HOST, PORT);
  9923. vector<uint64_t> progress_values;
  9924. auto res =
  9925. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9926. progress_values.push_back(current);
  9927. return true;
  9928. });
  9929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9930. EXPECT_EQ(200, res->status);
  9931. EXPECT_FALSE(progress_values.empty());
  9932. }
  9933. TEST(UploadProgressTest, PostContentProviderProgress) {
  9934. TestContentProviderUploadProgress(
  9935. [](Server &svr) {
  9936. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9937. res.set_content("provider received", "text/plain");
  9938. });
  9939. },
  9940. [](Client &cli, UploadProgress progress_callback) {
  9941. return cli.Post(
  9942. "/test", 9,
  9943. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9944. sink.os << "test data";
  9945. return true;
  9946. },
  9947. "text/plain", progress_callback);
  9948. });
  9949. }
  9950. // Helper function for multipart upload progress tests
  9951. template <typename SetupHandler, typename ClientCall>
  9952. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9953. ClientCall &&client_call,
  9954. const string &endpoint) {
  9955. Server svr;
  9956. setup_handler(svr);
  9957. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9958. auto se = detail::scope_exit([&] {
  9959. svr.stop();
  9960. t.join();
  9961. });
  9962. svr.wait_until_ready();
  9963. Client cli(HOST, PORT);
  9964. vector<uint64_t> progress_values;
  9965. UploadFormDataItems items = {
  9966. {"field1", "value1", "", ""},
  9967. {"field2", "longer value for progress tracking test", "", ""},
  9968. {"file1", "file content data for upload progress", "test.txt",
  9969. "text/plain"}};
  9970. auto res = client_call(cli, endpoint, items,
  9971. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9972. progress_values.push_back(current);
  9973. return true;
  9974. });
  9975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9976. EXPECT_EQ(200, res->status);
  9977. EXPECT_FALSE(progress_values.empty());
  9978. }
  9979. TEST(UploadProgressTest, PostMultipartProgress) {
  9980. TestMultipartUploadProgress(
  9981. [](Server &svr) {
  9982. svr.Post("/multipart", [](const Request &req, Response &res) {
  9983. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9984. res.set_content("multipart received", "text/plain");
  9985. });
  9986. },
  9987. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9988. UploadProgress progress_callback) {
  9989. return cli.Post(endpoint, items, progress_callback);
  9990. },
  9991. "/multipart");
  9992. }
  9993. // Helper function for basic download progress tests
  9994. template <typename SetupHandler, typename ClientCall>
  9995. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9996. ClientCall &&client_call, const string &endpoint,
  9997. size_t expected_content_size) {
  9998. Server svr;
  9999. setup_handler(svr);
  10000. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10001. auto se = detail::scope_exit([&] {
  10002. svr.stop();
  10003. t.join();
  10004. });
  10005. svr.wait_until_ready();
  10006. Client cli(HOST, PORT);
  10007. vector<uint64_t> progress_values;
  10008. auto res = client_call(cli, endpoint,
  10009. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10010. progress_values.push_back(current);
  10011. return true;
  10012. });
  10013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10014. EXPECT_EQ(200, res->status);
  10015. EXPECT_FALSE(progress_values.empty());
  10016. EXPECT_EQ(expected_content_size, res->body.size());
  10017. }
  10018. TEST(DownloadProgressTest, GetBasic) {
  10019. TestBasicDownloadProgress(
  10020. [](Server &svr) {
  10021. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10022. string content(1000, 'D');
  10023. res.set_content(content, "text/plain");
  10024. });
  10025. },
  10026. [](Client &cli, const string &endpoint,
  10027. DownloadProgress progress_callback) {
  10028. return cli.Get(endpoint, progress_callback);
  10029. },
  10030. "/download", 1000u);
  10031. }
  10032. // Helper function for content receiver download progress tests
  10033. template <typename SetupHandler, typename ClientCall>
  10034. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10035. ClientCall &&client_call,
  10036. const string &endpoint,
  10037. size_t expected_content_size) {
  10038. Server svr;
  10039. setup_handler(svr);
  10040. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10041. auto se = detail::scope_exit([&] {
  10042. svr.stop();
  10043. t.join();
  10044. });
  10045. svr.wait_until_ready();
  10046. Client cli(HOST, PORT);
  10047. vector<uint64_t> progress_values;
  10048. string received_body;
  10049. auto res = client_call(
  10050. cli, endpoint,
  10051. [&](const char *data, size_t data_length) -> bool {
  10052. received_body.append(data, data_length);
  10053. return true;
  10054. },
  10055. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10056. progress_values.push_back(current);
  10057. return true;
  10058. });
  10059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10060. EXPECT_EQ(200, res->status);
  10061. EXPECT_FALSE(progress_values.empty());
  10062. EXPECT_EQ(expected_content_size, received_body.size());
  10063. EXPECT_TRUE(res->body.empty());
  10064. }
  10065. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10066. TestContentReceiverDownloadProgress(
  10067. [](Server &svr) {
  10068. svr.Get("/download-receiver",
  10069. [](const Request & /*req*/, Response &res) {
  10070. string content(2000, 'R');
  10071. res.set_content(content, "text/plain");
  10072. });
  10073. },
  10074. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10075. DownloadProgress progress_callback) {
  10076. return cli.Get(endpoint, content_receiver, progress_callback);
  10077. },
  10078. "/download-receiver", 2000u);
  10079. }
  10080. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10081. // A provider reaching a pass with nothing to hand over - an empty buffer
  10082. // popped off a queue, say - must not be taken to mean the body is finished.
  10083. // It used to end the loop with the terminating chunk unwritten while the
  10084. // server still considered the response complete, so the peer waited for an
  10085. // end that never arrived.
  10086. Server svr;
  10087. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10088. auto step = std::make_shared<int>(0);
  10089. res.set_chunked_content_provider("text/plain",
  10090. [step](size_t /*offset*/, DataSink &sink) {
  10091. switch ((*step)++) {
  10092. case 0: sink.write("", 0); break;
  10093. case 1: sink.write("hello", 5); break;
  10094. default: sink.done(); break;
  10095. }
  10096. return true;
  10097. });
  10098. });
  10099. auto port = svr.bind_to_any_port(HOST);
  10100. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10101. auto listen_se = detail::scope_exit([&] {
  10102. svr.stop();
  10103. listen_thread.join();
  10104. ASSERT_FALSE(svr.is_running());
  10105. });
  10106. svr.wait_until_ready();
  10107. Client cli(HOST, port);
  10108. // Without the fix the body is never terminated, so bound the wait rather
  10109. // than letting the test hang on the default read timeout.
  10110. cli.set_read_timeout(5, 0);
  10111. auto res = cli.Get("/stream");
  10112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10113. EXPECT_EQ(StatusCode::OK_200, res->status);
  10114. EXPECT_EQ("hello", res->body);
  10115. }
  10116. TEST(StreamingTest, NoContentLengthStreaming) {
  10117. Server svr;
  10118. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10119. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10120. if (offset < 6) {
  10121. sink.os << (offset < 3 ? "a" : "b");
  10122. } else {
  10123. sink.done();
  10124. }
  10125. return true;
  10126. });
  10127. });
  10128. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10129. auto listen_se = detail::scope_exit([&] {
  10130. svr.stop();
  10131. listen_thread.join();
  10132. ASSERT_FALSE(svr.is_running());
  10133. });
  10134. svr.wait_until_ready();
  10135. Client client(HOST, PORT);
  10136. auto get_thread = std::thread([&client]() {
  10137. std::string s;
  10138. auto res =
  10139. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10140. s += std::string(data, len);
  10141. return true;
  10142. });
  10143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10144. EXPECT_EQ(StatusCode::OK_200, res->status);
  10145. EXPECT_EQ("aaabbb", s);
  10146. });
  10147. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10148. // Give GET time to get a few messages.
  10149. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10150. }
  10151. TEST(MountTest, Unmount) {
  10152. Server svr;
  10153. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10154. auto se = detail::scope_exit([&] {
  10155. svr.stop();
  10156. listen_thread.join();
  10157. ASSERT_FALSE(svr.is_running());
  10158. });
  10159. svr.wait_until_ready();
  10160. Client cli("localhost", PORT);
  10161. svr.set_mount_point("/mount2", "./www2");
  10162. auto res = cli.Get("/");
  10163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10164. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10165. res = cli.Get("/mount2/dir/test.html");
  10166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10167. EXPECT_EQ(StatusCode::OK_200, res->status);
  10168. svr.set_mount_point("/", "./www");
  10169. res = cli.Get("/dir/");
  10170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10171. EXPECT_EQ(StatusCode::OK_200, res->status);
  10172. svr.remove_mount_point("/");
  10173. res = cli.Get("/dir/");
  10174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10175. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10176. svr.remove_mount_point("/mount2");
  10177. res = cli.Get("/mount2/dir/test.html");
  10178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10179. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10180. }
  10181. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10182. Server svr;
  10183. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10184. svr.Get("/api/hello", [](const Request &, Response &res) {
  10185. res.set_content("api", "text/plain");
  10186. });
  10187. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10188. auto se = detail::scope_exit([&] {
  10189. svr.stop();
  10190. listen_thread.join();
  10191. ASSERT_FALSE(svr.is_running());
  10192. });
  10193. svr.wait_until_ready();
  10194. Client cli(HOST, PORT);
  10195. auto res = cli.Get("/dir/test.html");
  10196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10197. EXPECT_EQ(StatusCode::OK_200, res->status);
  10198. res = cli.Get("/api/hello");
  10199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10200. EXPECT_EQ(StatusCode::OK_200, res->status);
  10201. EXPECT_EQ("api", res->body);
  10202. }
  10203. TEST(MountTest, PathSegmentBoundary) {
  10204. Server svr;
  10205. svr.set_mount_point("/mount2", "./www2");
  10206. svr.set_mount_point("/", "./www");
  10207. auto port = svr.bind_to_any_port(HOST);
  10208. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10209. auto se = detail::scope_exit([&] {
  10210. svr.stop();
  10211. listen_thread.join();
  10212. ASSERT_FALSE(svr.is_running());
  10213. });
  10214. svr.wait_until_ready();
  10215. Client cli(HOST, port);
  10216. auto res = cli.Get("/mount2/dir/test.html");
  10217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10218. EXPECT_EQ(StatusCode::OK_200, res->status);
  10219. // "/mount2" must not match part-way through a path segment.
  10220. res = cli.Get("/mount2dir/test.html");
  10221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10223. // A mount point ending in '/' keeps matching every path below it.
  10224. res = cli.Get("/dir/test.html");
  10225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10226. EXPECT_EQ(StatusCode::OK_200, res->status);
  10227. }
  10228. TEST(MountTest, Redicect) {
  10229. Server svr;
  10230. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10231. auto se = detail::scope_exit([&] {
  10232. svr.stop();
  10233. listen_thread.join();
  10234. ASSERT_FALSE(svr.is_running());
  10235. });
  10236. svr.set_mount_point("/", "./www");
  10237. svr.wait_until_ready();
  10238. Client cli("localhost", PORT);
  10239. auto res = cli.Get("/dir/");
  10240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10241. EXPECT_EQ(StatusCode::OK_200, res->status);
  10242. res = cli.Get("/dir");
  10243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10244. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10245. res = cli.Get("/file");
  10246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10247. EXPECT_EQ(StatusCode::OK_200, res->status);
  10248. res = cli.Get("/file/");
  10249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10250. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10251. cli.set_follow_location(true);
  10252. res = cli.Get("/dir");
  10253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10254. EXPECT_EQ(StatusCode::OK_200, res->status);
  10255. }
  10256. TEST(MountTest, MultibytesPathName) {
  10257. Server svr;
  10258. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10259. auto se = detail::scope_exit([&] {
  10260. svr.stop();
  10261. listen_thread.join();
  10262. ASSERT_FALSE(svr.is_running());
  10263. });
  10264. svr.set_mount_point("/", "./www");
  10265. svr.wait_until_ready();
  10266. Client cli("localhost", PORT);
  10267. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10269. EXPECT_EQ(StatusCode::OK_200, res->status);
  10270. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10271. }
  10272. #ifdef _WIN32
  10273. // Issue #2435: mmap::open() must succeed even when another handle holds
  10274. // the file open for writing (e.g. an active log file).
  10275. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10276. const char *path = "mmap_concurrent_writer_test.txt";
  10277. const char *content = "hello";
  10278. {
  10279. std::ofstream f(path, std::ios::binary);
  10280. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10281. }
  10282. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10283. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10284. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10285. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10286. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10287. detail::mmap m(path);
  10288. ASSERT_TRUE(m.is_open());
  10289. EXPECT_EQ(strlen(content), m.size());
  10290. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  10291. }
  10292. #endif
  10293. #ifndef _WIN32
  10294. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  10295. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  10296. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  10297. TEST(MmapTest, FailedMappingIsNotOpen) {
  10298. const char *path = "./mmap_failed_mapping_test_dir";
  10299. ASSERT_EQ(0, ::mkdir(path, 0755));
  10300. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10301. detail::mmap m(path);
  10302. EXPECT_FALSE(m.is_open());
  10303. EXPECT_EQ(0U, m.size());
  10304. EXPECT_NE(static_cast<const void *>(m.data()),
  10305. static_cast<const void *>(MAP_FAILED));
  10306. }
  10307. #endif
  10308. TEST(KeepAliveTest, ReadTimeout) {
  10309. Server svr;
  10310. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10311. std::this_thread::sleep_for(std::chrono::seconds(2));
  10312. res.set_content("a", "text/plain");
  10313. });
  10314. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10315. res.set_content("b", "text/plain");
  10316. });
  10317. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10318. auto se = detail::scope_exit([&] {
  10319. svr.stop();
  10320. listen_thread.join();
  10321. ASSERT_FALSE(svr.is_running());
  10322. });
  10323. svr.wait_until_ready();
  10324. Client cli("localhost", PORT);
  10325. cli.set_keep_alive(true);
  10326. cli.set_read_timeout(std::chrono::seconds(1));
  10327. auto resa = cli.Get("/a");
  10328. ASSERT_FALSE(resa);
  10329. EXPECT_EQ(Error::Read, resa.error());
  10330. auto resb = cli.Get("/b");
  10331. ASSERT_TRUE(resb);
  10332. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10333. EXPECT_EQ("b", resb->body);
  10334. }
  10335. TEST(KeepAliveTest, MaxCount) {
  10336. size_t keep_alive_max_count = 3;
  10337. Server svr;
  10338. svr.set_keep_alive_max_count(keep_alive_max_count);
  10339. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10340. res.set_content("Hello World!", "text/plain");
  10341. });
  10342. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10343. auto se = detail::scope_exit([&] {
  10344. svr.stop();
  10345. listen_thread.join();
  10346. ASSERT_FALSE(svr.is_running());
  10347. });
  10348. svr.wait_until_ready();
  10349. Client cli(HOST, PORT);
  10350. cli.set_keep_alive(true);
  10351. for (size_t i = 0; i < 5; i++) {
  10352. auto result = cli.Get("/hi");
  10353. ASSERT_TRUE(result);
  10354. EXPECT_EQ(StatusCode::OK_200, result->status);
  10355. if (i == keep_alive_max_count - 1) {
  10356. EXPECT_EQ("close", result->get_header_value("Connection"));
  10357. } else {
  10358. EXPECT_FALSE(result->has_header("Connection"));
  10359. }
  10360. }
  10361. }
  10362. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10363. // can pull the next one into the server's buffer. The server must serve it
  10364. // without waiting for the socket to become readable again. The keep-alive
  10365. // timeout outlasts the client's read timeout, so a request left waiting for it
  10366. // shows up as a missing response.
  10367. static void serve_pipelining_routes(Server &svr,
  10368. const std::function<void(int)> &client) {
  10369. svr.set_keep_alive_timeout(5);
  10370. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10371. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10372. });
  10373. svr.Post("/echo", [](const Request &req, Response &res) {
  10374. res.set_content("echo " + req.body, "text/plain");
  10375. });
  10376. auto port = svr.bind_to_any_port(HOST);
  10377. thread t = thread([&] { svr.listen_after_bind(); });
  10378. auto se = detail::scope_exit([&] {
  10379. svr.stop();
  10380. t.join();
  10381. });
  10382. svr.wait_until_ready();
  10383. client(port);
  10384. }
  10385. static std::string
  10386. send_pipelined_requests(const std::vector<std::string> &parts) {
  10387. Server svr;
  10388. std::string res;
  10389. serve_pipelining_routes(svr, [&](int port) {
  10390. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10391. });
  10392. return res;
  10393. }
  10394. static void expect_in_order(const std::string &res,
  10395. const std::vector<std::string> &bodies) {
  10396. size_t pos = 0;
  10397. for (const auto &body : bodies) {
  10398. pos = res.find(body, pos);
  10399. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10400. pos += body.size();
  10401. }
  10402. }
  10403. TEST(KeepAliveTest, PipelinedRequests) {
  10404. auto res = send_pipelined_requests(
  10405. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10406. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10407. "Content-Length: 4\r\n\r\nbody"
  10408. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10409. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10410. }
  10411. // The second request starts in the server's buffer and ends on the socket.
  10412. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10413. auto res =
  10414. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10415. "GET /hi/2 HTTP/1.1\r\nHo",
  10416. "st: localhost\r\nConnection: close\r\n\r\n"});
  10417. expect_in_order(res, {"hi 1", "hi 2"});
  10418. }
  10419. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10420. // CRLF after a body does not turn into a 400 for the next request.
  10421. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10422. auto res = send_pipelined_requests(
  10423. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10424. "Content-Length: 4\r\n\r\nbody\r\n"
  10425. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10426. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10427. expect_in_order(res, {"echo body", "hi 2"});
  10428. }
  10429. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10430. // must not be served as the next request.
  10431. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10432. auto res = send_pipelined_requests(
  10433. {"INVALID REQUEST LINE\r\n\r\n"
  10434. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10435. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10436. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10437. }
  10438. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10439. // Over TLS, the next request is held by the TLS library as already decrypted
  10440. // data rather than on the socket.
  10441. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10443. std::string res;
  10444. serve_pipelining_routes(svr, [&](int port) {
  10445. // One part, so all three requests arrive in one TLS record
  10446. EXPECT_TRUE(send_ssl_request_in_parts(
  10447. 2,
  10448. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10449. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10450. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10451. &res, port));
  10452. });
  10453. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10454. }
  10455. #endif
  10456. TEST(KeepAliveTest, Issue1041) {
  10457. Server svr;
  10458. svr.set_keep_alive_timeout(3);
  10459. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10460. res.set_content("Hello World!", "text/plain");
  10461. });
  10462. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10463. auto se = detail::scope_exit([&] {
  10464. svr.stop();
  10465. listen_thread.join();
  10466. ASSERT_FALSE(svr.is_running());
  10467. });
  10468. svr.wait_until_ready();
  10469. Client cli(HOST, PORT);
  10470. cli.set_keep_alive(true);
  10471. auto result = cli.Get("/hi");
  10472. ASSERT_TRUE(result);
  10473. EXPECT_EQ(StatusCode::OK_200, result->status);
  10474. std::this_thread::sleep_for(std::chrono::seconds(5));
  10475. result = cli.Get("/hi");
  10476. ASSERT_TRUE(result);
  10477. EXPECT_EQ(StatusCode::OK_200, result->status);
  10478. }
  10479. TEST(KeepAliveTest, Issue1959) {
  10480. Server svr;
  10481. svr.set_keep_alive_timeout(5);
  10482. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10483. res.set_content("a", "text/plain");
  10484. });
  10485. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10486. auto se = detail::scope_exit([&] {
  10487. if (!svr.is_running()) return;
  10488. svr.stop();
  10489. listen_thread.join();
  10490. ASSERT_FALSE(svr.is_running());
  10491. });
  10492. svr.wait_until_ready();
  10493. Client cli("localhost", PORT);
  10494. cli.set_keep_alive(true);
  10495. using namespace std::chrono;
  10496. auto start = steady_clock::now();
  10497. cli.Get("/a");
  10498. svr.stop();
  10499. listen_thread.join();
  10500. auto end = steady_clock::now();
  10501. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10502. EXPECT_LT(elapsed, 5000);
  10503. }
  10504. #ifdef CPPHTTPLIB_SSL_ENABLED
  10505. TEST(KeepAliveTest, SSLClientReconnection) {
  10506. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10507. ASSERT_TRUE(svr.is_valid());
  10508. svr.set_keep_alive_timeout(1);
  10509. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10510. res.set_content("Hello World!", "text/plain");
  10511. });
  10512. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10513. auto se = detail::scope_exit([&] {
  10514. svr.stop();
  10515. listen_thread.join();
  10516. ASSERT_FALSE(svr.is_running());
  10517. });
  10518. svr.wait_until_ready();
  10519. SSLClient cli(HOST, PORT);
  10520. cli.enable_server_certificate_verification(false);
  10521. cli.set_keep_alive(true);
  10522. auto result = cli.Get("/hi");
  10523. ASSERT_TRUE(result);
  10524. EXPECT_EQ(StatusCode::OK_200, result->status);
  10525. result = cli.Get("/hi");
  10526. ASSERT_TRUE(result);
  10527. EXPECT_EQ(StatusCode::OK_200, result->status);
  10528. std::this_thread::sleep_for(std::chrono::seconds(2));
  10529. // Recoonect
  10530. result = cli.Get("/hi");
  10531. ASSERT_TRUE(result);
  10532. EXPECT_EQ(StatusCode::OK_200, result->status);
  10533. result = cli.Get("/hi");
  10534. ASSERT_TRUE(result);
  10535. EXPECT_EQ(StatusCode::OK_200, result->status);
  10536. }
  10537. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10539. ASSERT_TRUE(svr.is_valid());
  10540. svr.set_keep_alive_timeout(1);
  10541. std::string content = "reconnect";
  10542. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10543. res.set_content("Hello World!", "text/plain");
  10544. });
  10545. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10546. auto se = detail::scope_exit([&] {
  10547. svr.stop();
  10548. listen_thread.join();
  10549. ASSERT_FALSE(svr.is_running());
  10550. });
  10551. svr.wait_until_ready();
  10552. SSLClient cli(HOST, PORT);
  10553. cli.enable_server_certificate_verification(false);
  10554. cli.set_keep_alive(true);
  10555. auto result = cli.Post(
  10556. "/hi", content.size(),
  10557. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10558. sink.write(content.c_str(), content.size());
  10559. return true;
  10560. },
  10561. "text/plain");
  10562. ASSERT_TRUE(result);
  10563. EXPECT_EQ(200, result->status);
  10564. std::this_thread::sleep_for(std::chrono::seconds(2));
  10565. // Recoonect
  10566. result = cli.Post(
  10567. "/hi", content.size(),
  10568. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10569. sink.write(content.c_str(), content.size());
  10570. return true;
  10571. },
  10572. "text/plain");
  10573. ASSERT_TRUE(result);
  10574. EXPECT_EQ(200, result->status);
  10575. result = cli.Post(
  10576. "/hi", content.size(),
  10577. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10578. sink.write(content.c_str(), content.size());
  10579. return true;
  10580. },
  10581. "text/plain");
  10582. ASSERT_TRUE(result);
  10583. EXPECT_EQ(200, result->status);
  10584. }
  10585. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10586. using namespace httplib::tls;
  10587. {
  10588. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10589. ASSERT_TRUE(svr.is_valid());
  10590. svr.Get("/sni", [&](const Request &req, Response &res) {
  10591. std::string expected = req.sni();
  10592. EXPECT_EQ(expected, req.get_param_value("expected"));
  10593. res.set_content("ok", "text/plain");
  10594. });
  10595. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10596. auto se = detail::scope_exit([&] {
  10597. svr.stop();
  10598. listen_thread.join();
  10599. ASSERT_FALSE(svr.is_running());
  10600. });
  10601. svr.wait_until_ready();
  10602. {
  10603. SSLClient cli("localhost", PORT);
  10604. cli.enable_server_certificate_verification(false);
  10605. auto res = cli.Get("/sni?expected=localhost");
  10606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10607. }
  10608. {
  10609. SSLClient cli("::1", PORT);
  10610. cli.enable_server_certificate_verification(false);
  10611. auto res = cli.Get("/sni?expected=");
  10612. // NOTE: This may fail if the server is listening on IPv4 only
  10613. // (e.g., when localhost resolves to 127.0.0.1 only)
  10614. if (res) {
  10615. EXPECT_EQ(StatusCode::OK_200, res->status);
  10616. } else {
  10617. EXPECT_EQ(Error::Connection, res.error());
  10618. }
  10619. }
  10620. }
  10621. }
  10622. #endif
  10623. TEST(ClientProblemDetectionTest, ContentProvider) {
  10624. Server svr;
  10625. size_t content_length = 1024 * 1024;
  10626. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10627. res.set_content_provider(
  10628. content_length, "text/plain",
  10629. [&](size_t offset, size_t length, DataSink &sink) {
  10630. auto out_len = std::min(length, static_cast<size_t>(1024));
  10631. std::string out(out_len, '@');
  10632. sink.write(out.data(), out_len);
  10633. return offset < 4096;
  10634. },
  10635. [](bool success) { ASSERT_FALSE(success); });
  10636. });
  10637. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10638. res.set_content_provider(
  10639. 0, "text/plain",
  10640. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10641. EXPECT_TRUE(false);
  10642. return true;
  10643. },
  10644. [](bool success) { ASSERT_FALSE(success); });
  10645. });
  10646. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10647. auto se = detail::scope_exit([&] {
  10648. svr.stop();
  10649. listen_thread.join();
  10650. ASSERT_FALSE(svr.is_running());
  10651. });
  10652. svr.wait_until_ready();
  10653. Client cli("localhost", PORT);
  10654. {
  10655. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10656. size_t /*data_length*/) { return false; });
  10657. ASSERT_FALSE(res);
  10658. }
  10659. {
  10660. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10661. size_t /*data_length*/) { return false; });
  10662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10663. }
  10664. }
  10665. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10666. // A provider that reports success without writing anything and without
  10667. // calling done() used to be handed the same offset and length again on every
  10668. // pass, so it spun for as long as the peer stayed connected.
  10669. Server svr;
  10670. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10671. res.set_content("ok", "text/plain");
  10672. });
  10673. auto port = svr.bind_to_any_port(HOST);
  10674. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10675. auto se = detail::scope_exit([&] {
  10676. svr.stop();
  10677. listen_thread.join();
  10678. ASSERT_FALSE(svr.is_running());
  10679. });
  10680. svr.wait_until_ready();
  10681. std::atomic<int> call_count{0};
  10682. Client cli(HOST, port);
  10683. auto res = cli.Post(
  10684. "/", 1024,
  10685. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10686. // Give up after enough passes to show the spin, so that losing the
  10687. // check below fails this test instead of hanging it.
  10688. return ++call_count < 100;
  10689. },
  10690. "text/plain");
  10691. ASSERT_FALSE(res);
  10692. EXPECT_EQ(Error::Write, res.error());
  10693. EXPECT_EQ(1, call_count.load());
  10694. }
  10695. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10696. // A writer only has to assign `write`. The other three used to be left as
  10697. // empty std::functions, so a provider calling one threw
  10698. // std::bad_function_call out of the thread running it and took the whole
  10699. // process down.
  10700. DataSink sink;
  10701. std::string written;
  10702. sink.write = [&](const char *data, size_t data_len) {
  10703. written.append(data, data_len);
  10704. return true;
  10705. };
  10706. EXPECT_TRUE(sink.is_writable());
  10707. sink.done();
  10708. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10709. EXPECT_TRUE(written.empty());
  10710. }
  10711. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10712. // A sink that cannot carry trailers still has to finish.
  10713. DataSink sink;
  10714. auto done_count = 0;
  10715. sink.done = [&]() { done_count++; };
  10716. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10717. EXPECT_EQ(1, done_count);
  10718. }
  10719. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10720. Server svr;
  10721. const std::string body(4096, 'x');
  10722. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10723. res.set_content_provider(body.size(), "text/plain",
  10724. [&](size_t offset, size_t length, DataSink &sink) {
  10725. sink.write(body.data() + offset, length);
  10726. sink.done();
  10727. return true;
  10728. });
  10729. });
  10730. auto port = svr.bind_to_any_port(HOST);
  10731. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10732. auto se = detail::scope_exit([&] {
  10733. svr.stop();
  10734. listen_thread.join();
  10735. ASSERT_FALSE(svr.is_running());
  10736. });
  10737. svr.wait_until_ready();
  10738. Client cli(HOST, port);
  10739. auto res = cli.Get("/");
  10740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10741. EXPECT_EQ(StatusCode::OK_200, res->status);
  10742. EXPECT_EQ(body, res->body);
  10743. }
  10744. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10745. Server svr;
  10746. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10747. res.set_content_provider(
  10748. 1024, "text/plain",
  10749. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10750. sink.write("hello", 5);
  10751. sink.done(); // short of the 1024 bytes the response promised
  10752. return true;
  10753. });
  10754. });
  10755. auto port = svr.bind_to_any_port(HOST);
  10756. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10757. auto se = detail::scope_exit([&] {
  10758. svr.stop();
  10759. listen_thread.join();
  10760. ASSERT_FALSE(svr.is_running());
  10761. });
  10762. svr.wait_until_ready();
  10763. Client cli(HOST, port);
  10764. cli.set_read_timeout(5, 0);
  10765. // The response is short of its Content-Length, so the client cannot read a
  10766. // complete body. What matters is that this returns at all: a no-op done()
  10767. // would leave the writer looping over a provider that never makes progress.
  10768. auto res = cli.Get("/");
  10769. EXPECT_FALSE(res);
  10770. }
  10771. // Read as the next response by a peer that sees it after a framed body.
  10772. static const std::string smuggled_response =
  10773. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  10774. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  10775. Server svr;
  10776. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10777. res.set_content_provider(
  10778. 5, "text/plain",
  10779. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10780. auto data = "AAAAA" + smuggled_response;
  10781. sink.write(data.data(), data.size());
  10782. return true;
  10783. });
  10784. });
  10785. thread t = thread([&] { svr.listen(HOST, PORT); });
  10786. auto se = detail::scope_exit([&] {
  10787. svr.stop();
  10788. t.join();
  10789. ASSERT_FALSE(svr.is_running());
  10790. });
  10791. svr.wait_until_ready();
  10792. std::string resp;
  10793. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10794. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  10795. resp.clear();
  10796. ASSERT_TRUE(send_request(
  10797. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  10798. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  10799. }
  10800. TEST(NoContentTest, BodyIsNotSent) {
  10801. Server svr;
  10802. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  10803. res.status = StatusCode::NoContent_204;
  10804. res.set_content(smuggled_response, "text/plain");
  10805. });
  10806. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  10807. res.status = StatusCode::NotModified_304;
  10808. res.set_chunked_content_provider(
  10809. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  10810. sink.write(smuggled_response.data(), smuggled_response.size());
  10811. sink.done();
  10812. return true;
  10813. });
  10814. });
  10815. thread t = thread([&] { svr.listen(HOST, PORT); });
  10816. auto se = detail::scope_exit([&] {
  10817. svr.stop();
  10818. t.join();
  10819. ASSERT_FALSE(svr.is_running());
  10820. });
  10821. svr.wait_until_ready();
  10822. for (auto path : {"/204", "/304"}) {
  10823. std::string resp;
  10824. ASSERT_TRUE(send_request(
  10825. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10826. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  10827. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  10828. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  10829. }
  10830. }
  10831. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  10832. Server svr;
  10833. std::atomic<bool> smuggled(false);
  10834. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10835. res.set_content("ok", "text/plain");
  10836. });
  10837. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  10838. smuggled = true;
  10839. });
  10840. auto port = svr.bind_to_any_port(HOST);
  10841. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  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. // What follows the body would be read as the next request.
  10849. Client cli(HOST, port);
  10850. auto res = cli.Post(
  10851. "/", 5,
  10852. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10853. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  10854. sink.write(data.data(), data.size());
  10855. return true;
  10856. },
  10857. "text/plain");
  10858. ASSERT_FALSE(res);
  10859. EXPECT_EQ(Error::Write, res.error());
  10860. EXPECT_FALSE(smuggled);
  10861. }
  10862. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10863. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10864. // The compressed path builds the whole body before connecting, so this
  10865. // fails client-side and never reaches a server.
  10866. Client cli(HOST, PORT);
  10867. cli.set_compress(true);
  10868. auto res = cli.Post(
  10869. "/", 1024,
  10870. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10871. sink.write("hello", 5);
  10872. sink.done(); // short of the 1024 bytes the request announced
  10873. return true;
  10874. },
  10875. "text/plain");
  10876. ASSERT_FALSE(res);
  10877. EXPECT_EQ(Error::Write, res.error());
  10878. }
  10879. #endif
  10880. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10881. Server svr;
  10882. svr.set_error_handler([](Request const &, Response &res) -> void {
  10883. res.set_chunked_content_provider(
  10884. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10885. sink.os << "hello";
  10886. sink.os << "world";
  10887. sink.done();
  10888. return true;
  10889. });
  10890. });
  10891. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", 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. Client cli("localhost", PORT);
  10899. auto res = cli.Get("/");
  10900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10901. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10902. EXPECT_EQ("helloworld", res->body);
  10903. }
  10904. // A body set after a content provider must replace it, not be sent through it.
  10905. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10906. Server svr;
  10907. svr.set_mount_point("/", "./www");
  10908. svr.set_file_request_handler([](const Request &req, Response &res) {
  10909. if (req.path == "/dir/test.html") {
  10910. res.status = StatusCode::Forbidden_403;
  10911. res.set_content(std::string(5000, 'D'), "text/plain");
  10912. } else if (req.path == "/file") {
  10913. res.status = StatusCode::Forbidden_403;
  10914. res.body = "Denied";
  10915. }
  10916. });
  10917. auto port = svr.bind_to_any_port(HOST);
  10918. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10919. auto se = detail::scope_exit([&] {
  10920. svr.stop();
  10921. t.join();
  10922. ASSERT_FALSE(svr.is_running());
  10923. });
  10924. svr.wait_until_ready();
  10925. Client cli(HOST, port);
  10926. {
  10927. auto res = cli.Get("/dir/test.html");
  10928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10929. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10930. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10931. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10932. }
  10933. {
  10934. auto res = cli.Get("/file");
  10935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10936. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10937. EXPECT_EQ("Denied", res->body);
  10938. }
  10939. {
  10940. auto res = cli.Get("/dir/index.html");
  10941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10942. EXPECT_EQ(StatusCode::OK_200, res->status);
  10943. EXPECT_EQ(0U, res->body.find("<html>"));
  10944. }
  10945. }
  10946. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10947. Server svr;
  10948. std::vector<bool> released;
  10949. std::mutex released_mutex;
  10950. auto releaser = [&](bool success) {
  10951. std::lock_guard<std::mutex> guard(released_mutex);
  10952. released.push_back(success);
  10953. };
  10954. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10955. return sink.write(&"hello"[offset], length);
  10956. };
  10957. svr.Get("/sized", [&](const Request &, Response &res) {
  10958. res.status = StatusCode::NotFound_404;
  10959. res.set_content_provider(5, "text/plain", provider, releaser);
  10960. });
  10961. svr.Get("/chunked", [&](const Request &, Response &res) {
  10962. res.status = StatusCode::ServiceUnavailable_503;
  10963. res.set_chunked_content_provider(
  10964. "text/plain",
  10965. [](size_t, DataSink &sink) {
  10966. sink.os << "chunk";
  10967. sink.done();
  10968. return true;
  10969. },
  10970. releaser);
  10971. });
  10972. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10973. res.set_content_provider(5, "text/plain", provider, releaser);
  10974. throw std::runtime_error("after the provider");
  10975. });
  10976. svr.set_error_handler([](const Request &req, Response &res) {
  10977. // Leave the exception handler's content to it.
  10978. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10979. res.set_content(std::string(1000, 'E'), "text/html");
  10980. return Server::HandlerResponse::Handled;
  10981. });
  10982. svr.set_exception_handler(
  10983. [](const Request &, Response &res, std::exception_ptr) {
  10984. res.status = StatusCode::InternalServerError_500;
  10985. res.set_content(std::string(1000, 'X'), "text/html");
  10986. });
  10987. auto port = svr.bind_to_any_port(HOST);
  10988. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10989. auto se = detail::scope_exit([&] {
  10990. svr.stop();
  10991. t.join();
  10992. ASSERT_FALSE(svr.is_running());
  10993. });
  10994. svr.wait_until_ready();
  10995. Client cli(HOST, port);
  10996. {
  10997. auto res = cli.Get("/sized");
  10998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10999. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11000. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11001. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11002. }
  11003. {
  11004. auto res = cli.Get("/chunked");
  11005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11006. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11007. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11008. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11009. }
  11010. {
  11011. auto res = cli.Get("/throw");
  11012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11013. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11014. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11015. }
  11016. std::lock_guard<std::mutex> guard(released_mutex);
  11017. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11018. }
  11019. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11020. Server svr;
  11021. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11022. return sink.write(&"abc"[offset], length);
  11023. };
  11024. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11025. res.set_file_content("./www/dir/test.html");
  11026. res.set_content("body", "text/plain");
  11027. });
  11028. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11029. res.set_content(std::string(100, 'B'), "text/plain");
  11030. res.set_file_content("./www/dir/test.html");
  11031. });
  11032. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11033. res.set_content(std::string(100, 'B'), "text/plain");
  11034. res.set_content_provider(3, "text/plain", abc);
  11035. });
  11036. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11037. res.set_content_provider(3, "text/plain", abc);
  11038. res.set_content(std::string(100, 'B'), "text/plain");
  11039. });
  11040. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11041. res.set_content_provider(3, "text/plain", abc);
  11042. res.body = "direct";
  11043. });
  11044. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11045. res.set_file_content("./www/dir/test.html");
  11046. res.body = "direct";
  11047. });
  11048. auto port = svr.bind_to_any_port(HOST);
  11049. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11050. auto se = detail::scope_exit([&] {
  11051. svr.stop();
  11052. t.join();
  11053. ASSERT_FALSE(svr.is_running());
  11054. });
  11055. svr.wait_until_ready();
  11056. Client cli(HOST, port);
  11057. auto expect_body = [&](const char *path, const std::string &body) {
  11058. // Uncompressed, so Content-Length can be compared with the body.
  11059. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11060. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11061. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11062. EXPECT_EQ(body, res->body) << path;
  11063. EXPECT_EQ(std::to_string(body.size()),
  11064. res->get_header_value("Content-Length"))
  11065. << path;
  11066. };
  11067. expect_body("/file-then-body", "body");
  11068. expect_body("/body-then-file", "test.html");
  11069. expect_body("/body-then-provider", "abc");
  11070. expect_body("/provider-then-body", std::string(100, 'B'));
  11071. expect_body("/provider-then-direct-body", "direct");
  11072. expect_body("/file-then-direct-body", "direct");
  11073. // Ranges are checked against the body, not the dropped provider.
  11074. {
  11075. auto res = cli.Get("/provider-then-direct-body",
  11076. Headers{{make_range_header({{1, 2}})}});
  11077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11078. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11079. EXPECT_EQ("ir", res->body);
  11080. }
  11081. {
  11082. auto res = cli.Get("/file-then-direct-body",
  11083. Headers{{make_range_header({{7, 8}})}});
  11084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11085. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11086. }
  11087. }
  11088. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11089. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11090. const char *path = "./truncated_while_served.txt";
  11091. const size_t size = 32 * 1024 * 1024;
  11092. {
  11093. std::ofstream f(path, std::ios::binary);
  11094. f << std::string(size, 'x');
  11095. }
  11096. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11097. // Over TLS, where the bytes are encrypted in this process rather than
  11098. // copied by send().
  11099. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11100. svr.Get("/file", [&](const Request &, Response &res) {
  11101. res.set_file_content(path, "text/plain");
  11102. });
  11103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11104. auto se = detail::scope_exit([&] {
  11105. svr.stop();
  11106. thread.join();
  11107. ASSERT_FALSE(svr.is_running());
  11108. });
  11109. svr.wait_until_ready();
  11110. // The file shrinks once the first bytes are in, as a rewrite in place
  11111. // would, and reading the mapping past its new end used to raise SIGBUS.
  11112. SSLClient cli(HOST, PORT);
  11113. cli.enable_server_certificate_verification(false);
  11114. size_t received = 0;
  11115. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11116. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11117. received += len;
  11118. return true;
  11119. });
  11120. EXPECT_FALSE(res);
  11121. EXPECT_LT(received, size);
  11122. }
  11123. #endif
  11124. // Forward declaration (see the base64_encode note).
  11125. namespace httplib {
  11126. namespace detail {
  11127. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11128. const std::string &content_type,
  11129. EncodingType encoding);
  11130. } // namespace detail
  11131. } // namespace httplib
  11132. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11133. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11134. ASSERT_TRUE(mm->is_open());
  11135. Response res;
  11136. detail::set_file_content_provider(res, mm, "text/html",
  11137. detail::EncodingType::None);
  11138. std::string out;
  11139. DataSink sink;
  11140. sink.write = [&](const char *d, size_t l) {
  11141. out.append(d, l);
  11142. return true;
  11143. };
  11144. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11145. EXPECT_EQ("test.html", out);
  11146. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11147. EXPECT_EQ("test.html", out);
  11148. }
  11149. TEST(LongPollingTest, ClientCloseDetection) {
  11150. Server svr;
  11151. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11152. res.set_chunked_content_provider(
  11153. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11154. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11155. sink.os << "hello";
  11156. auto count = 10;
  11157. while (count > 0 && sink.is_writable()) {
  11158. this_thread::sleep_for(chrono::milliseconds(10));
  11159. count--;
  11160. }
  11161. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11162. return true;
  11163. });
  11164. });
  11165. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11166. auto se = detail::scope_exit([&] {
  11167. svr.stop();
  11168. listen_thread.join();
  11169. ASSERT_FALSE(svr.is_running());
  11170. });
  11171. svr.wait_until_ready();
  11172. Client cli("localhost", PORT);
  11173. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11174. EXPECT_EQ("hello", string(data, data_length));
  11175. return false; // close the socket immediately.
  11176. });
  11177. ASSERT_FALSE(res);
  11178. }
  11179. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11180. Server svr;
  11181. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11182. res.set_chunked_content_provider(
  11183. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11184. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11185. sink.os << "hello";
  11186. EXPECT_TRUE(sink.os.good());
  11187. // Wait for the client to close the connection
  11188. auto count = 10;
  11189. while (count > 0 && sink.is_writable()) {
  11190. this_thread::sleep_for(chrono::milliseconds(10));
  11191. count--;
  11192. }
  11193. // After client disconnect, write repeatedly until the socket
  11194. // write actually fails (small writes may be absorbed by the
  11195. // kernel buffer)
  11196. std::string chunk(1024, 'x');
  11197. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11198. sink.os << chunk;
  11199. }
  11200. EXPECT_TRUE(sink.os.fail());
  11201. return true;
  11202. });
  11203. });
  11204. auto port = svr.bind_to_any_port("localhost");
  11205. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11206. auto se = detail::scope_exit([&] {
  11207. svr.stop();
  11208. listen_thread.join();
  11209. ASSERT_FALSE(svr.is_running());
  11210. });
  11211. svr.wait_until_ready();
  11212. Client cli("localhost", port);
  11213. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11214. EXPECT_EQ("hello", string(data, data_length));
  11215. return false; // close the socket immediately.
  11216. });
  11217. ASSERT_FALSE(res);
  11218. }
  11219. TEST(GetWithParametersTest, GetWithParameters) {
  11220. Server svr;
  11221. svr.Get("/", [&](const Request &req, Response &) {
  11222. EXPECT_EQ("world", req.get_param_value("hello"));
  11223. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11224. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11225. });
  11226. svr.Get("/params", [&](const Request &req, Response &) {
  11227. EXPECT_EQ("world", req.get_param_value("hello"));
  11228. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11229. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11230. });
  11231. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11232. EXPECT_EQ("resource-id", req.matches[1]);
  11233. EXPECT_EQ("foo", req.get_param_value("param1"));
  11234. EXPECT_EQ("bar", req.get_param_value("param2"));
  11235. });
  11236. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11237. EXPECT_EQ("user-id", req.path_params.at("id"));
  11238. EXPECT_EQ("foo", req.get_param_value("param1"));
  11239. EXPECT_EQ("bar", req.get_param_value("param2"));
  11240. });
  11241. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11242. auto se = detail::scope_exit([&] {
  11243. svr.stop();
  11244. listen_thread.join();
  11245. ASSERT_FALSE(svr.is_running());
  11246. });
  11247. svr.wait_until_ready();
  11248. {
  11249. Client cli(HOST, PORT);
  11250. Params params;
  11251. params.emplace("hello", "world");
  11252. params.emplace("hello2", "world2");
  11253. params.emplace("hello3", "world3");
  11254. auto res = cli.Get("/", params, Headers{});
  11255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11256. EXPECT_EQ(StatusCode::OK_200, res->status);
  11257. }
  11258. {
  11259. Client cli(HOST, PORT);
  11260. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11262. EXPECT_EQ(StatusCode::OK_200, res->status);
  11263. }
  11264. {
  11265. Client cli(HOST, PORT);
  11266. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11268. EXPECT_EQ(StatusCode::OK_200, res->status);
  11269. }
  11270. {
  11271. Client cli(HOST, PORT);
  11272. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11274. EXPECT_EQ(StatusCode::OK_200, res->status);
  11275. }
  11276. }
  11277. TEST(GetWithParametersTest, GetWithParameters2) {
  11278. Server svr;
  11279. svr.Get("/", [&](const Request &req, Response &res) {
  11280. auto text = req.get_param_value("hello");
  11281. res.set_content(text, "text/plain");
  11282. });
  11283. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11284. auto se = detail::scope_exit([&] {
  11285. svr.stop();
  11286. listen_thread.join();
  11287. ASSERT_FALSE(svr.is_running());
  11288. });
  11289. svr.wait_until_ready();
  11290. Client cli("localhost", PORT);
  11291. Params params;
  11292. params.emplace("hello", "world");
  11293. std::string body;
  11294. auto res = cli.Get("/", params, Headers{},
  11295. [&](const char *data, size_t data_length) {
  11296. body.append(data, data_length);
  11297. return true;
  11298. });
  11299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11300. EXPECT_EQ(StatusCode::OK_200, res->status);
  11301. EXPECT_EQ("world", body);
  11302. }
  11303. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11304. Server svr;
  11305. svr.Get("/search", [&](const Request &req, Response &res) {
  11306. auto q = req.get_param_value("q");
  11307. res.set_content(q, "text/plain");
  11308. });
  11309. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11310. auto se = detail::scope_exit([&] {
  11311. svr.stop();
  11312. listen_thread.join();
  11313. ASSERT_FALSE(svr.is_running());
  11314. });
  11315. svr.wait_until_ready();
  11316. Client cli("localhost", PORT);
  11317. // Verify that Get(path, params) works without requiring Headers argument
  11318. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11320. EXPECT_EQ(StatusCode::OK_200, res->status);
  11321. EXPECT_EQ("cpp-httplib", res->body);
  11322. }
  11323. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11324. auto host = "httpbingo.org";
  11325. auto path = std::string{"/range/32"};
  11326. #ifdef CPPHTTPLIB_SSL_ENABLED
  11327. SSLClient cli(host);
  11328. #else
  11329. Client cli(host);
  11330. #endif
  11331. cli.set_default_headers({make_range_header({{1, 10}})});
  11332. cli.set_connection_timeout(5);
  11333. {
  11334. auto res = cli.Get(path);
  11335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11336. EXPECT_EQ("bcdefghijk", res->body);
  11337. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11338. }
  11339. {
  11340. auto res = cli.Get(path);
  11341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11342. EXPECT_EQ("bcdefghijk", res->body);
  11343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11344. }
  11345. }
  11346. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11347. Server svr;
  11348. svr.set_default_headers({{"Hello", "World"}});
  11349. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11350. res.set_content("ok", "text/plain");
  11351. });
  11352. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11353. auto se = detail::scope_exit([&] {
  11354. svr.stop();
  11355. listen_thread.join();
  11356. ASSERT_FALSE(svr.is_running());
  11357. });
  11358. svr.wait_until_ready();
  11359. Client cli("localhost", PORT);
  11360. auto res = cli.Get("/");
  11361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11362. EXPECT_EQ(StatusCode::OK_200, res->status);
  11363. EXPECT_EQ("ok", res->body);
  11364. EXPECT_EQ("World", res->get_header_value("Hello"));
  11365. }
  11366. #ifdef CPPHTTPLIB_SSL_ENABLED
  11367. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11368. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11369. ASSERT_TRUE(svr.is_valid());
  11370. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11371. std::this_thread::sleep_for(std::chrono::seconds(2));
  11372. res.set_content("a", "text/plain");
  11373. });
  11374. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11375. res.set_content("b", "text/plain");
  11376. });
  11377. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11378. auto se = detail::scope_exit([&] {
  11379. svr.stop();
  11380. listen_thread.join();
  11381. ASSERT_FALSE(svr.is_running());
  11382. });
  11383. svr.wait_until_ready();
  11384. SSLClient cli("localhost", PORT);
  11385. cli.enable_server_certificate_verification(false);
  11386. cli.set_keep_alive(true);
  11387. cli.set_read_timeout(std::chrono::seconds(1));
  11388. auto resa = cli.Get("/a");
  11389. ASSERT_TRUE(!resa);
  11390. EXPECT_EQ(Error::Read, resa.error());
  11391. auto resb = cli.Get("/b");
  11392. ASSERT_TRUE(resb);
  11393. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11394. EXPECT_EQ("b", resb->body);
  11395. }
  11396. // Closing an idle keep-alive connection sends close_notify and returns. The
  11397. // server must not wait for the client's close_notify: an idle client never
  11398. // sends one, so the worker would be held until the read timeout expires, and
  11399. // stop() would wait for it.
  11400. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11402. ASSERT_TRUE(svr.is_valid());
  11403. svr.set_keep_alive_timeout(1);
  11404. svr.set_read_timeout(10, 0);
  11405. svr.Get("/", [](const Request &, Response &res) {
  11406. res.set_content("ok", "text/plain");
  11407. });
  11408. auto port = svr.bind_to_any_port(HOST);
  11409. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11410. auto se = detail::scope_exit([&] {
  11411. if (listen_thread.joinable()) {
  11412. svr.stop();
  11413. listen_thread.join();
  11414. }
  11415. });
  11416. svr.wait_until_ready();
  11417. SSLClient cli(HOST, port);
  11418. cli.enable_server_certificate_verification(false);
  11419. cli.set_keep_alive(true);
  11420. auto res = cli.Get("/");
  11421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11422. EXPECT_EQ(StatusCode::OK_200, res->status);
  11423. // Stay idle past the keep-alive timeout so the server closes the connection.
  11424. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11425. auto start = std::chrono::steady_clock::now();
  11426. svr.stop();
  11427. listen_thread.join();
  11428. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11429. std::chrono::steady_clock::now() - start)
  11430. .count();
  11431. EXPECT_LT(elapsed, 3000);
  11432. }
  11433. #endif
  11434. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11435. protected:
  11436. ServerTestWithAI_PASSIVE()
  11437. : cli_(HOST, PORT)
  11438. #ifdef CPPHTTPLIB_SSL_ENABLED
  11439. ,
  11440. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11441. #endif
  11442. {
  11443. #ifdef CPPHTTPLIB_SSL_ENABLED
  11444. cli_.enable_server_certificate_verification(false);
  11445. #endif
  11446. }
  11447. virtual void SetUp() {
  11448. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11449. res.set_content("Hello World!", "text/plain");
  11450. });
  11451. t_ = thread(
  11452. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11453. svr_.wait_until_ready();
  11454. }
  11455. virtual void TearDown() {
  11456. svr_.stop();
  11457. t_.join();
  11458. }
  11459. #ifdef CPPHTTPLIB_SSL_ENABLED
  11460. SSLClient cli_;
  11461. SSLServer svr_;
  11462. #else
  11463. Client cli_;
  11464. Server svr_;
  11465. #endif
  11466. thread t_;
  11467. };
  11468. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11469. auto res = cli_.Get("/hi");
  11470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11471. EXPECT_EQ(StatusCode::OK_200, res->status);
  11472. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11473. EXPECT_EQ("Hello World!", res->body);
  11474. }
  11475. class ServerUpDownTest : public ::testing::Test {
  11476. protected:
  11477. ServerUpDownTest() : cli_(HOST, PORT) {}
  11478. virtual void SetUp() {
  11479. t_ = thread([&]() {
  11480. svr_.bind_to_any_port(HOST);
  11481. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11482. ASSERT_TRUE(svr_.listen_after_bind());
  11483. });
  11484. svr_.wait_until_ready();
  11485. }
  11486. virtual void TearDown() {
  11487. svr_.stop();
  11488. t_.join();
  11489. }
  11490. Client cli_;
  11491. Server svr_;
  11492. thread t_;
  11493. };
  11494. TEST_F(ServerUpDownTest, QuickStartStop) {
  11495. // Should not crash, especially when run with
  11496. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11497. }
  11498. class PayloadMaxLengthTest : public ::testing::Test {
  11499. protected:
  11500. PayloadMaxLengthTest()
  11501. : cli_(HOST, PORT)
  11502. #ifdef CPPHTTPLIB_SSL_ENABLED
  11503. ,
  11504. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11505. #endif
  11506. {
  11507. #ifdef CPPHTTPLIB_SSL_ENABLED
  11508. cli_.enable_server_certificate_verification(false);
  11509. #endif
  11510. }
  11511. virtual void SetUp() {
  11512. svr_.set_payload_max_length(8);
  11513. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11514. res.set_content("test", "text/plain");
  11515. });
  11516. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11517. svr_.wait_until_ready();
  11518. }
  11519. virtual void TearDown() {
  11520. svr_.stop();
  11521. t_.join();
  11522. }
  11523. #ifdef CPPHTTPLIB_SSL_ENABLED
  11524. SSLClient cli_;
  11525. SSLServer svr_;
  11526. #else
  11527. Client cli_;
  11528. Server svr_;
  11529. #endif
  11530. thread t_;
  11531. };
  11532. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11533. auto res = cli_.Post("/test", "123456789", "text/plain");
  11534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11535. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11536. res = cli_.Post("/test", "12345678", "text/plain");
  11537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11538. EXPECT_EQ(StatusCode::OK_200, res->status);
  11539. }
  11540. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11541. // Test chunked encoding with payload exceeding the 8-byte limit
  11542. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11543. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11545. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11546. }
  11547. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11548. // Test chunked encoding with payload within the 8-byte limit
  11549. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11550. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11552. EXPECT_EQ(StatusCode::OK_200, res->status);
  11553. }
  11554. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11555. // Test using send_request to send chunked data exceeding payload limit
  11556. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11557. "Host: " +
  11558. std::string(HOST) + ":" + std::to_string(PORT) +
  11559. "\r\n"
  11560. "Transfer-Encoding: chunked\r\n"
  11561. "Connection: close\r\n"
  11562. "\r\n"
  11563. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11564. "0123456789\r\n"
  11565. "0\r\n" // End chunk
  11566. "\r\n";
  11567. std::string response;
  11568. bool result = send_request(1, chunked_request, &response);
  11569. if (!result) {
  11570. // If send_request fails, it might be because the server closed the
  11571. // connection due to payload limit enforcement, which is acceptable
  11572. SUCCEED()
  11573. << "Server rejected oversized chunked request (connection closed)";
  11574. } else {
  11575. // If we got a response, check if it's an error response or connection was
  11576. // closed early Short response length indicates connection was closed due to
  11577. // payload limit
  11578. if (response.length() <= 10) {
  11579. SUCCEED() << "Server closed connection for oversized chunked request";
  11580. } else {
  11581. // Check for error status codes
  11582. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11583. response.find("Payload Too Large") != std::string::npos ||
  11584. response.find("400") != std::string::npos);
  11585. }
  11586. }
  11587. }
  11588. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11589. // Test request without Content-Length header exceeding payload limit
  11590. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11591. "Host: " +
  11592. std::string(HOST) + ":" +
  11593. std::to_string(PORT) +
  11594. "\r\n"
  11595. "Connection: close\r\n"
  11596. "\r\n";
  11597. // Add payload exceeding the 8-byte limit
  11598. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11599. request_without_content_length += large_payload;
  11600. std::string response;
  11601. bool result = send_request(1, request_without_content_length, &response);
  11602. if (!result) {
  11603. // If send_request fails, server likely closed connection due to payload
  11604. // limit
  11605. SUCCEED() << "Server rejected oversized request without Content-Length "
  11606. "(connection closed)";
  11607. } else {
  11608. // Check if server responded with error or closed connection early
  11609. if (response.length() <= 10) {
  11610. SUCCEED() << "Server closed connection for oversized request without "
  11611. "Content-Length";
  11612. } else {
  11613. // Check for error status codes
  11614. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11615. response.find("Payload Too Large") != std::string::npos ||
  11616. response.find("400") != std::string::npos);
  11617. }
  11618. }
  11619. }
  11620. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11621. // Test request without Content-Length header within payload limit
  11622. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11623. "Host: " +
  11624. std::string(HOST) + ":" +
  11625. std::to_string(PORT) +
  11626. "\r\n"
  11627. "Connection: close\r\n"
  11628. "\r\n";
  11629. // Add payload within the 8-byte limit
  11630. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11631. request_without_content_length += small_payload;
  11632. std::string response;
  11633. bool result = send_request(1, request_without_content_length, &response);
  11634. // For requests without Content-Length, the server may have different behavior
  11635. // The key is that it should not reject due to payload limit for small
  11636. // payloads
  11637. if (result) {
  11638. // Check for any HTTP response (success or error, but not connection closed)
  11639. if (response.length() > 10) {
  11640. SUCCEED()
  11641. << "Server processed request without Content-Length within limit";
  11642. } else {
  11643. // Short response might indicate connection closed, which is acceptable
  11644. SUCCEED() << "Server closed connection for request without "
  11645. "Content-Length (acceptable behavior)";
  11646. }
  11647. } else {
  11648. // Connection failure might be due to protocol requirements
  11649. SUCCEED() << "Connection issue with request without Content-Length "
  11650. "(environment-specific)";
  11651. }
  11652. }
  11653. class LargePayloadMaxLengthTest : public ::testing::Test {
  11654. protected:
  11655. LargePayloadMaxLengthTest()
  11656. : cli_(HOST, PORT)
  11657. #ifdef CPPHTTPLIB_SSL_ENABLED
  11658. ,
  11659. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11660. #endif
  11661. {
  11662. #ifdef CPPHTTPLIB_SSL_ENABLED
  11663. cli_.enable_server_certificate_verification(false);
  11664. #endif
  11665. }
  11666. virtual void SetUp() {
  11667. // Set 10MB payload limit
  11668. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11669. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11670. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11671. res.set_content("Large payload test", "text/plain");
  11672. });
  11673. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11674. svr_.wait_until_ready();
  11675. }
  11676. virtual void TearDown() {
  11677. svr_.stop();
  11678. t_.join();
  11679. }
  11680. #ifdef CPPHTTPLIB_SSL_ENABLED
  11681. SSLClient cli_;
  11682. SSLServer svr_;
  11683. #else
  11684. Client cli_;
  11685. Server svr_;
  11686. #endif
  11687. thread t_;
  11688. };
  11689. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11690. // Test chunked encoding with payload within 10MB limit
  11691. std::string medium_payload(5 * 1024 * 1024,
  11692. 'A'); // 5MB payload, within 10MB limit
  11693. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11695. EXPECT_EQ(StatusCode::OK_200, res->status);
  11696. }
  11697. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11698. // Test chunked encoding with payload exceeding 10MB limit
  11699. std::string large_payload(12 * 1024 * 1024,
  11700. 'B'); // 12MB payload, exceeds 10MB limit
  11701. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11702. // Server may either return 413 or close the connection
  11703. if (res) {
  11704. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11705. } else {
  11706. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11707. }
  11708. }
  11709. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11710. // Test request without Content-Length header within 10MB limit
  11711. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11712. "Host: " +
  11713. std::string(HOST) + ":" +
  11714. std::to_string(PORT) +
  11715. "\r\n"
  11716. "Connection: close\r\n"
  11717. "\r\n";
  11718. // Add 1MB payload (within 10MB limit)
  11719. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11720. request_without_content_length += medium_payload;
  11721. std::string response;
  11722. bool result = send_request(5, request_without_content_length, &response);
  11723. if (result) {
  11724. // Should get a proper HTTP response for payloads within limit
  11725. if (response.length() > 10) {
  11726. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11727. "10MB limit";
  11728. } else {
  11729. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11730. "Content-Length)";
  11731. }
  11732. } else {
  11733. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11734. }
  11735. }
  11736. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11737. // Test request without Content-Length header exceeding 10MB limit
  11738. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11739. "Host: " +
  11740. std::string(HOST) + ":" +
  11741. std::to_string(PORT) +
  11742. "\r\n"
  11743. "Connection: close\r\n"
  11744. "\r\n";
  11745. // Add 12MB payload (exceeds 10MB limit)
  11746. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11747. request_without_content_length += large_payload;
  11748. std::string response;
  11749. bool result = send_request(10, request_without_content_length, &response);
  11750. if (!result) {
  11751. // Server should close connection due to payload limit
  11752. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11753. "(connection closed)";
  11754. } else {
  11755. // Check for error response
  11756. if (response.length() <= 10) {
  11757. SUCCEED()
  11758. << "Server closed connection for 12MB request exceeding 10MB limit";
  11759. } else {
  11760. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11761. response.find("Payload Too Large") != std::string::npos ||
  11762. response.find("400") != std::string::npos);
  11763. }
  11764. }
  11765. }
  11766. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11767. Server svr;
  11768. svr.Get("/", [](const Request &, Response &res) {
  11769. // Claims far more than it sends, then drops the connection.
  11770. res.set_content_provider(size_t(1) << 41, "text/plain",
  11771. [](size_t, size_t, DataSink &sink) {
  11772. sink.write("abc", 3);
  11773. return false;
  11774. });
  11775. });
  11776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11777. auto se = detail::scope_exit([&] {
  11778. svr.stop();
  11779. thread.join();
  11780. ASSERT_FALSE(svr.is_running());
  11781. });
  11782. svr.wait_until_ready();
  11783. Client cli(HOST, PORT);
  11784. cli.set_payload_max_length(0);
  11785. EXPECT_FALSE(cli.Get("/"));
  11786. }
  11787. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11788. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11789. // path.
  11790. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11791. Server svr;
  11792. const size_t LIMIT = 64 * 1024; // 64KB
  11793. svr.set_payload_max_length(LIMIT);
  11794. size_t total = 0;
  11795. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11796. const ContentReader &content_reader) {
  11797. content_reader([&](const char * /*data*/, size_t len) {
  11798. total += len;
  11799. return true;
  11800. });
  11801. res.status = 200;
  11802. res.set_content("stream_ok", "text/plain");
  11803. });
  11804. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11805. auto se = detail::scope_exit([&] {
  11806. svr.stop();
  11807. thread.join();
  11808. ASSERT_FALSE(svr.is_running());
  11809. });
  11810. svr.wait_until_ready();
  11811. // Prepare 256KB raw data and gzip-compress it
  11812. std::string raw(256 * 1024, 'A');
  11813. std::string gz;
  11814. {
  11815. z_stream zs{};
  11816. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11817. Z_DEFAULT_STRATEGY);
  11818. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11819. zs.avail_in = static_cast<uInt>(raw.size());
  11820. char outbuf[4096];
  11821. int ret;
  11822. do {
  11823. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11824. zs.avail_out = sizeof(outbuf);
  11825. ret = deflate(&zs, Z_FINISH);
  11826. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11827. } while (ret != Z_STREAM_END);
  11828. deflateEnd(&zs);
  11829. }
  11830. Client cli(HOST, PORT);
  11831. cli.set_connection_timeout(std::chrono::seconds(5));
  11832. Headers headers = {{"Content-Encoding", "gzip"}};
  11833. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11834. "application/octet-stream");
  11835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11836. // Server must reject oversized decompressed payloads with 413.
  11837. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11838. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11839. EXPECT_LE(total, LIMIT);
  11840. }
  11841. #ifndef CPPHTTPLIB_SSL_ENABLED
  11842. // For a request with neither Content-Length nor Transfer-Encoding, the
  11843. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11844. // compressed wire bytes straight to the ContentReader without ever routing
  11845. // them through the decompressor, so payload_max_length_ only bounded the
  11846. // compressed size on the wire, not the decompressed size.
  11847. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11848. Server svr;
  11849. const size_t LIMIT = 64 * 1024; // 64KB
  11850. svr.set_payload_max_length(LIMIT);
  11851. size_t total = 0;
  11852. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11853. const ContentReader &content_reader) {
  11854. content_reader([&](const char * /*data*/, size_t len) {
  11855. total += len;
  11856. return true;
  11857. });
  11858. res.status = 200;
  11859. res.set_content("stream_ok", "text/plain");
  11860. });
  11861. auto port = svr.bind_to_any_port(HOST);
  11862. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11863. auto se = detail::scope_exit([&] {
  11864. svr.stop();
  11865. thread.join();
  11866. ASSERT_FALSE(svr.is_running());
  11867. });
  11868. svr.wait_until_ready();
  11869. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11870. // StreamingGzipDecompression test above.
  11871. std::string raw(256 * 1024, 'A');
  11872. std::string gz;
  11873. {
  11874. httplib::detail::gzip_compressor compressor;
  11875. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11876. [&](const char *chunk, size_t len) {
  11877. gz.append(chunk, len);
  11878. return true;
  11879. });
  11880. ASSERT_TRUE(result);
  11881. }
  11882. // Send the gzip body over raw TCP with neither Content-Length nor
  11883. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11884. // kicks in.
  11885. std::string req = "POST /stream HTTP/1.1\r\n"
  11886. "Host: " +
  11887. std::string(HOST) + ":" + std::to_string(port) +
  11888. "\r\n"
  11889. "Content-Encoding: gzip\r\n"
  11890. "Connection: close\r\n"
  11891. "\r\n" +
  11892. gz;
  11893. std::string response;
  11894. ASSERT_TRUE(send_request(5, req, &response, port));
  11895. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11896. EXPECT_LE(total, LIMIT);
  11897. }
  11898. #endif
  11899. #endif
  11900. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11901. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11902. // the payload must be passed through untouched instead of being rejected.
  11903. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11904. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11905. Server svr;
  11906. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11907. res.set_content(body, "image/jpeg");
  11908. res.set_header("Content-Encoding", "UTF-8");
  11909. });
  11910. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11911. res.set_content(body, "image/jpeg");
  11912. res.set_header("Content-Encoding", "identity");
  11913. });
  11914. svr.Post("/echo", [](const Request &req, Response &res) {
  11915. res.set_content(req.body, "image/jpeg");
  11916. });
  11917. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11918. auto se = detail::scope_exit([&] {
  11919. svr.stop();
  11920. t.join();
  11921. ASSERT_FALSE(svr.is_running());
  11922. });
  11923. svr.wait_until_ready();
  11924. Client cli(HOST, PORT);
  11925. {
  11926. auto res = cli.Get("/image");
  11927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11928. EXPECT_EQ(StatusCode::OK_200, res->status);
  11929. EXPECT_EQ(body, res->body);
  11930. }
  11931. {
  11932. auto res = cli.Get("/identity");
  11933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11934. EXPECT_EQ(StatusCode::OK_200, res->status);
  11935. EXPECT_EQ(body, res->body);
  11936. }
  11937. {
  11938. // The same applies to a request body reaching the server.
  11939. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11940. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11942. EXPECT_EQ(StatusCode::OK_200, res->status);
  11943. EXPECT_EQ(body, res->body);
  11944. }
  11945. }
  11946. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11947. // gzip-encoded response even when the build has no zlib support.
  11948. static const char GZIPPED_HELLO_WORLD[] = {
  11949. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11950. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11951. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11952. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11953. // A content coding is a whole token, not something the field value merely
  11954. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11955. // as "fibre" look like Brotli, and turned a multi-coding value like
  11956. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11957. // it was never meant to see.
  11958. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11959. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11960. Server svr;
  11961. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11962. res.set_content(body, "image/jpeg");
  11963. res.set_header("Content-Encoding", "fibre");
  11964. });
  11965. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11966. res.set_content(body, "image/jpeg");
  11967. res.set_header("Content-Encoding", "gzip, br");
  11968. });
  11969. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11970. res.set_content(body, "image/jpeg");
  11971. res.set_header("Content-Encoding", "x-zstd-ish");
  11972. });
  11973. auto port = svr.bind_to_any_port(HOST);
  11974. thread t = thread([&]() { svr.listen_after_bind(); });
  11975. auto se = detail::scope_exit([&] {
  11976. svr.stop();
  11977. t.join();
  11978. ASSERT_FALSE(svr.is_running());
  11979. });
  11980. svr.wait_until_ready();
  11981. Client cli(HOST, port);
  11982. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11983. auto res = cli.Get(path);
  11984. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11985. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11986. // Not a coding we recognize, so the payload comes back untouched
  11987. EXPECT_EQ(body, res->body) << path;
  11988. }
  11989. }
  11990. // A content coding cpp-httplib recognizes but was not built with must be
  11991. // reported as such. Handing the still-compressed payload back to the caller
  11992. // would silently corrupt it.
  11993. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11994. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11995. Server svr;
  11996. // "image/jpeg" keeps the server from applying a content coding of its own,
  11997. // so the hand-crafted Content-Encoding below survives.
  11998. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11999. res.set_content(gzipped, "image/jpeg");
  12000. res.set_header("Content-Encoding", "gzip");
  12001. });
  12002. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12003. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12004. res.set_content(gzipped, "image/jpeg");
  12005. res.set_header("Content-Encoding", "GZIP");
  12006. });
  12007. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12008. auto se = detail::scope_exit([&] {
  12009. svr.stop();
  12010. t.join();
  12011. ASSERT_FALSE(svr.is_running());
  12012. });
  12013. svr.wait_until_ready();
  12014. Client cli(HOST, PORT);
  12015. {
  12016. auto res = cli.Get("/gzipped");
  12017. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12019. EXPECT_EQ("Hello World!", res->body);
  12020. #else
  12021. ASSERT_FALSE(res);
  12022. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12023. #endif
  12024. }
  12025. {
  12026. // open_stream() must behave the same way.
  12027. auto handle = cli.open_stream("GET", "/gzipped");
  12028. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12029. ASSERT_TRUE(handle.is_valid());
  12030. std::string received;
  12031. char buf[256];
  12032. ssize_t n;
  12033. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12034. received.append(buf, static_cast<size_t>(n));
  12035. }
  12036. EXPECT_EQ("Hello World!", received);
  12037. #else
  12038. EXPECT_FALSE(handle.is_valid());
  12039. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12040. #endif
  12041. }
  12042. {
  12043. // A differently-cased coding must not be mistaken for an unknown one, or
  12044. // the body would be handed back still compressed.
  12045. auto res = cli.Get("/gzipped-uppercase");
  12046. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12048. EXPECT_EQ("Hello World!", res->body);
  12049. #else
  12050. ASSERT_FALSE(res);
  12051. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12052. #endif
  12053. }
  12054. }
  12055. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12056. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12057. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12058. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12059. // body a second time and appending a second Content-Encoding field line, so
  12060. // clients that decode one coding per listed value handed back raw gzip bytes.
  12061. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12062. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12063. Server svr;
  12064. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12065. // keeps the server from applying a coding of its own.
  12066. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12067. res.set_content(gzipped, "text/plain");
  12068. res.set_header("Content-Encoding", "gzip");
  12069. });
  12070. auto port = svr.bind_to_any_port(HOST);
  12071. thread t = thread([&]() { svr.listen_after_bind(); });
  12072. auto se = detail::scope_exit([&] {
  12073. svr.stop();
  12074. t.join();
  12075. ASSERT_FALSE(svr.is_running());
  12076. });
  12077. svr.wait_until_ready();
  12078. Client cli(HOST, port);
  12079. Headers headers = {{"Accept-Encoding", "gzip"}};
  12080. auto res = cli.Get("/pre-gzipped", headers);
  12081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12082. EXPECT_EQ(StatusCode::OK_200, res->status);
  12083. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12084. EXPECT_EQ("Hello World!", res->body);
  12085. }
  12086. // A chunked provider settles its coding where the headers are written and
  12087. // reuses it at write time. Both ends of that have to hold: a handler's own
  12088. // Content-Encoding suppresses the coding, and a response without one is still
  12089. // compressed as it always was.
  12090. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12091. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12092. const std::string plain = "Hello World! Hello World! Hello World!";
  12093. Server svr;
  12094. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12095. res.set_header("Content-Encoding", "gzip");
  12096. res.set_chunked_content_provider(
  12097. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12098. sink.write(gzipped.data(), gzipped.size());
  12099. sink.done();
  12100. return true;
  12101. });
  12102. });
  12103. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12104. res.set_chunked_content_provider(
  12105. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12106. sink.write(plain.data(), plain.size());
  12107. sink.done();
  12108. return true;
  12109. });
  12110. });
  12111. auto port = svr.bind_to_any_port(HOST);
  12112. thread t = thread([&]() { svr.listen_after_bind(); });
  12113. auto se = detail::scope_exit([&] {
  12114. svr.stop();
  12115. t.join();
  12116. ASSERT_FALSE(svr.is_running());
  12117. });
  12118. svr.wait_until_ready();
  12119. Client cli(HOST, port);
  12120. Headers headers = {{"Accept-Encoding", "gzip"}};
  12121. {
  12122. auto res = cli.Get("/pre-gzipped", headers);
  12123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12124. EXPECT_EQ(StatusCode::OK_200, res->status);
  12125. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12126. EXPECT_EQ("Hello World!", res->body);
  12127. }
  12128. {
  12129. auto res = cli.Get("/negotiated", headers);
  12130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12131. EXPECT_EQ(StatusCode::OK_200, res->status);
  12132. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12133. EXPECT_EQ(plain, res->body);
  12134. }
  12135. }
  12136. #endif
  12137. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12138. // the same message as the comma-joined one, so both have to be read the same
  12139. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12140. // single gzip coding, and a body the sender says was encoded twice was handed
  12141. // back after one pass, still compressed but presented as decoded.
  12142. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12143. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12144. Server svr;
  12145. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12146. res.set_content(body, "image/jpeg");
  12147. res.headers.emplace("Content-Encoding", "gzip");
  12148. res.headers.emplace("Content-Encoding", "gzip");
  12149. });
  12150. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12151. res.set_content(body, "image/jpeg");
  12152. res.set_header("Content-Encoding", "gzip, gzip");
  12153. });
  12154. auto port = svr.bind_to_any_port(HOST);
  12155. thread t = thread([&]() { svr.listen_after_bind(); });
  12156. auto se = detail::scope_exit([&] {
  12157. svr.stop();
  12158. t.join();
  12159. ASSERT_FALSE(svr.is_running());
  12160. });
  12161. svr.wait_until_ready();
  12162. Client cli(HOST, port);
  12163. // Two codings is not something cpp-httplib decodes, so both representations
  12164. // take the pass-through path rather than one of them being gunzipped once.
  12165. for (const char *path : {"/split", "/joined"}) {
  12166. auto res = cli.Get(path);
  12167. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12168. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12169. EXPECT_EQ(body, res->body) << path;
  12170. }
  12171. }
  12172. // Regression test for DoS vulnerability: a malicious server sending a response
  12173. // without Content-Length header must not cause unbounded memory consumption on
  12174. // the client side. The client should stop reading after a reasonable limit,
  12175. // similar to the server-side set_payload_max_length protection.
  12176. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12177. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12178. #ifndef _WIN32
  12179. signal(SIGPIPE, SIG_IGN);
  12180. #endif
  12181. auto server_thread = std::thread([] {
  12182. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12183. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12184. default_socket_options(srv);
  12185. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12186. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12187. sockaddr_in addr{};
  12188. addr.sin_family = AF_INET;
  12189. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12190. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12191. int opt = 1;
  12192. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12193. #ifdef _WIN32
  12194. reinterpret_cast<const char *>(&opt),
  12195. #else
  12196. &opt,
  12197. #endif
  12198. sizeof(opt));
  12199. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12200. ::listen(srv, 1);
  12201. sockaddr_in cli_addr{};
  12202. socklen_t cli_len = sizeof(cli_addr);
  12203. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12204. if (cli != INVALID_SOCKET) {
  12205. char buf[4096];
  12206. ::recv(cli, buf, sizeof(buf), 0);
  12207. // Malicious response: no Content-Length, no chunked encoding
  12208. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12209. "Connection: close\r\n"
  12210. "\r\n";
  12211. ::send(cli,
  12212. #ifdef _WIN32
  12213. static_cast<const char *>(response_header.c_str()),
  12214. static_cast<int>(response_header.size()),
  12215. #else
  12216. response_header.c_str(), response_header.size(),
  12217. #endif
  12218. 0);
  12219. // Send 10MB of data
  12220. std::string chunk(64 * 1024, 'A');
  12221. size_t total_sent = 0;
  12222. while (total_sent < MALICIOUS_DATA_SIZE) {
  12223. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12224. auto sent = ::send(cli,
  12225. #ifdef _WIN32
  12226. static_cast<const char *>(chunk.c_str()),
  12227. static_cast<int>(to_send),
  12228. #else
  12229. chunk.c_str(), to_send,
  12230. #endif
  12231. 0);
  12232. if (sent <= 0) break;
  12233. total_sent += static_cast<size_t>(sent);
  12234. }
  12235. detail::close_socket(cli);
  12236. }
  12237. detail::close_socket(srv);
  12238. });
  12239. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12240. size_t total_read = 0;
  12241. {
  12242. Client cli("127.0.0.1", PORT + 2);
  12243. cli.set_read_timeout(5, 0);
  12244. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12245. auto stream = cli.open_stream("GET", "/malicious");
  12246. ASSERT_TRUE(stream.is_valid());
  12247. char buffer[64 * 1024];
  12248. ssize_t n;
  12249. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12250. total_read += static_cast<size_t>(n);
  12251. }
  12252. } // StreamHandle and Client destroyed here, closing the socket
  12253. server_thread.join();
  12254. // With set_payload_max_length, the client must stop reading before consuming
  12255. // all 10MB. The read loop should be cut off at or near the configured limit.
  12256. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12257. << "Client read " << total_read << " bytes, exceeding the configured "
  12258. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12259. }
  12260. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12261. // the entire response body without truncation.
  12262. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12263. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12264. #ifndef _WIN32
  12265. signal(SIGPIPE, SIG_IGN);
  12266. #endif
  12267. auto server_thread = std::thread([] {
  12268. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12269. default_socket_options(srv);
  12270. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12271. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12272. sockaddr_in addr{};
  12273. addr.sin_family = AF_INET;
  12274. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12275. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12276. int opt = 1;
  12277. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12278. #ifdef _WIN32
  12279. reinterpret_cast<const char *>(&opt),
  12280. #else
  12281. &opt,
  12282. #endif
  12283. sizeof(opt));
  12284. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12285. ::listen(srv, 1);
  12286. sockaddr_in cli_addr{};
  12287. socklen_t cli_len = sizeof(cli_addr);
  12288. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12289. if (cli != INVALID_SOCKET) {
  12290. char buf[4096];
  12291. ::recv(cli, buf, sizeof(buf), 0);
  12292. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12293. "Connection: close\r\n"
  12294. "\r\n";
  12295. ::send(cli,
  12296. #ifdef _WIN32
  12297. static_cast<const char *>(response_header.c_str()),
  12298. static_cast<int>(response_header.size()),
  12299. #else
  12300. response_header.c_str(), response_header.size(),
  12301. #endif
  12302. 0);
  12303. std::string chunk(64 * 1024, 'A');
  12304. size_t total_sent = 0;
  12305. while (total_sent < DATA_SIZE) {
  12306. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12307. auto sent = ::send(cli,
  12308. #ifdef _WIN32
  12309. static_cast<const char *>(chunk.c_str()),
  12310. static_cast<int>(to_send),
  12311. #else
  12312. chunk.c_str(), to_send,
  12313. #endif
  12314. 0);
  12315. if (sent <= 0) break;
  12316. total_sent += static_cast<size_t>(sent);
  12317. }
  12318. #ifdef _WIN32
  12319. ::shutdown(cli, SD_SEND);
  12320. #else
  12321. ::shutdown(cli, SHUT_WR);
  12322. #endif
  12323. // Drain until the client closes its end, ensuring all data is delivered
  12324. char drain[1024];
  12325. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12326. detail::close_socket(cli);
  12327. }
  12328. detail::close_socket(srv);
  12329. });
  12330. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12331. size_t total_read = 0;
  12332. {
  12333. Client cli("127.0.0.1", PORT + 2);
  12334. cli.set_read_timeout(5, 0);
  12335. cli.set_payload_max_length(0); // 0 means no limit
  12336. auto stream = cli.open_stream("GET", "/data");
  12337. ASSERT_TRUE(stream.is_valid());
  12338. char buffer[64 * 1024];
  12339. ssize_t n;
  12340. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12341. total_read += static_cast<size_t>(n);
  12342. }
  12343. }
  12344. server_thread.join();
  12345. EXPECT_EQ(total_read, DATA_SIZE)
  12346. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12347. << " bytes without truncation, but only read " << total_read << " bytes.";
  12348. }
  12349. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12350. // enormous Content-Length must not cause the client to pre-allocate a huge
  12351. // response body buffer. The reservation is capped at payload_max_length_, and
  12352. // the read itself fails when the body exceeds the limit.
  12353. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12354. #ifndef _WIN32
  12355. signal(SIGPIPE, SIG_IGN);
  12356. #endif
  12357. auto server_thread = std::thread([] {
  12358. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12359. default_socket_options(srv);
  12360. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12361. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12362. sockaddr_in addr{};
  12363. addr.sin_family = AF_INET;
  12364. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12365. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12366. int opt = 1;
  12367. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12368. #ifdef _WIN32
  12369. reinterpret_cast<const char *>(&opt),
  12370. #else
  12371. &opt,
  12372. #endif
  12373. sizeof(opt));
  12374. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12375. ::listen(srv, 1);
  12376. sockaddr_in cli_addr{};
  12377. socklen_t cli_len = sizeof(cli_addr);
  12378. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12379. if (cli != INVALID_SOCKET) {
  12380. char buf[4096];
  12381. ::recv(cli, buf, sizeof(buf), 0);
  12382. // Malicious response: claim a 20GB body but send only a tiny payload.
  12383. std::string response = "HTTP/1.1 200 OK\r\n"
  12384. "Content-Length: 20000000000\r\n"
  12385. "\r\n"
  12386. "abc";
  12387. ::send(cli,
  12388. #ifdef _WIN32
  12389. static_cast<const char *>(response.c_str()),
  12390. static_cast<int>(response.size()),
  12391. #else
  12392. response.c_str(), response.size(),
  12393. #endif
  12394. 0);
  12395. detail::close_socket(cli);
  12396. }
  12397. detail::close_socket(srv);
  12398. });
  12399. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12400. {
  12401. Client cli("127.0.0.1", PORT + 2);
  12402. cli.set_read_timeout(5, 0);
  12403. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12404. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12405. // (server claims more bytes than payload_max_length permits), but it must
  12406. // not exhaust memory before getting there.
  12407. auto res = cli.Get("/malicious");
  12408. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12409. }
  12410. server_thread.join();
  12411. }
  12412. // Verify that content_receiver bypasses the default payload_max_length,
  12413. // allowing streaming downloads larger than 100MB without requiring an explicit
  12414. // set_payload_max_length call.
  12415. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12416. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12417. #ifndef _WIN32
  12418. signal(SIGPIPE, SIG_IGN);
  12419. #endif
  12420. auto server_thread = std::thread([] {
  12421. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12422. default_socket_options(srv);
  12423. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12424. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12425. sockaddr_in addr{};
  12426. addr.sin_family = AF_INET;
  12427. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12428. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12429. int opt = 1;
  12430. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12431. #ifdef _WIN32
  12432. reinterpret_cast<const char *>(&opt),
  12433. #else
  12434. &opt,
  12435. #endif
  12436. sizeof(opt));
  12437. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12438. ::listen(srv, 1);
  12439. sockaddr_in cli_addr{};
  12440. socklen_t cli_len = sizeof(cli_addr);
  12441. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12442. if (cli != INVALID_SOCKET) {
  12443. char buf[4096];
  12444. ::recv(cli, buf, sizeof(buf), 0);
  12445. // Response with Content-Length larger than default 100MB limit
  12446. auto content_length = std::to_string(DATA_SIZE);
  12447. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12448. "Content-Length: " +
  12449. content_length +
  12450. "\r\n"
  12451. "Connection: close\r\n"
  12452. "\r\n";
  12453. ::send(cli,
  12454. #ifdef _WIN32
  12455. static_cast<const char *>(response_header.c_str()),
  12456. static_cast<int>(response_header.size()),
  12457. #else
  12458. response_header.c_str(), response_header.size(),
  12459. #endif
  12460. 0);
  12461. std::string chunk(64 * 1024, 'A');
  12462. size_t total_sent = 0;
  12463. while (total_sent < DATA_SIZE) {
  12464. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12465. auto sent = ::send(cli,
  12466. #ifdef _WIN32
  12467. static_cast<const char *>(chunk.c_str()),
  12468. static_cast<int>(to_send),
  12469. #else
  12470. chunk.c_str(), to_send,
  12471. #endif
  12472. 0);
  12473. if (sent <= 0) break;
  12474. total_sent += static_cast<size_t>(sent);
  12475. }
  12476. detail::close_socket(cli);
  12477. }
  12478. detail::close_socket(srv);
  12479. });
  12480. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12481. size_t total_received = 0;
  12482. {
  12483. Client cli("127.0.0.1", PORT + 2);
  12484. cli.set_read_timeout(10, 0);
  12485. // Do NOT call set_payload_max_length — use the default 100MB limit
  12486. auto res =
  12487. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12488. total_received += data_length;
  12489. return true;
  12490. });
  12491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12492. EXPECT_EQ(StatusCode::OK_200, res->status);
  12493. }
  12494. server_thread.join();
  12495. EXPECT_EQ(total_received, DATA_SIZE)
  12496. << "With content_receiver, the client should read all " << DATA_SIZE
  12497. << " bytes despite the default 100MB payload_max_length, but only read "
  12498. << total_received << " bytes.";
  12499. }
  12500. // Verify that an explicit set_payload_max_length smaller than the response is
  12501. // enforced even when a content_receiver is used.
  12502. TEST(ClientVulnerabilityTest,
  12503. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12504. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12505. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12506. #ifndef _WIN32
  12507. signal(SIGPIPE, SIG_IGN);
  12508. #endif
  12509. auto server_thread = std::thread([] {
  12510. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12511. default_socket_options(srv);
  12512. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12513. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12514. sockaddr_in addr{};
  12515. addr.sin_family = AF_INET;
  12516. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12517. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12518. int opt = 1;
  12519. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12520. #ifdef _WIN32
  12521. reinterpret_cast<const char *>(&opt),
  12522. #else
  12523. &opt,
  12524. #endif
  12525. sizeof(opt));
  12526. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12527. ::listen(srv, 1);
  12528. sockaddr_in cli_addr{};
  12529. socklen_t cli_len = sizeof(cli_addr);
  12530. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12531. if (cli != INVALID_SOCKET) {
  12532. char buf[4096];
  12533. ::recv(cli, buf, sizeof(buf), 0);
  12534. auto content_length = std::to_string(DATA_SIZE);
  12535. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12536. "Content-Length: " +
  12537. content_length +
  12538. "\r\n"
  12539. "Connection: close\r\n"
  12540. "\r\n";
  12541. ::send(cli,
  12542. #ifdef _WIN32
  12543. static_cast<const char *>(response_header.c_str()),
  12544. static_cast<int>(response_header.size()),
  12545. #else
  12546. response_header.c_str(), response_header.size(),
  12547. #endif
  12548. 0);
  12549. std::string chunk(64 * 1024, 'A');
  12550. size_t total_sent = 0;
  12551. while (total_sent < DATA_SIZE) {
  12552. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12553. auto sent = ::send(cli,
  12554. #ifdef _WIN32
  12555. static_cast<const char *>(chunk.c_str()),
  12556. static_cast<int>(to_send),
  12557. #else
  12558. chunk.c_str(), to_send,
  12559. #endif
  12560. 0);
  12561. if (sent <= 0) break;
  12562. total_sent += static_cast<size_t>(sent);
  12563. }
  12564. detail::close_socket(cli);
  12565. }
  12566. detail::close_socket(srv);
  12567. });
  12568. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12569. size_t total_received = 0;
  12570. {
  12571. Client cli("127.0.0.1", PORT + 2);
  12572. cli.set_read_timeout(10, 0);
  12573. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12574. auto res =
  12575. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12576. total_received += data_length;
  12577. return true;
  12578. });
  12579. // Should fail because 200MB exceeds the explicit 150MB limit
  12580. EXPECT_FALSE(res);
  12581. }
  12582. server_thread.join();
  12583. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12584. << "Client with content_receiver should respect the explicit "
  12585. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12586. << total_received << " bytes.";
  12587. }
  12588. // Verify that an explicit set_payload_max_length larger than the response
  12589. // allows the content_receiver to read all data successfully.
  12590. TEST(ClientVulnerabilityTest,
  12591. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12592. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12593. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12594. #ifndef _WIN32
  12595. signal(SIGPIPE, SIG_IGN);
  12596. #endif
  12597. auto server_thread = std::thread([] {
  12598. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12599. default_socket_options(srv);
  12600. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12601. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12602. sockaddr_in addr{};
  12603. addr.sin_family = AF_INET;
  12604. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12605. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12606. int opt = 1;
  12607. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12608. #ifdef _WIN32
  12609. reinterpret_cast<const char *>(&opt),
  12610. #else
  12611. &opt,
  12612. #endif
  12613. sizeof(opt));
  12614. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12615. ::listen(srv, 1);
  12616. sockaddr_in cli_addr{};
  12617. socklen_t cli_len = sizeof(cli_addr);
  12618. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12619. if (cli != INVALID_SOCKET) {
  12620. char buf[4096];
  12621. ::recv(cli, buf, sizeof(buf), 0);
  12622. auto content_length = std::to_string(DATA_SIZE);
  12623. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12624. "Content-Length: " +
  12625. content_length +
  12626. "\r\n"
  12627. "Connection: close\r\n"
  12628. "\r\n";
  12629. ::send(cli,
  12630. #ifdef _WIN32
  12631. static_cast<const char *>(response_header.c_str()),
  12632. static_cast<int>(response_header.size()),
  12633. #else
  12634. response_header.c_str(), response_header.size(),
  12635. #endif
  12636. 0);
  12637. std::string chunk(64 * 1024, 'A');
  12638. size_t total_sent = 0;
  12639. while (total_sent < DATA_SIZE) {
  12640. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12641. auto sent = ::send(cli,
  12642. #ifdef _WIN32
  12643. static_cast<const char *>(chunk.c_str()),
  12644. static_cast<int>(to_send),
  12645. #else
  12646. chunk.c_str(), to_send,
  12647. #endif
  12648. 0);
  12649. if (sent <= 0) break;
  12650. total_sent += static_cast<size_t>(sent);
  12651. }
  12652. #ifdef _WIN32
  12653. ::shutdown(cli, SD_SEND);
  12654. #else
  12655. ::shutdown(cli, SHUT_WR);
  12656. #endif
  12657. char drain[1024];
  12658. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12659. detail::close_socket(cli);
  12660. }
  12661. detail::close_socket(srv);
  12662. });
  12663. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12664. size_t total_received = 0;
  12665. {
  12666. Client cli("127.0.0.1", PORT + 2);
  12667. cli.set_read_timeout(10, 0);
  12668. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12669. auto res =
  12670. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12671. total_received += data_length;
  12672. return true;
  12673. });
  12674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12675. EXPECT_EQ(StatusCode::OK_200, res->status);
  12676. }
  12677. server_thread.join();
  12678. EXPECT_EQ(total_received, DATA_SIZE)
  12679. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12680. << " bytes (larger than " << DATA_SIZE
  12681. << " bytes response), content_receiver should read all data, but only "
  12682. "read "
  12683. << total_received << " bytes.";
  12684. }
  12685. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12686. // Regression test for "zip bomb" attack on the client side: a malicious server
  12687. // sends a small gzip-compressed response that decompresses to a huge payload.
  12688. // The client must enforce payload_max_length on the decompressed size.
  12689. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12690. constexpr size_t DECOMPRESSED_SIZE =
  12691. 10 * 1024 * 1024; // 10MB after decompression
  12692. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12693. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12694. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12695. std::string compressed;
  12696. {
  12697. httplib::detail::gzip_compressor compressor;
  12698. bool ok =
  12699. compressor.compress(uncompressed.data(), uncompressed.size(),
  12700. /*last=*/true, [&](const char *buf, size_t len) {
  12701. compressed.append(buf, len);
  12702. return true;
  12703. });
  12704. ASSERT_TRUE(ok);
  12705. }
  12706. // Sanity: compressed data should be much smaller than the decompressed size
  12707. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12708. #ifndef _WIN32
  12709. signal(SIGPIPE, SIG_IGN);
  12710. #endif
  12711. // Set up the listening socket in the main thread so the server is guaranteed
  12712. // to be ready before the client connects (eliminates race condition).
  12713. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12714. default_socket_options(srv);
  12715. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12716. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12717. sockaddr_in addr{};
  12718. addr.sin_family = AF_INET;
  12719. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12720. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12721. int opt = 1;
  12722. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12723. #ifdef _WIN32
  12724. reinterpret_cast<const char *>(&opt),
  12725. #else
  12726. &opt,
  12727. #endif
  12728. sizeof(opt));
  12729. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12730. ASSERT_EQ(0, ::listen(srv, 1));
  12731. auto server_thread = std::thread([&compressed, srv] {
  12732. sockaddr_in cli_addr{};
  12733. socklen_t cli_len = sizeof(cli_addr);
  12734. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12735. if (cli != INVALID_SOCKET) {
  12736. // Read the full HTTP request (until \r\n\r\n)
  12737. char buf[4096];
  12738. size_t total = 0;
  12739. while (total < sizeof(buf)) {
  12740. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12741. if (n <= 0) break;
  12742. total += static_cast<size_t>(n);
  12743. // Check for end of headers
  12744. if (total >= 4) {
  12745. std::string req(buf, total);
  12746. if (req.find("\r\n\r\n") != std::string::npos) break;
  12747. }
  12748. }
  12749. // Malicious response: gzip-compressed body, no Content-Length
  12750. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12751. "Content-Encoding: gzip\r\n"
  12752. "Connection: close\r\n"
  12753. "\r\n";
  12754. ::send(cli,
  12755. #ifdef _WIN32
  12756. static_cast<const char *>(response_header.c_str()),
  12757. static_cast<int>(response_header.size()),
  12758. #else
  12759. response_header.c_str(), response_header.size(),
  12760. #endif
  12761. 0);
  12762. // Send the compressed payload (small on the wire, huge when decompressed)
  12763. size_t total_sent = 0;
  12764. while (total_sent < compressed.size()) {
  12765. auto to_send = std::min(compressed.size() - total_sent,
  12766. static_cast<size_t>(64 * 1024));
  12767. auto sent =
  12768. ::send(cli,
  12769. #ifdef _WIN32
  12770. static_cast<const char *>(compressed.c_str() + total_sent),
  12771. static_cast<int>(to_send),
  12772. #else
  12773. compressed.c_str() + total_sent, to_send,
  12774. #endif
  12775. 0);
  12776. if (sent <= 0) break;
  12777. total_sent += static_cast<size_t>(sent);
  12778. }
  12779. detail::close_socket(cli);
  12780. }
  12781. });
  12782. auto se = detail::scope_exit([&] {
  12783. detail::close_socket(srv);
  12784. server_thread.join();
  12785. });
  12786. size_t total_decompressed = 0;
  12787. {
  12788. Client cli("127.0.0.1", PORT + 3);
  12789. cli.set_read_timeout(5, 0);
  12790. cli.set_decompress(true);
  12791. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12792. auto stream = cli.open_stream("GET", "/zipbomb");
  12793. ASSERT_TRUE(stream.is_valid());
  12794. char buffer[64 * 1024];
  12795. ssize_t n;
  12796. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12797. total_decompressed += static_cast<size_t>(n);
  12798. }
  12799. }
  12800. // The decompressed size must be capped by payload_max_length. Without
  12801. // protection, the client would decompress the full 10MB from a tiny
  12802. // compressed payload, enabling a zip bomb DoS attack.
  12803. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12804. << "Client decompressed " << total_decompressed
  12805. << " bytes from a gzip response. The decompressed size should be "
  12806. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12807. }
  12808. #endif
  12809. TEST(HostAndPortPropertiesTest, NoSSL) {
  12810. httplib::Client cli("www.google.com", 1234);
  12811. ASSERT_EQ("www.google.com", cli.host());
  12812. ASSERT_EQ(1234, cli.port());
  12813. }
  12814. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12815. httplib::Client cli("www.google.com:1234");
  12816. ASSERT_EQ("www.google.com", cli.host());
  12817. ASSERT_EQ(1234, cli.port());
  12818. }
  12819. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12820. // Port number that overflows int — should not crash, client becomes invalid
  12821. httplib::Client cli("http://www.google.com:99999999999999999999");
  12822. ASSERT_FALSE(cli.is_valid());
  12823. }
  12824. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12825. // Port 99999 exceeds valid range (1-65535) — should not crash
  12826. httplib::Client cli("http://www.google.com:99999");
  12827. ASSERT_FALSE(cli.is_valid());
  12828. auto res = cli.Get("/");
  12829. EXPECT_FALSE(res);
  12830. EXPECT_EQ(Error::Connection, res.error());
  12831. }
  12832. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  12833. httplib::Client cli("http://user:pass@localhost:1234");
  12834. ASSERT_FALSE(cli.is_valid());
  12835. EXPECT_FALSE(cli.Get("/"));
  12836. }
  12837. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12838. httplib::Client cli("http://www.google.com:80abc");
  12839. ASSERT_FALSE(cli.is_valid());
  12840. }
  12841. #ifdef CPPHTTPLIB_SSL_ENABLED
  12842. TEST(HostAndPortPropertiesTest, SSL) {
  12843. httplib::SSLClient cli("www.google.com");
  12844. ASSERT_EQ("www.google.com", cli.host());
  12845. ASSERT_EQ(443, cli.port());
  12846. }
  12847. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12848. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12849. std::string cert;
  12850. read_file(CA_CERT_FILE, cert);
  12851. httplib::SSLClient httplib_client("www.google.com");
  12852. // Load CA store first time
  12853. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12854. // Load CA store second time (update)
  12855. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12856. // Verify client is still valid and can make connections
  12857. httplib_client.enable_server_certificate_verification(true);
  12858. auto res = httplib_client.Get("/");
  12859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12860. // Google may return 200 or 301 depending on various factors
  12861. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12862. res->status == StatusCode::MovedPermanently_301);
  12863. }
  12864. TEST(SSLClientTest, ServerNameIndication_Online) {
  12865. auto host = "httpbingo.org";
  12866. auto path = std::string{"/get"};
  12867. SSLClient cli(host, 443);
  12868. auto res = cli.Get(path);
  12869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12870. ASSERT_EQ(StatusCode::OK_200, res->status);
  12871. }
  12872. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12873. // Use a site that will cause SSL verification failure due to self-signed cert
  12874. SSLClient cli("self-signed.badssl.com", 443);
  12875. cli.enable_server_certificate_verification(true);
  12876. auto res = cli.Get("/");
  12877. ASSERT_TRUE(!res);
  12878. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12879. // Verify backend error is captured for SSLServerVerification
  12880. // This occurs when certificate verification fails
  12881. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12882. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12883. EXPECT_NE(0UL, res.ssl_backend_error());
  12884. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12885. // For OpenSSL, ssl_error is 0 for verification errors
  12886. EXPECT_EQ(0, res.ssl_error());
  12887. #if !defined(_WIN32) || \
  12888. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12889. // On non-Windows or when Windows Schannel is disabled, the error comes
  12890. // from OpenSSL's verification
  12891. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12892. res.ssl_backend_error());
  12893. #endif
  12894. #endif
  12895. }
  12896. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12897. // Use a site where hostname doesn't match the certificate
  12898. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12899. SSLClient cli("wrong.host.badssl.com", 443);
  12900. cli.enable_server_certificate_verification(true);
  12901. cli.enable_server_hostname_verification(true);
  12902. auto res = cli.Get("/");
  12903. ASSERT_TRUE(!res);
  12904. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12905. // Verify backend error is captured for hostname verification failure
  12906. EXPECT_NE(0UL, res.ssl_backend_error());
  12907. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12908. // For OpenSSL, ssl_error is 0 for verification errors
  12909. EXPECT_EQ(0, res.ssl_error());
  12910. #if !defined(_WIN32) || \
  12911. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12912. // On non-Windows or when Windows Schannel is disabled, the error comes
  12913. // from OpenSSL's hostname verification
  12914. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12915. res.ssl_backend_error());
  12916. #endif
  12917. #endif
  12918. }
  12919. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12920. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12921. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12922. SSLClient cli("www.google.com", 443);
  12923. cli.enable_server_certificate_verification(true);
  12924. auto res = cli.Get("/");
  12925. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12926. }
  12927. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12928. SSLClient cli("www.google.com", 443);
  12929. cli.enable_server_certificate_verification(true);
  12930. cli.enable_windows_certificate_verification(false);
  12931. auto res = cli.Get("/");
  12932. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12933. }
  12934. // The server sends an intermediate cross-signed by a root Windows trusts,
  12935. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12936. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12937. SSLClient cli("accounts.spotify.com", 443);
  12938. auto res = cli.Get("/");
  12939. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12940. << " ssl_backend_error=" << res.ssl_backend_error();
  12941. }
  12942. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12943. // policy status, which no backend reports for a self-signed certificate.
  12944. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12945. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12946. ASSERT_TRUE(svr.is_valid());
  12947. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12948. auto se = detail::scope_exit([&] {
  12949. svr.stop();
  12950. t.join();
  12951. ASSERT_FALSE(svr.is_running());
  12952. });
  12953. svr.wait_until_ready();
  12954. SSLClient cli("127.0.0.1", PORT);
  12955. cli.set_connection_timeout(30);
  12956. auto res = cli.Get("/");
  12957. ASSERT_FALSE(res);
  12958. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12959. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12960. }
  12961. #endif
  12962. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12963. Client cli("https://google.com");
  12964. auto res = cli.Get("/");
  12965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12966. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12967. }
  12968. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12969. SSLClient cli("google.com");
  12970. cli.set_ca_cert_path(CA_CERT_FILE);
  12971. auto res = cli.Get("/");
  12972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12973. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12974. }
  12975. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12976. SSLClient cli("google.com");
  12977. cli.enable_server_certificate_verification(true);
  12978. cli.set_ca_cert_path("hello");
  12979. auto res = cli.Get("/");
  12980. ASSERT_TRUE(!res);
  12981. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12982. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12983. // should be set
  12984. EXPECT_EQ(0, res.ssl_error());
  12985. // Verify backend error is captured for SSLLoadingCerts
  12986. // This error occurs when loading CA certificates fails
  12987. EXPECT_NE(0UL, res.ssl_backend_error());
  12988. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12989. // OpenSSL specific error codes:
  12990. // > openssl errstr 0x80000002
  12991. // error:80000002:system library::No such file or directory
  12992. // > openssl errstr 0xA000126
  12993. // error:0A000126:SSL routines::unexpected eof while reading
  12994. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12995. res.ssl_backend_error() == 0xA000126);
  12996. #endif
  12997. }
  12998. TEST(SSLClientTest, ServerCertificateVerification4) {
  12999. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13000. ASSERT_TRUE(svr.is_valid());
  13001. svr.Get("/test", [&](const Request &, Response &res) {
  13002. res.set_content("test", "text/plain");
  13003. svr.stop();
  13004. ASSERT_TRUE(true);
  13005. });
  13006. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13007. auto se = detail::scope_exit([&] {
  13008. t.join();
  13009. ASSERT_FALSE(svr.is_running());
  13010. });
  13011. svr.wait_until_ready();
  13012. SSLClient cli("127.0.0.1", PORT);
  13013. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13014. cli.enable_server_certificate_verification(true);
  13015. cli.set_connection_timeout(30);
  13016. auto res = cli.Get("/test");
  13017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13018. ASSERT_EQ(StatusCode::OK_200, res->status);
  13019. }
  13020. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13021. std::string cert;
  13022. read_file(CA_CERT_FILE, cert);
  13023. SSLClient cli("google.com");
  13024. cli.load_ca_cert_store(cert.data(), cert.size());
  13025. const auto res = cli.Get("/");
  13026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13027. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13028. }
  13029. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13030. // clang-format off
  13031. static constexpr char cert[] =
  13032. "GlobalSign Root CA\n"
  13033. "==================\n"
  13034. "-----BEGIN CERTIFICATE-----\n"
  13035. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13036. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13037. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13038. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13039. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13040. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13041. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13042. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13043. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13044. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13045. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13046. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13047. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13048. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13049. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13050. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13051. "-----END CERTIFICATE-----\n";
  13052. // clang-format on
  13053. SSLClient cli("google.com");
  13054. cli.load_ca_cert_store(cert, sizeof(cert));
  13055. const auto res = cli.Get("/");
  13056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13057. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13058. }
  13059. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13060. SSLClient cli("www.youtube.com");
  13061. cli.set_ca_cert_path(CA_CERT_FILE);
  13062. cli.enable_server_certificate_verification(true);
  13063. cli.set_follow_location(true);
  13064. auto res = cli.Get("/");
  13065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13066. ASSERT_EQ(StatusCode::OK_200, res->status);
  13067. }
  13068. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13069. SSLClient cli("wWw.YouTube.Com");
  13070. cli.set_ca_cert_path(CA_CERT_FILE);
  13071. cli.enable_server_certificate_verification(true);
  13072. cli.enable_server_hostname_verification(true);
  13073. cli.set_follow_location(true);
  13074. auto res = cli.Get("/");
  13075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13076. ASSERT_EQ(StatusCode::OK_200, res->status);
  13077. }
  13078. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13079. SSLClient cli("gOoGlE.COm");
  13080. cli.enable_server_certificate_verification(true);
  13081. cli.enable_server_hostname_verification(true);
  13082. cli.set_follow_location(true);
  13083. auto res = cli.Get("/");
  13084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13085. ASSERT_EQ(StatusCode::OK_200, res->status);
  13086. }
  13087. TEST(SSLClientTest, Issue2004_Online) {
  13088. Client client("https://google.com");
  13089. client.set_follow_location(true);
  13090. auto res = client.Get("/");
  13091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13092. ASSERT_EQ(StatusCode::OK_200, res->status);
  13093. auto body = res->body;
  13094. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13095. }
  13096. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13097. // Create SSLClient with invalid cert/key to make is_valid() return false
  13098. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13099. "nonexistent_key.pem");
  13100. // is_valid() should be false due to cert loading failure
  13101. ASSERT_FALSE(cli.is_valid());
  13102. auto res = cli.Get("/");
  13103. ASSERT_FALSE(res);
  13104. EXPECT_EQ(Error::SSLConnection, res.error());
  13105. }
  13106. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13107. // Test for Issue #2251: SSL error not properly reported when client cert
  13108. // and key paths are swapped or mismatched
  13109. // This simulates the scenario where user accidentally swaps the cert and key
  13110. // files
  13111. // Using client cert file as private key and vice versa (completely wrong)
  13112. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13113. // Should fail validation due to cert/key mismatch
  13114. ASSERT_FALSE(cli.is_valid());
  13115. // Attempt to make a request should fail with proper error
  13116. auto res = cli.Get("/");
  13117. ASSERT_FALSE(res);
  13118. EXPECT_EQ(Error::SSLConnection, res.error());
  13119. // SSL error should be recorded in the Result object (this is the key fix for
  13120. // Issue #2251)
  13121. auto backend_error = res.ssl_backend_error();
  13122. EXPECT_NE(0u, backend_error);
  13123. }
  13124. // Tests cert/key mismatch detection at the TLS context level
  13125. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13126. // Test that using mismatched cert/key causes connection failure.
  13127. // We verify this at the SSLClient level rather than through internal
  13128. // TLS API functions.
  13129. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13130. cli.enable_server_certificate_verification(false);
  13131. cli.set_connection_timeout(2);
  13132. // The mismatch should cause a connection or handshake error
  13133. auto res = cli.Get("/test");
  13134. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13135. // Either way, the request should fail
  13136. EXPECT_FALSE(res);
  13137. }
  13138. #endif
  13139. #if 0
  13140. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13141. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13142. ASSERT_TRUE(cli != nullptr);
  13143. cli->set_address_family(AF_INET6);
  13144. cli->set_interface("en0");
  13145. auto res = cli->Get("/get");
  13146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13147. ASSERT_EQ(StatusCode::OK_200, res->status);
  13148. }
  13149. #endif
  13150. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13151. #ifdef CPPHTTPLIB_SSL_ENABLED
  13152. void ClientCertPresent(
  13153. const std::string &client_cert_file,
  13154. const std::string &client_private_key_file,
  13155. const std::string &client_encrypted_private_key_pass = std::string()) {
  13156. using namespace httplib::tls;
  13157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13158. CLIENT_CA_CERT_DIR);
  13159. ASSERT_TRUE(svr.is_valid());
  13160. svr.Get("/test", [&](const Request &req, Response &res) {
  13161. res.set_content("test", "text/plain");
  13162. auto cert = req.peer_cert();
  13163. ASSERT_TRUE(static_cast<bool>(cert));
  13164. std::string common_name = cert.subject_cn();
  13165. EXPECT_EQ("Common Name", common_name);
  13166. });
  13167. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13168. auto se = detail::scope_exit([&] {
  13169. svr.stop();
  13170. t.join();
  13171. ASSERT_FALSE(svr.is_running());
  13172. });
  13173. svr.wait_until_ready();
  13174. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13175. client_encrypted_private_key_pass);
  13176. cli.enable_server_certificate_verification(false);
  13177. cli.set_connection_timeout(30);
  13178. auto res = cli.Get("/test");
  13179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13180. ASSERT_EQ(StatusCode::OK_200, res->status);
  13181. }
  13182. TEST(SSLClientServerTest, ClientCertPresent) {
  13183. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13184. }
  13185. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13186. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13187. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13188. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13189. }
  13190. // PEM memory-based constructor tests (works with all TLS backends)
  13191. void PemMemoryClientCertPresent(
  13192. const std::string &client_cert_file,
  13193. const std::string &client_private_key_file,
  13194. const std::string &client_encrypted_private_key_pass = std::string()) {
  13195. // Read PEM files into memory
  13196. std::string server_cert_pem, server_key_pem;
  13197. std::string client_ca_pem;
  13198. std::string client_cert_pem, client_key_pem;
  13199. read_file(SERVER_CERT_FILE, server_cert_pem);
  13200. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13201. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13202. read_file(client_cert_file, client_cert_pem);
  13203. read_file(client_private_key_file, client_key_pem);
  13204. // Create server with PEM memory
  13205. SSLServer::PemMemory server_pem = {
  13206. server_cert_pem.c_str(),
  13207. server_cert_pem.size(),
  13208. server_key_pem.c_str(),
  13209. server_key_pem.size(),
  13210. client_ca_pem.c_str(),
  13211. client_ca_pem.size(),
  13212. nullptr // no password for server key
  13213. };
  13214. SSLServer svr(server_pem);
  13215. ASSERT_TRUE(svr.is_valid());
  13216. svr.Get("/test", [&](const Request &, Response &res) {
  13217. res.set_content("test", "text/plain");
  13218. });
  13219. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13220. auto se = detail::scope_exit([&] {
  13221. svr.stop();
  13222. t.join();
  13223. ASSERT_FALSE(svr.is_running());
  13224. });
  13225. svr.wait_until_ready();
  13226. // Create client with PEM memory
  13227. const char *password = client_encrypted_private_key_pass.empty()
  13228. ? nullptr
  13229. : client_encrypted_private_key_pass.c_str();
  13230. SSLClient::PemMemory client_pem = {
  13231. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13232. client_key_pem.size(), password};
  13233. SSLClient cli(HOST, PORT, client_pem);
  13234. cli.enable_server_certificate_verification(false);
  13235. cli.set_connection_timeout(30);
  13236. auto res = cli.Get("/test");
  13237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13238. ASSERT_EQ(StatusCode::OK_200, res->status);
  13239. }
  13240. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13241. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13242. }
  13243. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13244. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13245. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13246. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13247. }
  13248. TEST(SSLClientServerTest, ClientCertMissing) {
  13249. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13250. CLIENT_CA_CERT_DIR);
  13251. ASSERT_TRUE(svr.is_valid());
  13252. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13253. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13254. auto se = detail::scope_exit([&] {
  13255. svr.stop();
  13256. t.join();
  13257. ASSERT_FALSE(svr.is_running());
  13258. });
  13259. svr.wait_until_ready();
  13260. SSLClient cli(HOST, PORT);
  13261. cli.set_connection_timeout(30);
  13262. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13263. // the chain check on Windows, so the result does not depend on the order.
  13264. cli.enable_server_hostname_verification(false);
  13265. auto res = cli.Get("/test");
  13266. ASSERT_TRUE(!res);
  13267. // When client cert is missing and server requires it, connection fails
  13268. // Error type depends on backend implementation
  13269. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13270. res.error() == Error::SSLConnection);
  13271. // Verify backend error is captured
  13272. // Note: This test may have different error codes depending on the exact
  13273. // verification failure
  13274. EXPECT_NE(0UL, res.ssl_backend_error());
  13275. }
  13276. TEST(SSLClientServerTest, TrustDirOptional) {
  13277. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13278. ASSERT_TRUE(svr.is_valid());
  13279. svr.Get("/test", [&](const Request &, Response &res) {
  13280. res.set_content("test", "text/plain");
  13281. });
  13282. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13283. auto se = detail::scope_exit([&] {
  13284. svr.stop();
  13285. t.join();
  13286. ASSERT_FALSE(svr.is_running());
  13287. });
  13288. svr.wait_until_ready();
  13289. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13290. cli.enable_server_certificate_verification(false);
  13291. cli.set_connection_timeout(30);
  13292. auto res = cli.Get("/test");
  13293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13294. ASSERT_EQ(StatusCode::OK_200, res->status);
  13295. }
  13296. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13297. class NoListenSSLServer : public SSLServer {
  13298. public:
  13299. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13300. const char *client_ca_cert_file_path,
  13301. const char *client_ca_cert_dir_path = nullptr)
  13302. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13303. client_ca_cert_dir_path),
  13304. stop_(false) {}
  13305. std::atomic_bool stop_;
  13306. private:
  13307. bool process_and_close_socket(socket_t /*sock*/) override {
  13308. // Don't create SSL context
  13309. while (!stop_.load()) {
  13310. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13311. }
  13312. return true;
  13313. }
  13314. };
  13315. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13316. CLIENT_CA_CERT_FILE);
  13317. ASSERT_TRUE(svr.is_valid());
  13318. svr.Get("/test", [&](const Request &, Response &res) {
  13319. res.set_content("test", "text/plain");
  13320. });
  13321. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13322. auto se = detail::scope_exit([&] {
  13323. svr.stop_ = true;
  13324. svr.stop();
  13325. t.join();
  13326. ASSERT_FALSE(svr.is_running());
  13327. });
  13328. svr.wait_until_ready();
  13329. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13330. cli.enable_server_certificate_verification(false);
  13331. cli.set_connection_timeout(1);
  13332. auto res = cli.Get("/test");
  13333. ASSERT_TRUE(!res);
  13334. EXPECT_EQ(Error::SSLConnection, res.error());
  13335. // Timeout results in WantRead error code (maps to backend-specific value)
  13336. EXPECT_NE(0, res.ssl_error());
  13337. }
  13338. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13339. // Test SSLServer with client certificate verification using the standard
  13340. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13342. CLIENT_CA_CERT_DIR);
  13343. ASSERT_TRUE(svr.is_valid());
  13344. svr.Get("/test", [&](const Request &req, Response &res) {
  13345. res.set_content("test", "text/plain");
  13346. auto cert = req.peer_cert();
  13347. ASSERT_TRUE(static_cast<bool>(cert));
  13348. auto common_name = cert.subject_cn();
  13349. EXPECT_EQ("Common Name", common_name);
  13350. });
  13351. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13352. auto se = detail::scope_exit([&] {
  13353. svr.stop();
  13354. t.join();
  13355. ASSERT_FALSE(svr.is_running());
  13356. });
  13357. svr.wait_until_ready();
  13358. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13359. cli.enable_server_certificate_verification(false);
  13360. cli.set_connection_timeout(30);
  13361. auto res = cli.Get("/test");
  13362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13363. ASSERT_EQ(StatusCode::OK_200, res->status);
  13364. }
  13365. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13366. // Verifies that wildcard matching and exact matching work consistently
  13367. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13368. using namespace httplib::tls;
  13369. // We need a running server to test against
  13370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13371. ASSERT_TRUE(svr.is_valid());
  13372. svr.Get("/test", [](const Request &, Response &res) {
  13373. res.set_content("ok", "text/plain");
  13374. });
  13375. thread t([&]() { svr.listen(HOST, PORT); });
  13376. auto se = detail::scope_exit([&] {
  13377. svr.stop();
  13378. t.join();
  13379. });
  13380. svr.wait_until_ready();
  13381. bool verify_callback_called = false;
  13382. bool verify_result_wrong = false;
  13383. SSLClient cli(HOST, PORT);
  13384. cli.enable_server_certificate_verification(true);
  13385. cli.set_ca_cert_path(CA_CERT_FILE);
  13386. cli.set_connection_timeout(5);
  13387. // Note: Test certificate has CN="Common Name", not "localhost"
  13388. bool verify_result_cn = false;
  13389. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13390. verify_callback_called = true;
  13391. if (!ctx.cert) return false;
  13392. // Test 1: "Common Name" should match (our test server cert CN)
  13393. verify_result_cn = ctx.check_hostname("Common Name");
  13394. // Test 2: wrong hostname should not match
  13395. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13396. return true; // Accept for the purpose of this test
  13397. });
  13398. auto res = cli.Get("/test");
  13399. // The request may succeed or fail depending on cert configuration
  13400. // but the callback should have been called
  13401. ASSERT_TRUE(verify_callback_called)
  13402. << "Verify callback should have been called";
  13403. // CN="Common Name" should match our test certificate
  13404. //
  13405. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13406. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13407. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13408. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13409. // <openssl/base.h>, which is included transitively when
  13410. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13411. #if defined(OPENSSL_IS_BORINGSSL)
  13412. EXPECT_FALSE(verify_result_cn)
  13413. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13414. #else
  13415. EXPECT_TRUE(verify_result_cn)
  13416. << "verify_hostname should match 'Common Name' (certificate CN)";
  13417. #endif
  13418. // Wrong hostname should not match
  13419. EXPECT_FALSE(verify_result_wrong)
  13420. << "verify_hostname should not match 'wronghost.example.com'";
  13421. }
  13422. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13423. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13424. // X509_check_ip behavior and must hold for every backend.
  13425. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13426. using namespace httplib::tls;
  13427. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13428. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13429. ASSERT_TRUE(svr.is_valid());
  13430. svr.Get("/test", [](const Request &, Response &res) {
  13431. res.set_content("ok", "text/plain");
  13432. });
  13433. thread t([&]() { svr.listen(HOST, PORT); });
  13434. auto se = detail::scope_exit([&] {
  13435. svr.stop();
  13436. t.join();
  13437. });
  13438. svr.wait_until_ready();
  13439. bool verify_callback_called = false;
  13440. bool ip_matched_via_cn = true;
  13441. SSLClient cli(HOST, PORT);
  13442. cli.enable_server_certificate_verification(true);
  13443. cli.set_ca_cert_path(CA_CERT_FILE);
  13444. cli.set_connection_timeout(5);
  13445. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13446. verify_callback_called = true;
  13447. if (!ctx.cert) return false;
  13448. // The IP appears only in the CN, so it must NOT be accepted.
  13449. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13450. return true; // Accept for the purpose of this test
  13451. });
  13452. cli.Get("/test");
  13453. ASSERT_TRUE(verify_callback_called)
  13454. << "Verify callback should have been called";
  13455. EXPECT_FALSE(ip_matched_via_cn)
  13456. << "An IP host must not be authenticated via the certificate CN";
  13457. }
  13458. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13459. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13460. using namespace httplib::tls;
  13461. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13462. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13463. ASSERT_TRUE(svr.is_valid());
  13464. svr.Get("/test", [](const Request &, Response &res) {
  13465. res.set_content("ok", "text/plain");
  13466. });
  13467. thread t([&]() { svr.listen(HOST, PORT); });
  13468. auto se = detail::scope_exit([&] {
  13469. svr.stop();
  13470. t.join();
  13471. });
  13472. svr.wait_until_ready();
  13473. bool verify_callback_called = false;
  13474. bool san_matched = false;
  13475. bool wrong_ipv6_matched = true;
  13476. bool cn_ipv6_matched = true;
  13477. SSLClient cli(HOST, PORT);
  13478. cli.enable_server_certificate_verification(true);
  13479. cli.set_ca_cert_path(CA_CERT_FILE);
  13480. cli.set_connection_timeout(5);
  13481. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13482. verify_callback_called = true;
  13483. if (!ctx.cert) return false;
  13484. // Matches the IPv6 iPAddress SAN.
  13485. san_matched = ctx.check_hostname("2001:db8::1");
  13486. // A different IPv6 address must not match.
  13487. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13488. // "::1" lives only in the CN, so it must not be accepted.
  13489. cn_ipv6_matched = ctx.check_hostname("::1");
  13490. return true; // Accept for the purpose of this test
  13491. });
  13492. cli.Get("/test");
  13493. ASSERT_TRUE(verify_callback_called)
  13494. << "Verify callback should have been called";
  13495. EXPECT_TRUE(san_matched)
  13496. << "verify_hostname should match an IPv6 iPAddress SAN";
  13497. EXPECT_FALSE(wrong_ipv6_matched)
  13498. << "verify_hostname should not match a non-matching IPv6 address";
  13499. EXPECT_FALSE(cn_ipv6_matched)
  13500. << "An IPv6 host must not be authenticated via the certificate CN";
  13501. }
  13502. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13503. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13504. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13505. using namespace httplib::tls;
  13506. // SANs: DNS:a.zz, IP:42.46.122.122
  13507. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13508. ASSERT_TRUE(svr.is_valid());
  13509. svr.Get("/test", [](const Request &, Response &res) {
  13510. res.set_content("ok", "text/plain");
  13511. });
  13512. auto port = svr.bind_to_any_port(HOST);
  13513. thread t([&]() { svr.listen_after_bind(); });
  13514. auto se = detail::scope_exit([&] {
  13515. svr.stop();
  13516. t.join();
  13517. });
  13518. svr.wait_until_ready();
  13519. bool verify_callback_called = false;
  13520. bool dns_san_matched = false;
  13521. bool ip_san_matched = false;
  13522. bool ip_matched_via_dns_san = true;
  13523. bool dns_matched_via_ip_san = true;
  13524. SSLClient cli(HOST, port);
  13525. cli.enable_server_certificate_verification(true);
  13526. cli.set_ca_cert_path(CA_CERT_FILE);
  13527. cli.set_connection_timeout(5);
  13528. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13529. verify_callback_called = true;
  13530. if (!ctx.cert) return false;
  13531. dns_san_matched = ctx.check_hostname("a.zz");
  13532. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13533. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13534. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13535. return true; // Accept for the purpose of this test
  13536. });
  13537. cli.Get("/test");
  13538. ASSERT_TRUE(verify_callback_called)
  13539. << "Verify callback should have been called";
  13540. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13541. EXPECT_TRUE(ip_san_matched)
  13542. << "verify_hostname should match an iPAddress SAN";
  13543. EXPECT_FALSE(ip_matched_via_dns_san)
  13544. << "An IP host must not be authenticated via a dNSName SAN";
  13545. EXPECT_FALSE(dns_matched_via_ip_san)
  13546. << "A DNS host must not be authenticated via an iPAddress SAN";
  13547. }
  13548. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13549. // "www.*.example.test" names one host and not every host under example.test.
  13550. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13551. using namespace httplib::tls;
  13552. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13553. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13554. ASSERT_TRUE(svr.is_valid());
  13555. svr.Get("/test", [](const Request &, Response &res) {
  13556. res.set_content("ok", "text/plain");
  13557. });
  13558. auto port = svr.bind_to_any_port(HOST);
  13559. thread t([&]() { svr.listen_after_bind(); });
  13560. auto se = detail::scope_exit([&] {
  13561. svr.stop();
  13562. t.join();
  13563. });
  13564. svr.wait_until_ready();
  13565. bool verify_callback_called = false;
  13566. bool leftmost_wildcard_matched = false;
  13567. bool wildcard_spanned_labels = true;
  13568. bool inner_wildcard_matched = true;
  13569. SSLClient cli(HOST, port);
  13570. cli.enable_server_certificate_verification(true);
  13571. cli.set_ca_cert_path(CA_CERT_FILE);
  13572. cli.set_connection_timeout(5);
  13573. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13574. verify_callback_called = true;
  13575. if (!ctx.cert) return false;
  13576. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13577. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13578. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13579. return true; // Accept for the purpose of this test
  13580. });
  13581. cli.Get("/test");
  13582. ASSERT_TRUE(verify_callback_called)
  13583. << "Verify callback should have been called";
  13584. EXPECT_TRUE(leftmost_wildcard_matched)
  13585. << "A leftmost wildcard should match a single label";
  13586. EXPECT_FALSE(wildcard_spanned_labels)
  13587. << "A wildcard label must not match more than one label";
  13588. EXPECT_FALSE(inner_wildcard_matched)
  13589. << "A wildcard outside the leftmost label must not be honoured";
  13590. }
  13591. // sans() must report each SAN entry under its own type.
  13592. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13593. using namespace httplib::tls;
  13594. // SANs: DNS:a.zz, IP:42.46.122.122
  13595. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13596. ASSERT_TRUE(svr.is_valid());
  13597. svr.Get("/test", [](const Request &, Response &res) {
  13598. res.set_content("ok", "text/plain");
  13599. });
  13600. auto port = svr.bind_to_any_port(HOST);
  13601. thread t([&]() { svr.listen_after_bind(); });
  13602. auto se = detail::scope_exit([&] {
  13603. svr.stop();
  13604. t.join();
  13605. });
  13606. svr.wait_until_ready();
  13607. bool verify_callback_called = false;
  13608. std::vector<SanEntry> sans;
  13609. SSLClient cli(HOST, port);
  13610. cli.enable_server_certificate_verification(true);
  13611. cli.set_ca_cert_path(CA_CERT_FILE);
  13612. cli.set_connection_timeout(5);
  13613. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13614. verify_callback_called = true;
  13615. if (!ctx.cert) return false;
  13616. sans = ctx.sans();
  13617. return true; // Accept for the purpose of this test
  13618. });
  13619. cli.Get("/test");
  13620. ASSERT_TRUE(verify_callback_called)
  13621. << "Verify callback should have been called";
  13622. auto has_san = [&](SanType type, const std::string &value) {
  13623. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13624. return san.type == type && san.value == value;
  13625. });
  13626. };
  13627. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13628. << "sans() should report the dNSName SAN";
  13629. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13630. << "sans() should report the iPAddress SAN";
  13631. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13632. << "sans() must not report the dNSName SAN as an address";
  13633. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13634. << "sans() must not report the iPAddress SAN as a DNS name";
  13635. }
  13636. #endif
  13637. // mbedTLS-specific callback constructor test
  13638. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13639. #ifdef CPPHTTPLIB_SSL_ENABLED
  13640. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13642. ASSERT_TRUE(svr.is_valid());
  13643. // Set up a handler to verify client certificate is present
  13644. bool client_cert_verified = false;
  13645. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13646. // Verify that client certificate was provided
  13647. client_cert_verified = true;
  13648. res.set_content("success", "text/plain");
  13649. });
  13650. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13651. auto se = detail::scope_exit([&] {
  13652. svr.stop();
  13653. t.join();
  13654. ASSERT_FALSE(svr.is_running());
  13655. });
  13656. svr.wait_until_ready();
  13657. // Client with certificate
  13658. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13659. cli.enable_server_certificate_verification(false);
  13660. cli.set_connection_timeout(30);
  13661. auto res = cli.Get("/test");
  13662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13663. ASSERT_EQ(StatusCode::OK_200, res->status);
  13664. ASSERT_TRUE(client_cert_verified);
  13665. EXPECT_EQ("success", res->body);
  13666. }
  13667. #endif
  13668. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13669. // backends
  13670. #ifdef CPPHTTPLIB_SSL_ENABLED
  13671. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13672. using namespace httplib::tls;
  13673. // Test that when client CA cert file is provided,
  13674. // the server properly requests and validates client certificates
  13675. // Create a server with client authentication
  13676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13677. ASSERT_TRUE(svr.is_valid());
  13678. bool handler_called = false;
  13679. svr.Get("/test", [&](const Request &req, Response &res) {
  13680. handler_called = true;
  13681. // Verify that a client certificate was provided
  13682. auto cert = req.peer_cert();
  13683. ASSERT_TRUE(static_cast<bool>(cert));
  13684. // Get the issuer name
  13685. std::string issuer_str = cert.issuer_name();
  13686. ASSERT_FALSE(issuer_str.empty());
  13687. // The client certificate should be issued by our test CA
  13688. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13689. res.set_content("authenticated", "text/plain");
  13690. });
  13691. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13692. auto se = detail::scope_exit([&] {
  13693. svr.stop();
  13694. t.join();
  13695. ASSERT_FALSE(svr.is_running());
  13696. });
  13697. svr.wait_until_ready();
  13698. // Connect with a client certificate issued by the CA
  13699. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13700. cli.enable_server_certificate_verification(false);
  13701. cli.set_connection_timeout(30);
  13702. auto res = cli.Get("/test");
  13703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13704. ASSERT_EQ(StatusCode::OK_200, res->status);
  13705. ASSERT_TRUE(handler_called);
  13706. EXPECT_EQ("authenticated", res->body);
  13707. }
  13708. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13709. using namespace httplib::tls;
  13710. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13711. ASSERT_TRUE(svr.is_valid());
  13712. svr.Get("/test", [](const Request &, Response &res) {
  13713. res.set_content("ok", "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. });
  13720. svr.wait_until_ready();
  13721. SSLClient cli(HOST, PORT);
  13722. cli.enable_server_certificate_verification(false);
  13723. cli.set_connection_timeout(30);
  13724. bool cert_checked = false;
  13725. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13726. if (ctx.cert) {
  13727. auto sans = ctx.sans();
  13728. // Test certificate may or may not have SANs - just verify the API
  13729. // works If SANs exist, verify the types are valid
  13730. for (const auto &san : sans) {
  13731. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13732. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13733. san.type == SanType::OTHER);
  13734. EXPECT_FALSE(san.value.empty());
  13735. }
  13736. cert_checked = true;
  13737. }
  13738. return true;
  13739. });
  13740. auto res = cli.Get("/test");
  13741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13742. EXPECT_TRUE(cert_checked);
  13743. }
  13744. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13745. using namespace httplib::tls;
  13746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13747. ASSERT_TRUE(svr.is_valid());
  13748. svr.Get("/test", [](const Request &, Response &res) {
  13749. res.set_content("ok", "text/plain");
  13750. });
  13751. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13752. auto se = detail::scope_exit([&] {
  13753. svr.stop();
  13754. t.join();
  13755. });
  13756. svr.wait_until_ready();
  13757. SSLClient cli(HOST, PORT);
  13758. cli.enable_server_certificate_verification(false);
  13759. cli.set_connection_timeout(30);
  13760. bool validity_checked = false;
  13761. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13762. if (ctx.cert) {
  13763. time_t not_before = 0, not_after = 0;
  13764. bool result = ctx.validity(not_before, not_after);
  13765. EXPECT_TRUE(result);
  13766. // Verify that not_before < now < not_after for a valid cert
  13767. time_t now = time(nullptr);
  13768. EXPECT_LT(not_before, now);
  13769. EXPECT_GT(not_after, now);
  13770. validity_checked = true;
  13771. }
  13772. return true;
  13773. });
  13774. auto res = cli.Get("/test");
  13775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13776. EXPECT_TRUE(validity_checked);
  13777. }
  13778. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13779. using namespace httplib::tls;
  13780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13781. ASSERT_TRUE(svr.is_valid());
  13782. svr.Get("/test", [](const Request &, Response &res) {
  13783. res.set_content("ok", "text/plain");
  13784. });
  13785. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13786. auto se = detail::scope_exit([&] {
  13787. svr.stop();
  13788. t.join();
  13789. });
  13790. svr.wait_until_ready();
  13791. SSLClient cli(HOST, PORT);
  13792. cli.enable_server_certificate_verification(false);
  13793. cli.set_connection_timeout(30);
  13794. bool serial_checked = false;
  13795. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13796. if (ctx.cert) {
  13797. std::string serial = ctx.serial();
  13798. EXPECT_FALSE(serial.empty());
  13799. // Serial should be a hex string
  13800. for (char c : serial) {
  13801. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13802. (c >= 'a' && c <= 'f'));
  13803. }
  13804. serial_checked = true;
  13805. }
  13806. return true;
  13807. });
  13808. auto res = cli.Get("/test");
  13809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13810. EXPECT_TRUE(serial_checked);
  13811. }
  13812. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13813. // Test 1: Valid CA file - no error should be recorded
  13814. {
  13815. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13816. CLIENT_CA_CERT_FILE);
  13817. ASSERT_TRUE(svr.is_valid());
  13818. // With valid setup, last_ssl_error should be 0
  13819. EXPECT_EQ(0, svr.ssl_last_error());
  13820. }
  13821. // Test 2: Invalid CA file content
  13822. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13823. {
  13824. // Create a temporary file with completely invalid content
  13825. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13826. {
  13827. std::ofstream ofs(temp_invalid_ca);
  13828. ofs << "This is not a certificate file at all\n";
  13829. ofs << "Just plain text content\n";
  13830. }
  13831. // Create server with invalid CA file
  13832. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13833. // Clean up temporary file
  13834. std::remove(temp_invalid_ca);
  13835. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13836. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13837. // Note: SSL_CTX_load_verify_locations typically fails first,
  13838. // but our error handling code path is still exercised
  13839. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13840. }
  13841. }
  13842. TEST(VerifyCallbackTest, VerifyContextFields) {
  13843. using namespace httplib::tls;
  13844. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13845. ASSERT_TRUE(svr.is_valid());
  13846. svr.Get("/test", [](const Request &, Response &res) {
  13847. res.set_content("ok", "text/plain");
  13848. });
  13849. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13850. auto se = detail::scope_exit([&] {
  13851. svr.stop();
  13852. t.join();
  13853. });
  13854. svr.wait_until_ready();
  13855. SSLClient cli(HOST, PORT);
  13856. cli.enable_server_certificate_verification(false);
  13857. cli.set_connection_timeout(30);
  13858. int callback_count = 0;
  13859. bool saw_leaf_cert = false;
  13860. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13861. if (ctx.cert) {
  13862. callback_count++;
  13863. // We should see at least one certificate (the leaf)
  13864. std::string cn = ctx.subject_cn();
  13865. if (!cn.empty()) { saw_leaf_cert = true; }
  13866. // Verify context fields are populated
  13867. EXPECT_NE(ctx.session, nullptr);
  13868. EXPECT_GE(ctx.depth, 0);
  13869. }
  13870. return true;
  13871. });
  13872. auto res = cli.Get("/test");
  13873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13874. EXPECT_GT(callback_count, 0);
  13875. EXPECT_TRUE(saw_leaf_cert);
  13876. }
  13877. // A verifier belongs to the client that set it, not to the thread that set it.
  13878. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13879. using namespace httplib::tls;
  13880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13881. ASSERT_TRUE(svr.is_valid());
  13882. svr.Get("/test", [](const Request &, Response &res) {
  13883. res.set_content("ok", "text/plain");
  13884. });
  13885. auto port = svr.bind_to_any_port(HOST);
  13886. thread t([&]() { svr.listen_after_bind(); });
  13887. auto se = detail::scope_exit([&] {
  13888. svr.stop();
  13889. t.join();
  13890. });
  13891. svr.wait_until_ready();
  13892. auto rejecting_calls = 0;
  13893. SSLClient rejecting(HOST, port);
  13894. rejecting.enable_server_certificate_verification(false);
  13895. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13896. rejecting_calls++;
  13897. return false;
  13898. });
  13899. auto accepting_calls = 0;
  13900. SSLClient accepting(HOST, port);
  13901. accepting.enable_server_certificate_verification(false);
  13902. // Set on another thread than the requests below.
  13903. thread([&]() {
  13904. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13905. accepting_calls++;
  13906. return true;
  13907. });
  13908. }).join();
  13909. // Requested on another thread than the verifier was set on.
  13910. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13911. EXPECT_GT(rejecting_calls, 0);
  13912. auto res = accepting.Get("/test");
  13913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13914. EXPECT_GT(accepting_calls, 0);
  13915. }
  13916. // VerifyContext::session is the same handle the other tls:: functions take.
  13917. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13918. using namespace httplib::tls;
  13919. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13920. ASSERT_TRUE(svr.is_valid());
  13921. svr.Get("/test", [](const Request &, Response &res) {
  13922. res.set_content("ok", "text/plain");
  13923. });
  13924. auto port = svr.bind_to_any_port(HOST);
  13925. thread t([&]() { svr.listen_after_bind(); });
  13926. auto se = detail::scope_exit([&] {
  13927. svr.stop();
  13928. t.join();
  13929. });
  13930. svr.wait_until_ready();
  13931. SSLClient cli(HOST, port);
  13932. cli.enable_server_certificate_verification(false);
  13933. session_t verifier_session = nullptr;
  13934. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13935. verifier_session = ctx.session;
  13936. return true;
  13937. });
  13938. session_t session_verifier_session = nullptr;
  13939. cli.set_session_verifier([&](session_t session) {
  13940. session_verifier_session = session;
  13941. return SSLVerifierResponse::NoDecisionMade;
  13942. });
  13943. auto res = cli.Get("/test");
  13944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13945. EXPECT_NE(nullptr, verifier_session);
  13946. EXPECT_EQ(session_verifier_session, verifier_session);
  13947. }
  13948. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13949. using httplib::tls::TlsError;
  13950. // Test that verify_error_to_string returns empty for success
  13951. std::string success_str = TlsError::verify_error_to_string(0);
  13952. EXPECT_TRUE(success_str.empty());
  13953. // Test that verify_error_to_string returns non-empty for error codes
  13954. // Using a common error code (certificate expired)
  13955. std::string error_str =
  13956. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13957. EXPECT_FALSE(error_str.empty());
  13958. }
  13959. TEST(SessionVerifierTest, CertificateAccepted) {
  13960. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13961. ASSERT_TRUE(svr.is_valid());
  13962. svr.Get("/test", [](const Request &, Response &res) {
  13963. res.set_content("ok", "text/plain");
  13964. });
  13965. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13966. auto se = detail::scope_exit([&] {
  13967. svr.stop();
  13968. t.join();
  13969. });
  13970. svr.wait_until_ready();
  13971. SSLClient cli(HOST, PORT);
  13972. cli.enable_server_certificate_verification(false);
  13973. cli.set_connection_timeout(30);
  13974. bool callback_called = false;
  13975. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13976. EXPECT_NE(session, nullptr);
  13977. callback_called = true;
  13978. return SSLVerifierResponse::CertificateAccepted;
  13979. });
  13980. auto res = cli.Get("/test");
  13981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13982. EXPECT_EQ(200, res->status);
  13983. EXPECT_TRUE(callback_called);
  13984. }
  13985. TEST(SessionVerifierTest, CertificateRejected) {
  13986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13987. ASSERT_TRUE(svr.is_valid());
  13988. svr.Get("/test", [](const Request &, Response &res) {
  13989. res.set_content("ok", "text/plain");
  13990. });
  13991. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13992. auto se = detail::scope_exit([&] {
  13993. svr.stop();
  13994. t.join();
  13995. });
  13996. svr.wait_until_ready();
  13997. SSLClient cli(HOST, PORT);
  13998. cli.enable_server_certificate_verification(false);
  13999. cli.set_connection_timeout(30);
  14000. bool callback_called = false;
  14001. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14002. EXPECT_NE(session, nullptr);
  14003. callback_called = true;
  14004. return SSLVerifierResponse::CertificateRejected;
  14005. });
  14006. auto res = cli.Get("/test");
  14007. EXPECT_FALSE(res);
  14008. EXPECT_TRUE(callback_called);
  14009. }
  14010. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14012. ASSERT_TRUE(svr.is_valid());
  14013. svr.Get("/test", [](const Request &, Response &res) {
  14014. res.set_content("ok", "text/plain");
  14015. });
  14016. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14017. auto se = detail::scope_exit([&] {
  14018. svr.stop();
  14019. t.join();
  14020. });
  14021. svr.wait_until_ready();
  14022. // NoDecisionMade with verification disabled should succeed (no default check)
  14023. SSLClient cli(HOST, PORT);
  14024. cli.enable_server_certificate_verification(false);
  14025. cli.set_connection_timeout(30);
  14026. bool callback_called = false;
  14027. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14028. EXPECT_NE(session, nullptr);
  14029. callback_called = true;
  14030. return SSLVerifierResponse::NoDecisionMade;
  14031. });
  14032. auto res = cli.Get("/test");
  14033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14034. EXPECT_EQ(200, res->status);
  14035. EXPECT_TRUE(callback_called);
  14036. }
  14037. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14038. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14039. ASSERT_TRUE(svr.is_valid());
  14040. svr.Get("/test", [](const Request &, Response &res) {
  14041. res.set_content("ok", "text/plain");
  14042. });
  14043. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14044. auto se = detail::scope_exit([&] {
  14045. svr.stop();
  14046. t.join();
  14047. });
  14048. svr.wait_until_ready();
  14049. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14050. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14051. // so we only check that the request fails, not whether the callback was
  14052. // called.
  14053. SSLClient cli(HOST, PORT);
  14054. cli.enable_server_certificate_verification(true);
  14055. cli.set_connection_timeout(30);
  14056. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14057. EXPECT_NE(session, nullptr);
  14058. return SSLVerifierResponse::NoDecisionMade;
  14059. });
  14060. auto res = cli.Get("/test");
  14061. EXPECT_FALSE(res);
  14062. }
  14063. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14064. // Test SSL server using PemMemory constructor with client CA certificates
  14065. // Read PEM files
  14066. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14067. read_file(SERVER_CERT_FILE, server_cert_pem);
  14068. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14069. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14070. // Create SSLServer with PemMemory constructor including client CA
  14071. SSLServer::PemMemory server_pem = {
  14072. server_cert_pem.c_str(),
  14073. server_cert_pem.size(),
  14074. server_key_pem.c_str(),
  14075. server_key_pem.size(),
  14076. client_ca_pem.c_str(),
  14077. client_ca_pem.size(),
  14078. nullptr // no password for server key
  14079. };
  14080. SSLServer svr(server_pem);
  14081. ASSERT_TRUE(svr.is_valid());
  14082. // No SSL error should be recorded for valid setup
  14083. EXPECT_EQ(0, svr.ssl_last_error());
  14084. // Set up server endpoints
  14085. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14086. res.set_content("ok", "text/plain");
  14087. });
  14088. // Start server in a thread
  14089. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14090. svr.wait_until_ready();
  14091. // Connect with client certificate (using constructor with paths)
  14092. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14093. cli.enable_server_certificate_verification(false);
  14094. auto res = cli.Get("/test-pem-ca");
  14095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14096. EXPECT_EQ(200, res->status);
  14097. EXPECT_EQ("ok", res->body);
  14098. svr.stop();
  14099. server_thread.join();
  14100. }
  14101. #endif
  14102. #ifdef _WIN32
  14103. TEST(CleanupTest, WSACleanup) {
  14104. int ret = WSACleanup();
  14105. ASSERT_EQ(0, ret);
  14106. }
  14107. #endif
  14108. #ifndef CPPHTTPLIB_SSL_ENABLED
  14109. TEST(NoSSLSupport, SimpleInterface) {
  14110. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14111. }
  14112. #endif
  14113. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14114. TEST(InvalidScheme, SimpleInterface) {
  14115. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14116. }
  14117. #endif
  14118. TEST(NoScheme, SimpleInterface) {
  14119. Client cli("yahoo.com:80");
  14120. ASSERT_TRUE(cli.is_valid());
  14121. }
  14122. TEST(SendAPI, SimpleInterface_Online) {
  14123. Client cli("http://yahoo.com");
  14124. Request req;
  14125. req.method = "GET";
  14126. req.path = "/";
  14127. auto res = cli.send(req);
  14128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14129. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14130. }
  14131. TEST(SendAPI, WithParamsInRequest) {
  14132. Server svr;
  14133. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14134. EXPECT_TRUE(req.has_param("test"));
  14135. EXPECT_EQ("test_value", req.get_param_value("test"));
  14136. });
  14137. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14138. auto se = detail::scope_exit([&] {
  14139. svr.stop();
  14140. t.join();
  14141. ASSERT_FALSE(svr.is_running());
  14142. });
  14143. svr.wait_until_ready();
  14144. Client cli(HOST, PORT);
  14145. {
  14146. Request req;
  14147. req.method = "GET";
  14148. req.path = "/";
  14149. req.params.emplace("test", "test_value");
  14150. auto res = cli.send(req);
  14151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14152. }
  14153. {
  14154. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14156. }
  14157. }
  14158. TEST(ClientImplMethods, GetSocketTest) {
  14159. httplib::Server svr;
  14160. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14161. res.status = StatusCode::OK_200;
  14162. });
  14163. auto port = svr.bind_to_any_port("127.0.0.1");
  14164. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14165. auto se = detail::scope_exit([&] {
  14166. svr.stop();
  14167. thread.join();
  14168. ASSERT_FALSE(svr.is_running());
  14169. });
  14170. svr.wait_until_ready();
  14171. {
  14172. httplib::Client cli("127.0.0.1", port);
  14173. cli.set_keep_alive(true);
  14174. // Use the behavior of cpp-httplib of opening the connection
  14175. // only when the first request happens. If that changes,
  14176. // this test would be obsolete.
  14177. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14178. // This also implicitly tests the server. But other tests would fail much
  14179. // earlier than this one to be considered.
  14180. auto res = cli.Get("/");
  14181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14182. EXPECT_EQ(StatusCode::OK_200, res->status);
  14183. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14184. }
  14185. }
  14186. #ifdef CPPHTTPLIB_SSL_ENABLED
  14187. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14188. Client cli("http://yahoo.com");
  14189. auto res = cli.Get("/");
  14190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14191. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14192. cli.set_follow_location(true);
  14193. res = cli.Get("/");
  14194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14195. EXPECT_EQ(StatusCode::OK_200, res->status);
  14196. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14197. }
  14198. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14199. Client cli("https://yahoo.com");
  14200. auto res = cli.Get("/");
  14201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14202. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14203. cli.set_follow_location(true);
  14204. res = cli.Get("/");
  14205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14206. EXPECT_EQ(StatusCode::OK_200, res->status);
  14207. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14208. }
  14209. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14210. Client cli("https://yahoo.com");
  14211. auto res = cli.Get("/");
  14212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14213. ASSERT_FALSE(!res);
  14214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14215. ASSERT_FALSE(res == nullptr);
  14216. ASSERT_TRUE(res != nullptr);
  14217. EXPECT_EQ(Error::Success, res.error());
  14218. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14219. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14220. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14221. cli.set_follow_location(true);
  14222. res = cli.Get("/");
  14223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14224. EXPECT_EQ(Error::Success, res.error());
  14225. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14226. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14227. EXPECT_EQ(StatusCode::OK_200, res->status);
  14228. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14229. }
  14230. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14231. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14232. Client cli("https://cdnjs.cloudflare.com");
  14233. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14234. Headers{{"Accept-Encoding", "br"}});
  14235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14236. EXPECT_EQ(StatusCode::OK_200, res->status);
  14237. EXPECT_EQ(287630U, res->body.size());
  14238. EXPECT_EQ("application/javascript; charset=utf-8",
  14239. res->get_header_value("Content-Type"));
  14240. }
  14241. #endif
  14242. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14243. #undef REDIR_HOST // Silence compiler warning
  14244. #define REDIR_HOST "https://httpbingo.org"
  14245. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14246. Client cli(REDIR_HOST);
  14247. cli.set_follow_location(true);
  14248. auto res =
  14249. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14251. EXPECT_EQ(StatusCode::OK_200, res->status);
  14252. }
  14253. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14254. Client cli(REDIR_HOST);
  14255. cli.set_follow_location(true);
  14256. Params params;
  14257. params.emplace("url", "http://example.com");
  14258. params.emplace("status_code", "302");
  14259. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14261. EXPECT_EQ(StatusCode::OK_200, res->status);
  14262. }
  14263. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14264. Client cli(REDIR_HOST);
  14265. cli.set_follow_location(true);
  14266. Params params;
  14267. params.emplace("url", "http://example.com");
  14268. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14270. EXPECT_EQ(StatusCode::OK_200, res->status);
  14271. }
  14272. TEST(HttpToHttpsRedirectTest, CertFile) {
  14273. auto ssl_port = PORT + 1;
  14274. Server svr;
  14275. ASSERT_TRUE(svr.is_valid());
  14276. svr.Get("/index", [&](const Request &, Response &res) {
  14277. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14278. "/index");
  14279. svr.stop();
  14280. });
  14281. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14282. ASSERT_TRUE(ssl_svr.is_valid());
  14283. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14284. res.set_content("test", "text/plain");
  14285. ssl_svr.stop();
  14286. });
  14287. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14288. thread t2 =
  14289. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14290. auto se = detail::scope_exit([&] {
  14291. t2.join();
  14292. t.join();
  14293. ASSERT_FALSE(svr.is_running());
  14294. });
  14295. svr.wait_until_ready();
  14296. ssl_svr.wait_until_ready();
  14297. Client cli("127.0.0.1", PORT);
  14298. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14299. cli.enable_server_certificate_verification(true);
  14300. cli.set_follow_location(true);
  14301. cli.set_connection_timeout(30);
  14302. auto res = cli.Get("/index");
  14303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14304. ASSERT_EQ(StatusCode::OK_200, res->status);
  14305. }
  14306. TEST(SSLClientRedirectTest, CertFile) {
  14307. auto ssl_port = PORT + 1;
  14308. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14309. ASSERT_TRUE(ssl_svr1.is_valid());
  14310. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14311. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14312. "/index");
  14313. ssl_svr1.stop();
  14314. });
  14315. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14316. ASSERT_TRUE(ssl_svr2.is_valid());
  14317. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14318. res.set_content("test", "text/plain");
  14319. ssl_svr2.stop();
  14320. });
  14321. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14322. thread t2 =
  14323. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14324. auto se = detail::scope_exit([&] {
  14325. t2.join();
  14326. t.join();
  14327. ASSERT_FALSE(ssl_svr1.is_running());
  14328. });
  14329. ssl_svr1.wait_until_ready();
  14330. ssl_svr2.wait_until_ready();
  14331. SSLClient cli("127.0.0.1", PORT);
  14332. std::string cert;
  14333. read_file(SERVER_CERT2_FILE, cert);
  14334. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14335. cli.enable_server_certificate_verification(true);
  14336. cli.set_follow_location(true);
  14337. cli.set_connection_timeout(30);
  14338. auto res = cli.Get("/index");
  14339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14340. ASSERT_EQ(StatusCode::OK_200, res->status);
  14341. }
  14342. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14343. // another port, so the client follows it with a new client.
  14344. static Result GetThroughTlsRedirectToDifferentPort(
  14345. const std::function<void(SSLClient &)> &setup,
  14346. const char *target_cert = SERVER_CERT2_FILE) {
  14347. auto ssl_port = PORT + 1;
  14348. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14349. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14350. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14351. "/index");
  14352. });
  14353. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14354. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14355. res.set_content("test", "text/plain");
  14356. });
  14357. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14358. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14359. auto se = detail::scope_exit([&] {
  14360. ssl_svr2.stop();
  14361. ssl_svr1.stop();
  14362. t2.join();
  14363. t.join();
  14364. });
  14365. ssl_svr1.wait_until_ready();
  14366. ssl_svr2.wait_until_ready();
  14367. SSLClient cli("127.0.0.1", PORT);
  14368. cli.set_follow_location(true);
  14369. cli.set_connection_timeout(30);
  14370. setup(cli);
  14371. return cli.Get("/index");
  14372. }
  14373. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14374. auto calls = 0;
  14375. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14376. cli.enable_server_certificate_verification(false);
  14377. // Accept the first server only.
  14378. cli.set_session_verifier([&](tls::session_t) {
  14379. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14380. : SSLVerifierResponse::CertificateRejected;
  14381. });
  14382. });
  14383. EXPECT_FALSE(res);
  14384. EXPECT_EQ(2, calls);
  14385. }
  14386. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14387. std::string pinned;
  14388. auto res = GetThroughTlsRedirectToDifferentPort(
  14389. [&](SSLClient &cli) {
  14390. cli.enable_server_certificate_verification(false);
  14391. // Pin the first certificate seen.
  14392. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14393. if (pinned.empty()) { pinned = ctx.serial(); }
  14394. return ctx.serial() == pinned;
  14395. });
  14396. },
  14397. // A certificate other than the first server's.
  14398. SERVER_CERT_FILE);
  14399. EXPECT_FALSE(res);
  14400. EXPECT_FALSE(pinned.empty());
  14401. }
  14402. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14403. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14404. std::string cert;
  14405. read_file(SERVER_CERT2_FILE, cert);
  14406. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14407. });
  14408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14409. EXPECT_EQ(StatusCode::OK_200, res->status);
  14410. }
  14411. #endif
  14412. #ifdef CPPHTTPLIB_SSL_ENABLED
  14413. // Test that set_ca_cert_store() skips system certs (consistent with
  14414. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14415. // should be trusted - system certs should NOT be loaded.
  14416. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14417. // Load a specific cert that is NOT a system CA cert
  14418. std::string cert;
  14419. read_file(SERVER_CERT2_FILE, cert);
  14420. SSLClient cli("google.com");
  14421. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14422. cli.enable_server_certificate_verification(true);
  14423. // This should FAIL because:
  14424. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14425. // 2. System certs should NOT be loaded when custom store is set
  14426. // If system certs WERE loaded, this would succeed
  14427. auto res = cli.Get("/");
  14428. ASSERT_FALSE(res);
  14429. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14430. }
  14431. // Same as above, but through the native store handle path. Regression test:
  14432. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14433. // merged system certs into the user-provided store.
  14434. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14435. std::string cert;
  14436. read_file(SERVER_CERT2_FILE, cert);
  14437. SSLClient cli("google.com");
  14438. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14439. cli.enable_server_certificate_verification(true);
  14440. auto res = cli.Get("/");
  14441. ASSERT_FALSE(res);
  14442. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14443. }
  14444. // A custom store set via the native handle must still verify a server whose
  14445. // cert it does contain.
  14446. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14447. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14448. ASSERT_TRUE(svr.is_valid());
  14449. svr.Get("/test", [&](const Request &, Response &res) {
  14450. res.set_content("test", "text/plain");
  14451. });
  14452. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14453. auto se = detail::scope_exit([&] {
  14454. svr.stop();
  14455. t.join();
  14456. ASSERT_FALSE(svr.is_running());
  14457. });
  14458. svr.wait_until_ready();
  14459. SSLClient cli("127.0.0.1", PORT);
  14460. std::string cert;
  14461. read_file(SERVER_CERT2_FILE, cert);
  14462. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14463. cli.enable_server_certificate_verification(true);
  14464. cli.set_connection_timeout(30);
  14465. auto res = cli.Get("/test");
  14466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14467. ASSERT_EQ(StatusCode::OK_200, res->status);
  14468. }
  14469. // CA certs loaded through the universal Client must be transferred to the
  14470. // client created internally for following an HTTPS redirect. Regression test:
  14471. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14472. // the CA data for redirect transfer.
  14473. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14474. auto ssl_port = PORT + 1;
  14475. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14476. ASSERT_TRUE(ssl_svr1.is_valid());
  14477. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14478. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14479. "/index");
  14480. });
  14481. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14482. ASSERT_TRUE(ssl_svr2.is_valid());
  14483. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14484. res.set_content("test", "text/plain");
  14485. });
  14486. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14487. thread t2 =
  14488. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14489. auto se = detail::scope_exit([&] {
  14490. ssl_svr2.stop();
  14491. ssl_svr1.stop();
  14492. t2.join();
  14493. t.join();
  14494. ASSERT_FALSE(ssl_svr1.is_running());
  14495. });
  14496. ssl_svr1.wait_until_ready();
  14497. ssl_svr2.wait_until_ready();
  14498. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14499. std::string cert;
  14500. read_file(SERVER_CERT2_FILE, cert);
  14501. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14502. cli.enable_server_certificate_verification(true);
  14503. cli.set_follow_location(true);
  14504. cli.set_connection_timeout(30);
  14505. auto res = cli.Get("/index");
  14506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14507. ASSERT_EQ(StatusCode::OK_200, res->status);
  14508. }
  14509. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14510. // so a host signed by a system CA verifies even though a custom CA is set
  14511. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14512. std::string cert;
  14513. read_file(SERVER_CERT2_FILE, cert);
  14514. SSLClient cli("google.com");
  14515. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14516. cli.enable_system_ca(true);
  14517. cli.enable_server_certificate_verification(true);
  14518. auto res = cli.Get("/");
  14519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14520. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14521. }
  14522. // The custom CA remains effective when combined with the system CA
  14523. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14524. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14525. ASSERT_TRUE(svr.is_valid());
  14526. svr.Get("/test", [&](const Request &, Response &res) {
  14527. res.set_content("test", "text/plain");
  14528. });
  14529. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14530. auto se = detail::scope_exit([&] {
  14531. svr.stop();
  14532. t.join();
  14533. ASSERT_FALSE(svr.is_running());
  14534. });
  14535. svr.wait_until_ready();
  14536. SSLClient cli("127.0.0.1", PORT);
  14537. std::string cert;
  14538. read_file(SERVER_CERT2_FILE, cert);
  14539. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14540. cli.enable_system_ca(true);
  14541. cli.enable_server_certificate_verification(true);
  14542. cli.set_connection_timeout(30);
  14543. auto res = cli.Get("/test");
  14544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14545. ASSERT_EQ(StatusCode::OK_200, res->status);
  14546. }
  14547. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14548. // skip chain verification entirely (only the certificate identity was
  14549. // checked), so a server presenting an untrusted certificate with a matching
  14550. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14551. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14552. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14553. ASSERT_TRUE(svr.is_valid());
  14554. svr.Get("/test", [&](const Request &, Response &res) {
  14555. res.set_content("test", "text/plain");
  14556. });
  14557. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14558. auto se = detail::scope_exit([&] {
  14559. svr.stop();
  14560. t.join();
  14561. ASSERT_FALSE(svr.is_running());
  14562. });
  14563. svr.wait_until_ready();
  14564. SSLClient cli("127.0.0.1", PORT);
  14565. std::string cert;
  14566. // A trusted CA that did not sign the server certificate. The server cert
  14567. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14568. // this connection.
  14569. read_file(CLIENT_CA_CERT_FILE, cert);
  14570. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14571. cli.enable_server_certificate_verification(true);
  14572. cli.set_connection_timeout(30);
  14573. auto res = cli.Get("/test");
  14574. ASSERT_FALSE(res);
  14575. }
  14576. // enable_system_ca(false) prevents system CA loading entirely
  14577. TEST(SSLClientTest, DisableSystemCa_Online) {
  14578. SSLClient cli("google.com");
  14579. cli.enable_system_ca(false);
  14580. cli.enable_server_certificate_verification(true);
  14581. auto res = cli.Get("/");
  14582. ASSERT_FALSE(res);
  14583. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14584. // itself when the CA chain is empty
  14585. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14586. res.error() == Error::SSLConnection);
  14587. }
  14588. // The universal Client forwards enable_system_ca()
  14589. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14590. std::string cert;
  14591. read_file(SERVER_CERT2_FILE, cert);
  14592. Client cli("https://google.com");
  14593. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14594. cli.enable_system_ca(true);
  14595. cli.enable_server_certificate_verification(true);
  14596. auto res = cli.Get("/");
  14597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14598. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14599. }
  14600. // The system CA policy must carry over to the client created internally for
  14601. // following a cross-host HTTPS redirect
  14602. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14603. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14604. ASSERT_TRUE(svr.is_valid());
  14605. svr.Get("/index", [&](const Request &, Response &res) {
  14606. res.set_redirect("https://www.google.com/");
  14607. });
  14608. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14609. auto se = detail::scope_exit([&] {
  14610. svr.stop();
  14611. t.join();
  14612. ASSERT_FALSE(svr.is_running());
  14613. });
  14614. svr.wait_until_ready();
  14615. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14616. std::string cert;
  14617. read_file(SERVER_CERT2_FILE, cert);
  14618. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14619. cli.enable_system_ca(true);
  14620. cli.enable_server_certificate_verification(true);
  14621. cli.set_follow_location(true);
  14622. cli.set_connection_timeout(30);
  14623. // Receiving any response proves the redirect client completed the TLS
  14624. // handshake with a system-CA-signed host
  14625. auto res = cli.Get("/index");
  14626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14627. }
  14628. TEST(MultipartFormDataTest, LargeData) {
  14629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14630. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14631. const ContentReader &content_reader) {
  14632. if (req.is_multipart_form_data()) {
  14633. std::vector<FormData> items;
  14634. content_reader(
  14635. [&](const FormData &file) {
  14636. items.push_back(file);
  14637. return true;
  14638. },
  14639. [&](const char *data, size_t data_length) {
  14640. items.back().content.append(data, data_length);
  14641. return true;
  14642. });
  14643. EXPECT_TRUE(std::string(items[0].name) == "document");
  14644. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14645. EXPECT_TRUE(items[0].filename == "2MB_data");
  14646. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14647. EXPECT_TRUE(items[1].name == "hello");
  14648. EXPECT_TRUE(items[1].content == "world");
  14649. EXPECT_TRUE(items[1].filename == "");
  14650. EXPECT_TRUE(items[1].content_type == "");
  14651. } else {
  14652. std::string body;
  14653. content_reader([&](const char *data, size_t data_length) {
  14654. body.append(data, data_length);
  14655. return true;
  14656. });
  14657. }
  14658. });
  14659. auto port = svr.bind_to_any_port(HOST);
  14660. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14661. auto se = detail::scope_exit([&] {
  14662. svr.stop();
  14663. t.join();
  14664. ASSERT_FALSE(svr.is_running());
  14665. });
  14666. svr.wait_until_ready();
  14667. {
  14668. std::string data(1024 * 1024 * 2, '.');
  14669. std::stringstream buffer;
  14670. buffer << data;
  14671. SSLClient cli(HOST, port);
  14672. cli.enable_server_certificate_verification(false);
  14673. UploadFormDataItems items{
  14674. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14675. {"hello", "world", "", ""},
  14676. };
  14677. auto res = cli.Post("/post", items);
  14678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14679. ASSERT_EQ(StatusCode::OK_200, res->status);
  14680. }
  14681. }
  14682. TEST(MultipartFormDataTest, DataProviderItems) {
  14683. std::random_device seed_gen;
  14684. std::mt19937 random(seed_gen());
  14685. std::string rand1;
  14686. rand1.resize(1000);
  14687. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14688. std::string rand2;
  14689. rand2.resize(3000);
  14690. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14692. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14693. const ContentReader &content_reader) {
  14694. ASSERT_FALSE(req.is_multipart_form_data());
  14695. std::string body;
  14696. content_reader([&](const char *data, size_t data_length) {
  14697. body.append(data, data_length);
  14698. return true;
  14699. });
  14700. EXPECT_EQ(body, "");
  14701. });
  14702. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14703. const ContentReader &content_reader) {
  14704. ASSERT_TRUE(req.is_multipart_form_data());
  14705. std::vector<FormData> items;
  14706. content_reader(
  14707. [&](const FormData &file) {
  14708. items.push_back(file);
  14709. return true;
  14710. },
  14711. [&](const char *data, size_t data_length) {
  14712. items.back().content.append(data, data_length);
  14713. return true;
  14714. });
  14715. ASSERT_TRUE(items.size() == 2);
  14716. EXPECT_EQ(std::string(items[0].name), "name1");
  14717. EXPECT_EQ(items[0].content, "Testing123");
  14718. EXPECT_EQ(items[0].filename, "filename1");
  14719. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14720. EXPECT_EQ(items[1].name, "name2");
  14721. EXPECT_EQ(items[1].content, "Testing456");
  14722. EXPECT_EQ(items[1].filename, "");
  14723. EXPECT_EQ(items[1].content_type, "");
  14724. });
  14725. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14726. const ContentReader &content_reader) {
  14727. ASSERT_TRUE(req.is_multipart_form_data());
  14728. std::vector<FormData> items;
  14729. content_reader(
  14730. [&](const FormData &file) {
  14731. items.push_back(file);
  14732. return true;
  14733. },
  14734. [&](const char *data, size_t data_length) {
  14735. items.back().content.append(data, data_length);
  14736. return true;
  14737. });
  14738. ASSERT_TRUE(items.size() == 2);
  14739. EXPECT_EQ(items[0].name, "name3");
  14740. EXPECT_EQ(items[0].content, rand1);
  14741. EXPECT_EQ(items[0].filename, "filename3");
  14742. EXPECT_EQ(items[0].content_type, "");
  14743. EXPECT_EQ(items[1].name, "name4");
  14744. EXPECT_EQ(items[1].content, rand2);
  14745. EXPECT_EQ(items[1].filename, "filename4");
  14746. EXPECT_EQ(items[1].content_type, "");
  14747. });
  14748. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14749. const ContentReader &content_reader) {
  14750. ASSERT_TRUE(req.is_multipart_form_data());
  14751. std::vector<FormData> items;
  14752. content_reader(
  14753. [&](const FormData &file) {
  14754. items.push_back(file);
  14755. return true;
  14756. },
  14757. [&](const char *data, size_t data_length) {
  14758. items.back().content.append(data, data_length);
  14759. return true;
  14760. });
  14761. ASSERT_TRUE(items.size() == 4);
  14762. EXPECT_EQ(std::string(items[0].name), "name1");
  14763. EXPECT_EQ(items[0].content, "Testing123");
  14764. EXPECT_EQ(items[0].filename, "filename1");
  14765. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14766. EXPECT_EQ(items[1].name, "name2");
  14767. EXPECT_EQ(items[1].content, "Testing456");
  14768. EXPECT_EQ(items[1].filename, "");
  14769. EXPECT_EQ(items[1].content_type, "");
  14770. EXPECT_EQ(items[2].name, "name3");
  14771. EXPECT_EQ(items[2].content, rand1);
  14772. EXPECT_EQ(items[2].filename, "filename3");
  14773. EXPECT_EQ(items[2].content_type, "");
  14774. EXPECT_EQ(items[3].name, "name4");
  14775. EXPECT_EQ(items[3].content, rand2);
  14776. EXPECT_EQ(items[3].filename, "filename4");
  14777. EXPECT_EQ(items[3].content_type, "");
  14778. });
  14779. auto port = svr.bind_to_any_port("localhost");
  14780. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14781. auto se = detail::scope_exit([&] {
  14782. svr.stop();
  14783. t.join();
  14784. ASSERT_FALSE(svr.is_running());
  14785. });
  14786. svr.wait_until_ready();
  14787. {
  14788. SSLClient cli("localhost", port);
  14789. cli.enable_server_certificate_verification(false);
  14790. UploadFormDataItems items{
  14791. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14792. {"name2", "Testing456", "", ""}, // not a file
  14793. };
  14794. {
  14795. auto res = cli.Post("/post-none", {}, {}, {});
  14796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14797. ASSERT_EQ(StatusCode::OK_200, res->status);
  14798. }
  14799. FormDataProviderItems providers;
  14800. {
  14801. auto res =
  14802. cli.Post("/post-items", {}, items, providers); // empty providers
  14803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14804. ASSERT_EQ(StatusCode::OK_200, res->status);
  14805. }
  14806. providers.push_back({"name3",
  14807. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14808. // test the offset is given correctly at each step
  14809. if (!offset)
  14810. sink.os.write(rand1.data(), 30);
  14811. else if (offset == 30)
  14812. sink.os.write(rand1.data() + 30, 300);
  14813. else if (offset == 330)
  14814. sink.os.write(rand1.data() + 330, 670);
  14815. else if (offset == rand1.size())
  14816. sink.done();
  14817. return true;
  14818. },
  14819. "filename3",
  14820. {}});
  14821. providers.push_back({"name4",
  14822. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14823. // test the offset is given correctly at each step
  14824. if (!offset)
  14825. sink.os.write(rand2.data(), 2000);
  14826. else if (offset == 2000)
  14827. sink.os.write(rand2.data() + 2000, 1);
  14828. else if (offset == 2001)
  14829. sink.os.write(rand2.data() + 2001, 999);
  14830. else if (offset == rand2.size())
  14831. sink.done();
  14832. return true;
  14833. },
  14834. "filename4",
  14835. {}});
  14836. {
  14837. auto res = cli.Post("/post-providers", {}, {}, providers);
  14838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14839. ASSERT_EQ(StatusCode::OK_200, res->status);
  14840. }
  14841. {
  14842. auto res = cli.Post("/post-both", {}, items, providers);
  14843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14844. ASSERT_EQ(StatusCode::OK_200, res->status);
  14845. }
  14846. }
  14847. }
  14848. TEST(MultipartFormDataTest, BadHeader) {
  14849. Server svr;
  14850. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14851. res.set_content("ok", "text/plain");
  14852. });
  14853. thread t = thread([&] { svr.listen(HOST, PORT); });
  14854. auto se = detail::scope_exit([&] {
  14855. svr.stop();
  14856. t.join();
  14857. ASSERT_FALSE(svr.is_running());
  14858. });
  14859. svr.wait_until_ready();
  14860. const std::string body =
  14861. "This is the preamble. It is to be ignored, though it\r\n"
  14862. "is a handy place for composition agents to include an\r\n"
  14863. "explanatory note to non-MIME conformant readers.\r\n"
  14864. "\r\n"
  14865. "\r\n"
  14866. "--simple boundary\r\n"
  14867. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14868. ": BAD...\r\n"
  14869. "\r\n"
  14870. "value1\r\n"
  14871. "--simple boundary\r\n"
  14872. "Content-Disposition: form-data; name=\"field2\"; "
  14873. "filename=\"example.txt\"\r\n"
  14874. "\r\n"
  14875. "value2\r\n"
  14876. "--simple boundary--\r\n"
  14877. "This is the epilogue. It is also to be ignored.\r\n";
  14878. std::string content_type =
  14879. R"(multipart/form-data; boundary="simple boundary")";
  14880. Client cli(HOST, PORT);
  14881. auto res = cli.Post("/post", body, content_type.c_str());
  14882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14883. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14884. }
  14885. TEST(MultipartFormDataTest, WithPreamble) {
  14886. Server svr;
  14887. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14888. res.set_content("ok", "text/plain");
  14889. });
  14890. thread t = thread([&] { svr.listen(HOST, PORT); });
  14891. auto se = detail::scope_exit([&] {
  14892. svr.stop();
  14893. t.join();
  14894. ASSERT_FALSE(svr.is_running());
  14895. });
  14896. svr.wait_until_ready();
  14897. const std::string body =
  14898. "This is the preamble. It is to be ignored, though it\r\n"
  14899. "is a handy place for composition agents to include an\r\n"
  14900. "explanatory note to non-MIME conformant readers.\r\n"
  14901. "\r\n"
  14902. "\r\n"
  14903. "--simple boundary\r\n"
  14904. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14905. "\r\n"
  14906. "value1\r\n"
  14907. "--simple boundary\r\n"
  14908. "Content-Disposition: form-data; name=\"field2\"; "
  14909. "filename=\"example.txt\"\r\n"
  14910. "\r\n"
  14911. "value2\r\n"
  14912. "--simple boundary--\r\n"
  14913. "This is the epilogue. It is also to be ignored.\r\n";
  14914. std::string content_type =
  14915. R"(multipart/form-data; boundary="simple boundary")";
  14916. Client cli(HOST, PORT);
  14917. auto res = cli.Post("/post", body, content_type.c_str());
  14918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14919. EXPECT_EQ(StatusCode::OK_200, res->status);
  14920. }
  14921. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14923. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14924. const ContentReader &content_reader) {
  14925. if (req.is_multipart_form_data()) {
  14926. std::vector<FormData> items;
  14927. content_reader(
  14928. [&](const FormData &file) {
  14929. items.push_back(file);
  14930. return true;
  14931. },
  14932. [&](const char *data, size_t data_length) {
  14933. items.back().content.append(data, data_length);
  14934. return true;
  14935. });
  14936. EXPECT_TRUE(std::string(items[0].name) == "document");
  14937. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14938. EXPECT_TRUE(items[0].filename == "2MB_data");
  14939. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14940. EXPECT_TRUE(items[1].name == "hello");
  14941. EXPECT_TRUE(items[1].content == "world");
  14942. EXPECT_TRUE(items[1].filename == "");
  14943. EXPECT_TRUE(items[1].content_type == "");
  14944. } else {
  14945. std::string body;
  14946. content_reader([&](const char *data, size_t data_length) {
  14947. body.append(data, data_length);
  14948. return true;
  14949. });
  14950. }
  14951. });
  14952. auto port = svr.bind_to_any_port("localhost");
  14953. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14954. auto se = detail::scope_exit([&] {
  14955. svr.stop();
  14956. t.join();
  14957. ASSERT_FALSE(svr.is_running());
  14958. });
  14959. svr.wait_until_ready();
  14960. {
  14961. std::string data(1024 * 1024 * 2, '.');
  14962. std::stringstream buffer;
  14963. buffer << data;
  14964. SSLClient cli("localhost", port);
  14965. cli.enable_server_certificate_verification(false);
  14966. UploadFormDataItems items{
  14967. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14968. {"hello", "world", "", ""},
  14969. };
  14970. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14972. ASSERT_EQ(StatusCode::OK_200, res->status);
  14973. }
  14974. }
  14975. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14976. std::string data(1024 * 1024 * 2, '&');
  14977. std::stringstream buffer;
  14978. buffer << data;
  14979. Client cli("https://localhost:8080");
  14980. UploadFormDataItems items{
  14981. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14982. {"hello", "world", "", ""},
  14983. };
  14984. for (const char &c : " \t\r\n") {
  14985. auto res =
  14986. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14987. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14988. ASSERT_FALSE(res);
  14989. }
  14990. }
  14991. TEST(MultipartFormDataTest, PutFormData) {
  14992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14993. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14994. const ContentReader &content_reader) {
  14995. if (req.is_multipart_form_data()) {
  14996. std::vector<FormData> items;
  14997. content_reader(
  14998. [&](const FormData &file) {
  14999. items.push_back(file);
  15000. return true;
  15001. },
  15002. [&](const char *data, size_t data_length) {
  15003. items.back().content.append(data, data_length);
  15004. return true;
  15005. });
  15006. EXPECT_TRUE(std::string(items[0].name) == "document");
  15007. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15008. EXPECT_TRUE(items[0].filename == "2MB_data");
  15009. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15010. EXPECT_TRUE(items[1].name == "hello");
  15011. EXPECT_TRUE(items[1].content == "world");
  15012. EXPECT_TRUE(items[1].filename == "");
  15013. EXPECT_TRUE(items[1].content_type == "");
  15014. } else {
  15015. std::string body;
  15016. content_reader([&](const char *data, size_t data_length) {
  15017. body.append(data, data_length);
  15018. return true;
  15019. });
  15020. }
  15021. });
  15022. auto port = svr.bind_to_any_port("localhost");
  15023. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15024. auto se = detail::scope_exit([&] {
  15025. svr.stop();
  15026. t.join();
  15027. ASSERT_FALSE(svr.is_running());
  15028. });
  15029. svr.wait_until_ready();
  15030. {
  15031. std::string data(1024 * 1024 * 2, '&');
  15032. std::stringstream buffer;
  15033. buffer << data;
  15034. SSLClient cli("localhost", port);
  15035. cli.enable_server_certificate_verification(false);
  15036. UploadFormDataItems items{
  15037. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15038. {"hello", "world", "", ""},
  15039. };
  15040. auto res = cli.Put("/put", items);
  15041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15042. ASSERT_EQ(StatusCode::OK_200, res->status);
  15043. }
  15044. }
  15045. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15047. svr.Put("/put_customboundary",
  15048. [&](const Request &req, const Response & /*res*/,
  15049. const ContentReader &content_reader) {
  15050. if (req.is_multipart_form_data()) {
  15051. std::vector<FormData> items;
  15052. content_reader(
  15053. [&](const FormData &file) {
  15054. items.push_back(file);
  15055. return true;
  15056. },
  15057. [&](const char *data, size_t data_length) {
  15058. items.back().content.append(data, data_length);
  15059. return true;
  15060. });
  15061. EXPECT_TRUE(std::string(items[0].name) == "document");
  15062. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15063. EXPECT_TRUE(items[0].filename == "2MB_data");
  15064. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15065. EXPECT_TRUE(items[1].name == "hello");
  15066. EXPECT_TRUE(items[1].content == "world");
  15067. EXPECT_TRUE(items[1].filename == "");
  15068. EXPECT_TRUE(items[1].content_type == "");
  15069. } else {
  15070. std::string body;
  15071. content_reader([&](const char *data, size_t data_length) {
  15072. body.append(data, data_length);
  15073. return true;
  15074. });
  15075. }
  15076. });
  15077. auto port = svr.bind_to_any_port("localhost");
  15078. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15079. auto se = detail::scope_exit([&] {
  15080. svr.stop();
  15081. t.join();
  15082. ASSERT_FALSE(svr.is_running());
  15083. });
  15084. svr.wait_until_ready();
  15085. {
  15086. std::string data(1024 * 1024 * 2, '&');
  15087. std::stringstream buffer;
  15088. buffer << data;
  15089. SSLClient cli("localhost", port);
  15090. cli.enable_server_certificate_verification(false);
  15091. UploadFormDataItems items{
  15092. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15093. {"hello", "world", "", ""},
  15094. };
  15095. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15097. ASSERT_EQ(StatusCode::OK_200, res->status);
  15098. }
  15099. }
  15100. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15101. std::string data(1024 * 1024 * 2, '&');
  15102. std::stringstream buffer;
  15103. buffer << data;
  15104. Client cli("https://localhost:8080");
  15105. cli.enable_server_certificate_verification(false);
  15106. UploadFormDataItems items{
  15107. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15108. {"hello", "world", "", ""},
  15109. };
  15110. for (const char &c : " \t\r\n") {
  15111. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15112. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15113. ASSERT_FALSE(res);
  15114. }
  15115. }
  15116. TEST(MultipartFormDataTest, AlternateFilename) {
  15117. auto handled = false;
  15118. Server svr;
  15119. svr.Post("/test", [&](const Request &req, Response &res) {
  15120. ASSERT_EQ(2u, req.form.files.size());
  15121. ASSERT_EQ(1u, req.form.fields.size());
  15122. // Test files
  15123. const auto &file1 = req.form.get_file("file1");
  15124. ASSERT_EQ("file1", file1.name);
  15125. ASSERT_EQ("A.txt", file1.filename);
  15126. ASSERT_EQ("text/plain", file1.content_type);
  15127. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15128. const auto &file2 = req.form.get_file("file2");
  15129. ASSERT_EQ("file2", file2.name);
  15130. ASSERT_EQ("a.html", file2.filename);
  15131. ASSERT_EQ("text/html", file2.content_type);
  15132. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15133. file2.content);
  15134. // Test text field
  15135. const auto &text = req.form.get_field("text");
  15136. ASSERT_EQ("text default", text);
  15137. res.set_content("ok", "text/plain");
  15138. handled = true;
  15139. });
  15140. thread t = thread([&] { svr.listen(HOST, PORT); });
  15141. auto se = detail::scope_exit([&] {
  15142. svr.stop();
  15143. t.join();
  15144. ASSERT_FALSE(svr.is_running());
  15145. ASSERT_TRUE(handled);
  15146. });
  15147. svr.wait_until_ready();
  15148. auto req = "POST /test HTTP/1.1\r\n"
  15149. "Host: localhost\r\n"
  15150. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15151. "Content-Length: 399\r\n"
  15152. "\r\n"
  15153. "----------\r\n"
  15154. "Content-Disposition: form-data; name=\"text\"\r\n"
  15155. "\r\n"
  15156. "text default\r\n"
  15157. "----------\r\n"
  15158. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15159. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15160. "Content-Type: text/plain\r\n"
  15161. "\r\n"
  15162. "Content of a.txt.\r\n"
  15163. "\r\n"
  15164. "----------\r\n"
  15165. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15166. "\"a.html\"\r\n"
  15167. "Content-Type: text/html\r\n"
  15168. "\r\n"
  15169. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15170. "\r\n"
  15171. "------------\r\n";
  15172. ASSERT_TRUE(send_request(1, req));
  15173. }
  15174. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15175. auto handled = false;
  15176. Server svr;
  15177. svr.Post("/test", [&](const Request &req, Response &res) {
  15178. // Case-insensitive "utf-8''" prefix with a long value
  15179. const auto &file = req.form.get_file("file1");
  15180. ASSERT_EQ("file1", file.name);
  15181. // 8000 chars exercises both the Content-Disposition parser and the
  15182. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15183. // Prior to the fix, std::regex_match on this header would cause O(N)
  15184. // stack recursion in libstdc++, leading to SIGSEGV.
  15185. std::string expected_filename(8000, 'A');
  15186. ASSERT_EQ(expected_filename, file.filename);
  15187. res.set_content("ok", "text/plain");
  15188. handled = true;
  15189. });
  15190. thread t = thread([&] { svr.listen(HOST, PORT); });
  15191. auto se = detail::scope_exit([&] {
  15192. svr.stop();
  15193. t.join();
  15194. ASSERT_FALSE(svr.is_running());
  15195. ASSERT_TRUE(handled);
  15196. });
  15197. svr.wait_until_ready();
  15198. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15199. // Regression test for GHSA-qq6v-r583-3h69
  15200. std::string long_filename(8000, 'A');
  15201. std::string body = "----------\r\n"
  15202. "Content-Disposition: form-data; name=\"file1\"; "
  15203. "filename*=\"Utf-8''" +
  15204. long_filename +
  15205. "\"\r\n"
  15206. "\r\n"
  15207. "hello\r\n"
  15208. "------------\r\n";
  15209. auto req = "POST /test HTTP/1.1\r\n"
  15210. "Host: localhost\r\n"
  15211. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15212. "Content-Length: " +
  15213. std::to_string(body.size()) + "\r\n\r\n" + body;
  15214. ASSERT_TRUE(send_request(1, req));
  15215. }
  15216. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15217. auto handled = false;
  15218. Server svr;
  15219. svr.Post("/test", [&](const Request &req, Response &) {
  15220. ASSERT_EQ(2u, req.form.fields.size());
  15221. const auto &text1 = req.form.get_field("text1");
  15222. ASSERT_EQ("text1", text1);
  15223. const auto &text2 = req.form.get_field("text2");
  15224. ASSERT_EQ("text2", text2);
  15225. handled = true;
  15226. });
  15227. thread t = thread([&] { svr.listen(HOST, PORT); });
  15228. auto se = detail::scope_exit([&] {
  15229. svr.stop();
  15230. t.join();
  15231. ASSERT_FALSE(svr.is_running());
  15232. ASSERT_TRUE(handled);
  15233. });
  15234. svr.wait_until_ready();
  15235. auto req = "POST /test HTTP/1.1\r\n"
  15236. "Host: localhost\r\n"
  15237. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15238. "Content-Length: 146\r\n"
  15239. "\r\n----------\r\n"
  15240. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15241. "\r\n"
  15242. "text1"
  15243. "\r\n----------\r\n"
  15244. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15245. "\r\n"
  15246. "text2"
  15247. "\r\n------------";
  15248. std::string response;
  15249. ASSERT_TRUE(send_request(1, req, &response));
  15250. ASSERT_EQ("200", response.substr(9, 3));
  15251. }
  15252. TEST(MultipartFormDataTest, ContentLength) {
  15253. auto handled = false;
  15254. Server svr;
  15255. svr.Post("/test", [&](const Request &req, Response &) {
  15256. ASSERT_EQ(2u, req.form.fields.size());
  15257. const auto &text1 = req.form.get_field("text1");
  15258. ASSERT_EQ("text1", text1);
  15259. const auto &text2 = req.form.get_field("text2");
  15260. ASSERT_EQ("text2", text2);
  15261. handled = true;
  15262. });
  15263. thread t = thread([&] { svr.listen(HOST, PORT); });
  15264. auto se = detail::scope_exit([&] {
  15265. svr.stop();
  15266. t.join();
  15267. ASSERT_FALSE(svr.is_running());
  15268. ASSERT_TRUE(handled);
  15269. });
  15270. svr.wait_until_ready();
  15271. auto req = "POST /test HTTP/1.1\r\n"
  15272. "Host: localhost\r\n"
  15273. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15274. "Content-Length: 167\r\n"
  15275. "\r\n----------\r\n"
  15276. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15277. "Content-Length: 5\r\n"
  15278. "\r\n"
  15279. "text1"
  15280. "\r\n----------\r\n"
  15281. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15282. "\r\n"
  15283. "text2"
  15284. "\r\n------------\r\n";
  15285. std::string response;
  15286. ASSERT_TRUE(send_request(1, req, &response));
  15287. ASSERT_EQ("200", response.substr(9, 3));
  15288. }
  15289. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15290. auto handled = false;
  15291. Server svr;
  15292. svr.Post("/test", [&](const Request &req, Response &) {
  15293. ASSERT_EQ(2u, req.form.fields.size());
  15294. const auto &text1 = req.form.get_field("text1");
  15295. ASSERT_EQ("text1", text1);
  15296. // TODO: Add header access for text fields if needed
  15297. const auto &text2 = req.form.get_field("text2");
  15298. ASSERT_EQ("text2", text2);
  15299. // TODO: Header access for text fields needs to be implemented
  15300. // auto &headers = it->second.headers;
  15301. // ASSERT_EQ(3U, headers.size());
  15302. // auto custom_header = headers.find("x-whatever");
  15303. // ASSERT_TRUE(custom_header != headers.end());
  15304. // ASSERT_NE("customvalue", custom_header->second);
  15305. // ASSERT_EQ("CustomValue", custom_header->second);
  15306. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15307. handled = true;
  15308. });
  15309. thread t = thread([&] { svr.listen(HOST, PORT); });
  15310. auto se = detail::scope_exit([&] {
  15311. svr.stop();
  15312. t.join();
  15313. ASSERT_FALSE(svr.is_running());
  15314. ASSERT_TRUE(handled);
  15315. });
  15316. svr.wait_until_ready();
  15317. auto req = "POST /test HTTP/1.1\r\n"
  15318. "Host: localhost\r\n"
  15319. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15320. "Content-Length: 232\r\n"
  15321. "\r\n----------\r\n"
  15322. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15323. "Content-Length: 5\r\n"
  15324. "X-Test: 1\r\n"
  15325. "\r\n"
  15326. "text1"
  15327. "\r\n----------\r\n"
  15328. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15329. "Content-Type: text/plain\r\n"
  15330. "X-Whatever: CustomValue\r\n"
  15331. "\r\n"
  15332. "text2"
  15333. "\r\n------------\r\n"
  15334. "That should be disregarded. Not even read";
  15335. std::string response;
  15336. ASSERT_TRUE(send_request(1, req, &response));
  15337. ASSERT_EQ("200", response.substr(9, 3));
  15338. }
  15339. TEST(MultipartFormDataTest, LargeHeader) {
  15340. auto handled = false;
  15341. Server svr;
  15342. svr.Post("/test", [&](const Request &req, Response &) {
  15343. ASSERT_EQ(1u, req.form.fields.size());
  15344. const auto &text = req.form.get_field("name1");
  15345. ASSERT_EQ("text1", text);
  15346. handled = true;
  15347. });
  15348. thread t = thread([&] { svr.listen(HOST, PORT); });
  15349. auto se = detail::scope_exit([&] {
  15350. svr.stop();
  15351. t.join();
  15352. ASSERT_FALSE(svr.is_running());
  15353. ASSERT_TRUE(handled);
  15354. });
  15355. svr.wait_until_ready();
  15356. auto boundary = std::string("cpp-httplib-multipart-data");
  15357. std::string content = "--" + boundary +
  15358. "\r\n"
  15359. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15360. "\r\n"
  15361. "text1\r\n"
  15362. "--" +
  15363. boundary + "--\r\n";
  15364. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15365. "Host: localhost\r\n"
  15366. "Content-Type: multipart/form-data;boundary=" +
  15367. boundary +
  15368. "\r\n"
  15369. "Content-Length: " +
  15370. std::to_string(content.size()) +
  15371. "\r\n"
  15372. "Dummy-Header: ";
  15373. std::string header_suffix = "\r\n"
  15374. "\r\n";
  15375. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15376. size_t header_dummy_size =
  15377. read_buff_size -
  15378. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15379. auto header_dummy = std::string(header_dummy_size, '@');
  15380. auto req = header_prefix + header_dummy + header_suffix + content;
  15381. std::string response;
  15382. ASSERT_TRUE(send_request(1, req, &response));
  15383. ASSERT_EQ("200", response.substr(9, 3));
  15384. }
  15385. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15386. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15387. // (not chunked Transfer-Encoding) after the streaming refactor.
  15388. auto handled = false;
  15389. Server svr;
  15390. svr.Post("/upload", [&](const Request &req, Response &res) {
  15391. auto cl_it = req.headers.find("Content-Length");
  15392. EXPECT_TRUE(cl_it != req.headers.end());
  15393. auto te_it = req.headers.find("Transfer-Encoding");
  15394. EXPECT_TRUE(te_it == req.headers.end());
  15395. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15396. res.set_content("ok", "text/plain");
  15397. handled = true;
  15398. });
  15399. auto port = svr.bind_to_any_port(HOST);
  15400. auto t = thread([&] { svr.listen_after_bind(); });
  15401. auto se = detail::scope_exit([&] {
  15402. svr.stop();
  15403. t.join();
  15404. ASSERT_FALSE(svr.is_running());
  15405. ASSERT_TRUE(handled);
  15406. });
  15407. svr.wait_until_ready();
  15408. UploadFormDataItems items = {
  15409. {"field1", "hello", "", "text/plain"},
  15410. {"file1", "world", "test.txt", "application/octet-stream"},
  15411. };
  15412. Client cli(HOST, port);
  15413. auto res = cli.Post("/upload", {}, items);
  15414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15415. EXPECT_EQ(StatusCode::OK_200, res->status);
  15416. }
  15417. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15418. // Verify that make_multipart_content_provider coalesces many small segments
  15419. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15420. constexpr size_t kItemCount = 1000;
  15421. UploadFormDataItems items;
  15422. items.reserve(kItemCount);
  15423. for (size_t i = 0; i < kItemCount; i++) {
  15424. items.push_back(
  15425. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15426. }
  15427. const std::string boundary = "----test-boundary";
  15428. auto content_length = detail::get_multipart_content_length(items, boundary);
  15429. auto provider = detail::make_multipart_content_provider(items, boundary);
  15430. // Drive the provider the same way write_content_with_progress does
  15431. size_t write_count = 0;
  15432. size_t total_bytes = 0;
  15433. DataSink sink;
  15434. size_t offset = 0;
  15435. sink.write = [&](const char *d, size_t l) -> bool {
  15436. (void)d;
  15437. write_count++;
  15438. total_bytes += l;
  15439. offset += l;
  15440. return true;
  15441. };
  15442. sink.is_writable = []() -> bool { return true; };
  15443. while (offset < content_length) {
  15444. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15445. }
  15446. EXPECT_EQ(content_length, total_bytes);
  15447. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15448. // With buffering into 64KB blocks, write_count should be much smaller.
  15449. auto segment_count = 3 * kItemCount + 1;
  15450. EXPECT_LT(write_count, segment_count / 10);
  15451. }
  15452. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15453. // Integration test: send many UploadFormDataItems and verify the server
  15454. // receives all of them correctly (#2410).
  15455. constexpr size_t kItemCount = 500;
  15456. auto handled = false;
  15457. Server svr;
  15458. svr.Post("/upload", [&](const Request &req, Response &res) {
  15459. EXPECT_EQ(kItemCount, req.form.fields.size());
  15460. for (size_t i = 0; i < kItemCount; i++) {
  15461. auto key = "field" + std::to_string(i);
  15462. auto val = "value" + std::to_string(i);
  15463. auto it = req.form.fields.find(key);
  15464. if (it != req.form.fields.end()) {
  15465. EXPECT_EQ(val, it->second.content);
  15466. } else {
  15467. ADD_FAILURE() << "Missing field: " << key;
  15468. }
  15469. }
  15470. res.set_content("ok", "text/plain");
  15471. handled = true;
  15472. });
  15473. auto port = svr.bind_to_any_port(HOST);
  15474. auto t = thread([&] { svr.listen_after_bind(); });
  15475. auto se = detail::scope_exit([&] {
  15476. svr.stop();
  15477. t.join();
  15478. ASSERT_FALSE(svr.is_running());
  15479. ASSERT_TRUE(handled);
  15480. });
  15481. svr.wait_until_ready();
  15482. UploadFormDataItems items;
  15483. items.reserve(kItemCount);
  15484. for (size_t i = 0; i < kItemCount; i++) {
  15485. items.push_back(
  15486. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15487. }
  15488. Client cli(HOST, port);
  15489. auto res = cli.Post("/upload", items);
  15490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15491. EXPECT_EQ(StatusCode::OK_200, res->status);
  15492. }
  15493. TEST(MultipartFormDataTest, MakeFileProvider) {
  15494. // Verify make_file_provider sends a file's contents correctly.
  15495. const std::string file_content(4096, 'Z');
  15496. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15497. {
  15498. std::ofstream ofs(tmp_path, std::ios::binary);
  15499. ofs.write(file_content.data(),
  15500. static_cast<std::streamsize>(file_content.size()));
  15501. }
  15502. auto handled = false;
  15503. Server svr;
  15504. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15505. const ContentReader &content_reader) {
  15506. ASSERT_TRUE(req.is_multipart_form_data());
  15507. std::vector<FormData> items;
  15508. content_reader(
  15509. [&](const FormData &file) {
  15510. items.push_back(file);
  15511. return true;
  15512. },
  15513. [&](const char *data, size_t data_length) {
  15514. items.back().content.append(data, data_length);
  15515. return true;
  15516. });
  15517. ASSERT_EQ(1u, items.size());
  15518. EXPECT_EQ("myfile", items[0].name);
  15519. EXPECT_EQ("data.bin", items[0].filename);
  15520. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15521. EXPECT_EQ(file_content, items[0].content);
  15522. handled = true;
  15523. });
  15524. auto port = svr.bind_to_any_port(HOST);
  15525. auto t = thread([&] { svr.listen_after_bind(); });
  15526. auto se = detail::scope_exit([&] {
  15527. svr.stop();
  15528. t.join();
  15529. ASSERT_FALSE(svr.is_running());
  15530. ASSERT_TRUE(handled);
  15531. std::remove(tmp_path.c_str());
  15532. });
  15533. svr.wait_until_ready();
  15534. FormDataProviderItems providers;
  15535. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15536. "application/octet-stream"));
  15537. Client cli(HOST, port);
  15538. auto res = cli.Post("/upload", {}, {}, providers);
  15539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15540. EXPECT_EQ(StatusCode::OK_200, res->status);
  15541. }
  15542. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15543. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15544. // (100) headers is rejected with a 400 Bad Request response.
  15545. Server svr;
  15546. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15547. res.set_content("ok", "text/plain");
  15548. });
  15549. thread t = thread([&] { svr.listen(HOST, PORT); });
  15550. auto se = detail::scope_exit([&] {
  15551. svr.stop();
  15552. t.join();
  15553. ASSERT_FALSE(svr.is_running());
  15554. });
  15555. svr.wait_until_ready();
  15556. // Build a multipart part with 101 custom headers (exceeding
  15557. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15558. std::stringstream body;
  15559. body << "--simpleboundary\r\n"
  15560. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15561. for (int i = 0; i < 101; i++) {
  15562. body << "X-Custom-Header-" << i << ": value\r\n";
  15563. }
  15564. body << "\r\n"
  15565. << "value1\r\n"
  15566. << "--simpleboundary--\r\n";
  15567. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15568. Client cli(HOST, PORT);
  15569. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15571. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15572. }
  15573. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15574. // A body that never contains the declared boundary must not be accumulated
  15575. // while the parser waits for it. Buffering it would also make every read
  15576. // rescan everything seen so far, which is quadratic in the body size.
  15577. Server svr;
  15578. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15579. res.set_content("ok", "text/plain");
  15580. });
  15581. auto port = svr.bind_to_any_port(HOST);
  15582. thread t = thread([&] { svr.listen_after_bind(); });
  15583. auto se = detail::scope_exit([&] {
  15584. svr.stop();
  15585. t.join();
  15586. ASSERT_FALSE(svr.is_running());
  15587. });
  15588. svr.wait_until_ready();
  15589. Client cli(HOST, port);
  15590. cli.set_read_timeout(60, 0);
  15591. cli.set_write_timeout(60, 0);
  15592. // '-' is the worst case: it matches the first character of the boundary, so
  15593. // every position has to be checked against it.
  15594. auto post_dashes = [&](size_t size) {
  15595. const std::string body(size, '-');
  15596. auto start = std::chrono::steady_clock::now();
  15597. auto res =
  15598. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15599. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15600. std::chrono::steady_clock::now() - start)
  15601. .count();
  15602. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15603. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15604. return ms;
  15605. };
  15606. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15607. // Windows.
  15608. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15609. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15610. // Comparing the two sizes rather than checking an absolute duration keeps
  15611. // this meaningful across build types and CI load, both of which move the
  15612. // absolute numbers by more than an order of magnitude. Four times the bytes
  15613. // costs about four times the time when parsing is linear, and about sixteen
  15614. // times when the body is buffered and rescanned.
  15615. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15616. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15617. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15618. << "ms, which suggests the body is being buffered and rescanned";
  15619. }
  15620. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15621. // A boundary can only be followed by CRLF or by "--", so anything else is
  15622. // malformed no matter what comes next. The parser must say so right away
  15623. // instead of buffering the rest of the declared body.
  15624. Server svr;
  15625. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15626. res.set_content("ok", "text/plain");
  15627. });
  15628. auto port = svr.bind_to_any_port(HOST);
  15629. thread t = thread([&] { svr.listen_after_bind(); });
  15630. auto se = detail::scope_exit([&] {
  15631. svr.stop();
  15632. t.join();
  15633. ASSERT_FALSE(svr.is_running());
  15634. });
  15635. svr.wait_until_ready();
  15636. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15637. // buffers instead of failing would still be waiting for the remaining bytes.
  15638. const std::string body = "--zzzz\r\n"
  15639. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15640. "\r\n"
  15641. "text1"
  15642. "\r\n--zzzzXX";
  15643. const std::string req = "POST /post HTTP/1.1\r\n"
  15644. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15645. "Content-Length: 1048576\r\n"
  15646. "\r\n" +
  15647. body;
  15648. std::string response;
  15649. ASSERT_TRUE(send_request(3, req, &response, port));
  15650. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15651. EXPECT_EQ("400", response.substr(9, 3));
  15652. }
  15653. // Posts a multipart body split into two writes, so that the server sees the
  15654. // split at whatever offset the caller chose, and expects the single "text1"
  15655. // field to come through.
  15656. static void expect_split_multipart_ok(const std::string &body1,
  15657. const std::string &body2) {
  15658. auto handled = false;
  15659. Server svr;
  15660. svr.Post("/post", [&](const Request &req, Response &) {
  15661. EXPECT_EQ(1u, req.form.fields.size());
  15662. EXPECT_EQ("text1", req.form.get_field("text1"));
  15663. handled = true;
  15664. });
  15665. auto port = svr.bind_to_any_port(HOST);
  15666. thread t = thread([&] { svr.listen_after_bind(); });
  15667. auto se = detail::scope_exit([&] {
  15668. svr.stop();
  15669. t.join();
  15670. ASSERT_FALSE(svr.is_running());
  15671. ASSERT_TRUE(handled);
  15672. });
  15673. svr.wait_until_ready();
  15674. // "Connection: close" makes the server close once it has answered, so the
  15675. // response drain ends immediately instead of idling until the read timeout.
  15676. const std::string head =
  15677. "POST /post HTTP/1.1\r\n"
  15678. "Host: localhost\r\n"
  15679. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15680. "Connection: close\r\n"
  15681. "Content-Length: " +
  15682. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15683. std::string response;
  15684. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15685. ASSERT_GE(response.size(), 12u) << "no response";
  15686. EXPECT_EQ("200", response.substr(9, 3));
  15687. }
  15688. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15689. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15690. // ignored, including when it does not arrive in the same read as the
  15691. // close-delimiter itself.
  15692. expect_split_multipart_ok("--zzzz\r\n"
  15693. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15694. "\r\n"
  15695. "text1"
  15696. "\r\n--zzzz--",
  15697. "\r\nthis epilogue must be ignored\r\n");
  15698. }
  15699. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15700. // The initial boundary may be preceded by a preamble of any length and may
  15701. // straddle a read boundary. Discarding data while waiting for it must not
  15702. // throw away a partial boundary sitting at the end of the buffer.
  15703. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15704. "zz\r\n"
  15705. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15706. "\r\n"
  15707. "text1"
  15708. "\r\n--zzzz--\r\n");
  15709. }
  15710. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15711. // The received boundary was only checked for being non-empty, so it could be
  15712. // as long as a header is allowed to be. The parser scans the body for
  15713. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15714. // costs a nearly full comparison at nearly every position, making the
  15715. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15716. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15717. Server svr;
  15718. svr.Post("/post", [](const Request &req, Response &res) {
  15719. EXPECT_EQ(1u, req.form.fields.size());
  15720. EXPECT_EQ("text1", req.form.get_field("text1"));
  15721. res.set_content("ok", "text/plain");
  15722. });
  15723. auto port = svr.bind_to_any_port(HOST);
  15724. thread t = thread([&] { svr.listen_after_bind(); });
  15725. auto se = detail::scope_exit([&] {
  15726. svr.stop();
  15727. t.join();
  15728. ASSERT_FALSE(svr.is_running());
  15729. });
  15730. svr.wait_until_ready();
  15731. Client cli(HOST, port);
  15732. auto post_with_boundary_of_length = [&](size_t len) {
  15733. const std::string boundary(len, 'a');
  15734. const std::string body =
  15735. "--" + boundary +
  15736. "\r\n"
  15737. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15738. "\r\n"
  15739. "text1"
  15740. "\r\n--" +
  15741. boundary + "--\r\n";
  15742. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15743. };
  15744. auto res = post_with_boundary_of_length(70);
  15745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15746. EXPECT_EQ(StatusCode::OK_200, res->status);
  15747. res = post_with_boundary_of_length(71);
  15748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15749. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15750. }
  15751. TEST(MakeFileBodyTest, Basic) {
  15752. const std::string file_content(4096, 'Z');
  15753. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15754. {
  15755. std::ofstream ofs(tmp_path, std::ios::binary);
  15756. ofs.write(file_content.data(),
  15757. static_cast<std::streamsize>(file_content.size()));
  15758. }
  15759. auto handled = false;
  15760. Server svr;
  15761. svr.Post("/upload", [&](const Request &req, Response &res) {
  15762. EXPECT_EQ(file_content, req.body);
  15763. handled = true;
  15764. res.status = StatusCode::OK_200;
  15765. });
  15766. auto port = svr.bind_to_any_port(HOST);
  15767. auto t = thread([&] { svr.listen_after_bind(); });
  15768. auto se = detail::scope_exit([&] {
  15769. svr.stop();
  15770. t.join();
  15771. ASSERT_FALSE(svr.is_running());
  15772. ASSERT_TRUE(handled);
  15773. std::remove(tmp_path.c_str());
  15774. });
  15775. svr.wait_until_ready();
  15776. auto fb = make_file_body(tmp_path);
  15777. ASSERT_GT(fb.first, 0u);
  15778. Client cli(HOST, port);
  15779. auto res =
  15780. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15782. EXPECT_EQ(StatusCode::OK_200, res->status);
  15783. }
  15784. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15785. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15786. {
  15787. std::ofstream ofs(path, std::ios::binary);
  15788. const std::string content(100, 'A');
  15789. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15790. }
  15791. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15792. auto body = make_file_body(path);
  15793. ASSERT_EQ(100u, body.first);
  15794. ASSERT_TRUE(static_cast<bool>(body.second));
  15795. // Rewritten shorter after its length was measured - and, on a server, after
  15796. // that length has already gone out as Content-Length.
  15797. {
  15798. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15799. const std::string content(10, 'A');
  15800. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15801. }
  15802. std::string written;
  15803. DataSink sink;
  15804. sink.write = [&](const char *d, size_t l) {
  15805. written.append(d, l);
  15806. return true;
  15807. };
  15808. // The provider has to report failure. write_content_with_progress() advances
  15809. // its offset only by what was written, so a provider that returns true
  15810. // without completing the length it promised is called again straight away,
  15811. // and again.
  15812. EXPECT_FALSE(body.second(0, body.first, sink));
  15813. EXPECT_EQ(std::string(10, 'A'), written);
  15814. }
  15815. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15816. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15817. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15818. {
  15819. std::ofstream ofs(path, std::ios::binary);
  15820. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15821. }
  15822. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15823. auto body = make_file_body(path);
  15824. ASSERT_EQ(content.size(), body.first);
  15825. ASSERT_TRUE(static_cast<bool>(body.second));
  15826. std::string written;
  15827. DataSink sink;
  15828. sink.write = [&](const char *d, size_t l) {
  15829. written.append(d, l);
  15830. return true;
  15831. };
  15832. EXPECT_TRUE(body.second(0, body.first, sink));
  15833. EXPECT_EQ(content, written);
  15834. }
  15835. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15836. static constexpr unsigned int number_of_tasks{1000000};
  15837. std::atomic_uint count{0};
  15838. std::unique_ptr<TaskQueue> task_queue{
  15839. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15840. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15841. auto queued = task_queue->enqueue(
  15842. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15843. EXPECT_TRUE(queued);
  15844. }
  15845. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15846. task_queue->shutdown();
  15847. #else
  15848. EXPECT_NO_THROW(task_queue->shutdown());
  15849. #endif
  15850. EXPECT_EQ(number_of_tasks, count.load());
  15851. }
  15852. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15853. static constexpr unsigned int number_of_tasks{1000000};
  15854. static constexpr unsigned int qlimit{2};
  15855. unsigned int queued_count{0};
  15856. std::atomic_uint count{0};
  15857. std::unique_ptr<TaskQueue> task_queue{
  15858. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15859. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15860. if (task_queue->enqueue(
  15861. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15862. queued_count++;
  15863. }
  15864. }
  15865. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15866. task_queue->shutdown();
  15867. #else
  15868. EXPECT_NO_THROW(task_queue->shutdown());
  15869. #endif
  15870. EXPECT_EQ(queued_count, count.load());
  15871. EXPECT_TRUE(queued_count <= number_of_tasks);
  15872. EXPECT_TRUE(queued_count >= qlimit);
  15873. }
  15874. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15875. // Use a short idle timeout so a dynamic thread spawns, times out and
  15876. // exits during the test, and the pool keeps working afterwards.
  15877. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15878. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15879. /*idle_timeout_sec=*/1}};
  15880. std::atomic_uint count{0};
  15881. std::condition_variable cv;
  15882. std::mutex mtx;
  15883. bool release = false;
  15884. // Block the base thread so the second task spawns a dynamic thread.
  15885. EXPECT_TRUE(task_queue->enqueue([&] {
  15886. std::unique_lock<std::mutex> lock(mtx);
  15887. while (!release) {
  15888. cv.wait(lock);
  15889. }
  15890. count++;
  15891. }));
  15892. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15893. // Let the dynamic thread finish its task and exceed the idle timeout.
  15894. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15895. {
  15896. std::unique_lock<std::mutex> lock(mtx);
  15897. release = true;
  15898. }
  15899. cv.notify_all();
  15900. // The pool must still accept and run tasks after the dynamic thread exited.
  15901. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15902. task_queue->shutdown();
  15903. EXPECT_EQ(3u, count.load());
  15904. }
  15905. TEST(TaskQueueTest, MaxQueuedRequests) {
  15906. static constexpr unsigned int qlimit{3};
  15907. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15908. std::condition_variable sem_cv;
  15909. std::mutex sem_mtx;
  15910. int credits = 0;
  15911. bool queued;
  15912. /* Fill up the queue with tasks that will block until we give them credits to
  15913. * complete. */
  15914. for (unsigned int n = 0; n <= qlimit;) {
  15915. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15916. std::unique_lock<std::mutex> lock(sem_mtx);
  15917. while (credits <= 0) {
  15918. sem_cv.wait(lock);
  15919. }
  15920. /* Consume the credit and signal the test code if they are all gone. */
  15921. if (--credits == 0) { sem_cv.notify_one(); }
  15922. });
  15923. if (n < qlimit) {
  15924. /* The first qlimit enqueues must succeed. */
  15925. EXPECT_TRUE(queued);
  15926. } else {
  15927. /* The last one will succeed only when the worker thread
  15928. * starts and dequeues the first blocking task. Although
  15929. * not necessary for the correctness of this test, we sleep for
  15930. * a short while to avoid busy waiting. */
  15931. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15932. }
  15933. if (queued) { n++; }
  15934. }
  15935. /* Further enqueues must fail since the queue is full. */
  15936. for (auto i = 0; i < 4; i++) {
  15937. queued = task_queue->enqueue([] {});
  15938. EXPECT_FALSE(queued);
  15939. }
  15940. /* Give the credits to allow the previous tasks to complete. */
  15941. {
  15942. std::unique_lock<std::mutex> lock(sem_mtx);
  15943. credits += qlimit + 1;
  15944. }
  15945. sem_cv.notify_all();
  15946. /* Wait for all the credits to be consumed. */
  15947. {
  15948. std::unique_lock<std::mutex> lock(sem_mtx);
  15949. while (credits > 0) {
  15950. sem_cv.wait(lock);
  15951. }
  15952. }
  15953. /* Check that we are able again to enqueue at least qlimit tasks. */
  15954. for (unsigned int i = 0; i < qlimit; i++) {
  15955. queued = task_queue->enqueue([] {});
  15956. EXPECT_TRUE(queued);
  15957. }
  15958. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15959. task_queue->shutdown();
  15960. #else
  15961. EXPECT_NO_THROW(task_queue->shutdown());
  15962. #endif
  15963. }
  15964. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15965. Server svr;
  15966. std::string method;
  15967. std::string body;
  15968. auto has_content_length = false;
  15969. auto has_transfer_encoding = false;
  15970. std::atomic<int> bad_requests{0};
  15971. // Leftover body bytes get parsed as a malformed request and answered with
  15972. // 400
  15973. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15974. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15975. });
  15976. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15977. res.set_redirect("/down", StatusCode::SeeOther_303);
  15978. });
  15979. svr.Get("/down", [&](const Request &req, Response &res) {
  15980. method = req.method;
  15981. body = req.body;
  15982. has_content_length = req.has_header("Content-Length");
  15983. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15984. res.set_content("ok", "text/plain");
  15985. });
  15986. auto port = svr.bind_to_any_port(HOST);
  15987. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15988. auto se = detail::scope_exit([&] {
  15989. svr.stop();
  15990. thread.join();
  15991. ASSERT_FALSE(svr.is_running());
  15992. });
  15993. svr.wait_until_ready();
  15994. const std::string payload = "SECRET-BODY";
  15995. auto check = [&](Client &cli, const Result &res) {
  15996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15997. EXPECT_EQ(StatusCode::OK_200, res->status);
  15998. EXPECT_EQ("ok", res->body);
  15999. EXPECT_EQ("GET", method);
  16000. EXPECT_TRUE(body.empty());
  16001. EXPECT_FALSE(has_content_length);
  16002. EXPECT_FALSE(has_transfer_encoding);
  16003. // Nothing of the original body may be left on the connection
  16004. auto res2 = cli.Get("/down");
  16005. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16006. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16007. EXPECT_EQ("ok", res2->body);
  16008. EXPECT_EQ(0, bad_requests);
  16009. };
  16010. // With content length
  16011. {
  16012. Client cli(HOST, port);
  16013. cli.set_keep_alive(true);
  16014. cli.set_follow_location(true);
  16015. auto res = cli.Post(
  16016. "/up", payload.size(),
  16017. [&](size_t offset, size_t length, DataSink &sink) {
  16018. return sink.write(payload.data() + offset, length);
  16019. },
  16020. "text/plain");
  16021. check(cli, res);
  16022. }
  16023. // Without content length (chunked)
  16024. {
  16025. Client cli(HOST, port);
  16026. cli.set_keep_alive(true);
  16027. cli.set_follow_location(true);
  16028. auto res = cli.Post(
  16029. "/up",
  16030. [&](size_t /*offset*/, DataSink &sink) {
  16031. sink.write(payload.data(), payload.size());
  16032. sink.done();
  16033. return true;
  16034. },
  16035. "text/plain");
  16036. check(cli, res);
  16037. }
  16038. }
  16039. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16040. Server svr;
  16041. std::string target;
  16042. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16043. // Echo the still-encoded name back in the Location
  16044. const std::string prefix = "/start/";
  16045. res.status = StatusCode::Found_302;
  16046. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16047. });
  16048. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16049. target = req.target;
  16050. res.set_content("ok", "text/plain");
  16051. });
  16052. auto port = svr.bind_to_any_port(HOST);
  16053. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16054. auto se = detail::scope_exit([&] {
  16055. svr.stop();
  16056. thread.join();
  16057. ASSERT_FALSE(svr.is_running());
  16058. });
  16059. svr.wait_until_ready();
  16060. // Decoding the Location path would turn the first four into a path
  16061. // separator, a query delimiter, a fragment delimiter and a different
  16062. // percent-encoded octet. The rest must keep reaching the server as they are.
  16063. const std::vector<std::string> names = {
  16064. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16065. };
  16066. for (auto path_encode : {true, false}) {
  16067. Client cli(HOST, port);
  16068. cli.set_follow_location(true);
  16069. cli.set_path_encode(path_encode);
  16070. for (const auto &name : names) {
  16071. target.clear();
  16072. auto res = cli.Get("/start/" + name);
  16073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16074. EXPECT_EQ(StatusCode::OK_200, res->status);
  16075. EXPECT_EQ("/dest/" + name, target);
  16076. }
  16077. }
  16078. }
  16079. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16080. Server svr;
  16081. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16082. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16083. });
  16084. svr.Get("/hello", [](const Request &req, Response &res) {
  16085. res.set_content(req.get_param_value("key"), "text/plain");
  16086. });
  16087. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16088. auto se = detail::scope_exit([&] {
  16089. svr.stop();
  16090. thread.join();
  16091. ASSERT_FALSE(svr.is_running());
  16092. });
  16093. svr.wait_until_ready();
  16094. {
  16095. Client cli(HOST, PORT);
  16096. cli.set_follow_location(true);
  16097. auto res = cli.Get("/");
  16098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16099. EXPECT_EQ(StatusCode::OK_200, res->status);
  16100. EXPECT_EQ("val&key2=val2", res->body);
  16101. }
  16102. }
  16103. #endif
  16104. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16105. Server svr;
  16106. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16107. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16108. });
  16109. svr.Get("/hello", [](const Request &req, Response &res) {
  16110. res.set_content(req.get_param_value("key"), "text/plain");
  16111. });
  16112. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16113. auto se = detail::scope_exit([&] {
  16114. svr.stop();
  16115. thread.join();
  16116. ASSERT_FALSE(svr.is_running());
  16117. });
  16118. svr.wait_until_ready();
  16119. {
  16120. Client cli(HOST, PORT);
  16121. cli.set_follow_location(true);
  16122. auto res = cli.Get("/");
  16123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16124. EXPECT_EQ(StatusCode::OK_200, res->status);
  16125. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16126. }
  16127. }
  16128. TEST(RedirectTest, RedirectWithPlusInPath) {
  16129. Server svr;
  16130. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16131. res.set_redirect("/a+b");
  16132. });
  16133. // Route pattern uses regex; escape + as \\+
  16134. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16135. res.set_content(req.path, "text/plain");
  16136. });
  16137. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16138. auto se = detail::scope_exit([&] {
  16139. svr.stop();
  16140. thread.join();
  16141. ASSERT_FALSE(svr.is_running());
  16142. });
  16143. svr.wait_until_ready();
  16144. {
  16145. Client cli(HOST, PORT);
  16146. cli.set_follow_location(true);
  16147. auto res = cli.Get("/");
  16148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16149. EXPECT_EQ(StatusCode::OK_200, res->status);
  16150. EXPECT_EQ("/a+b", res->body);
  16151. }
  16152. }
  16153. TEST(RedirectTest, ResolveRelativeLocation) {
  16154. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16155. const std::vector<std::pair<std::string, std::string>> cases = {
  16156. {"g", "/b/c/g"},
  16157. {"./g", "/b/c/g"},
  16158. {"g/", "/b/c/g/"},
  16159. {"?y", "/b/c/d;p?y"},
  16160. {"g?y", "/b/c/g?y"},
  16161. {"#s", "/b/c/d;p?q#s"},
  16162. {"g#s", "/b/c/g#s"},
  16163. {"g?y#s", "/b/c/g?y#s"},
  16164. {";x", "/b/c/;x"},
  16165. {"g;x", "/b/c/g;x"},
  16166. {".", "/b/c/"},
  16167. {"./", "/b/c/"},
  16168. {"..", "/b/"},
  16169. {"../", "/b/"},
  16170. {"../g", "/b/g"},
  16171. {"../..", "/"},
  16172. {"../../", "/"},
  16173. {"../../g", "/g"},
  16174. {"../../../g", "/g"},
  16175. {"g.", "/b/c/g."},
  16176. {".g", "/b/c/.g"},
  16177. {"g..", "/b/c/g.."},
  16178. {"..g", "/b/c/..g"},
  16179. {"./../g", "/b/g"},
  16180. {"./g/.", "/b/c/g/"},
  16181. {"g/./h", "/b/c/g/h"},
  16182. {"g/../h", "/b/c/h"},
  16183. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16184. {"g;x=1/../y", "/b/c/y"},
  16185. {"g?y/./x", "/b/c/g?y/./x"},
  16186. {"g#s/../x", "/b/c/g#s/../x"},
  16187. // Not relative-path references, so left for parse_url.
  16188. {"/g", "/g"},
  16189. {"//g", "//g"},
  16190. {"http://g/x", "http://g/x"},
  16191. {"g:h", "g:h"},
  16192. };
  16193. for (const auto &c : cases) {
  16194. EXPECT_EQ(c.second,
  16195. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16196. << c.first;
  16197. }
  16198. }
  16199. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16200. Server svr;
  16201. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16202. res.set_redirect(req.get_param_value("to"));
  16203. });
  16204. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16205. res.set_content(req.target, "text/plain");
  16206. });
  16207. svr.Get("/other", [](const Request &req, Response &res) {
  16208. res.set_content(req.target, "text/plain");
  16209. });
  16210. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16211. auto se = detail::scope_exit([&] {
  16212. svr.stop();
  16213. thread.join();
  16214. ASSERT_FALSE(svr.is_running());
  16215. });
  16216. svr.wait_until_ready();
  16217. const std::vector<std::pair<std::string, std::string>> cases = {
  16218. {"next", "/dir/next"},
  16219. {"./next?x=1", "/dir/next?x=1"},
  16220. {"../other", "/other"},
  16221. };
  16222. for (const auto &c : cases) {
  16223. Client cli(HOST, PORT);
  16224. cli.set_follow_location(true);
  16225. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16226. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16227. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16228. EXPECT_EQ(c.second, res->body) << c.first;
  16229. }
  16230. }
  16231. #ifdef CPPHTTPLIB_SSL_ENABLED
  16232. TEST(RedirectTest, Issue2185_Online) {
  16233. SSLClient client("github.com");
  16234. client.set_follow_location(true);
  16235. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16236. "Coollab-Windows.zip");
  16237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16238. EXPECT_EQ(StatusCode::OK_200, res->status);
  16239. EXPECT_EQ(9920427U, res->body.size());
  16240. }
  16241. #endif
  16242. TEST(VulnerabilityTest, CRLFInjection) {
  16243. Server svr;
  16244. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16245. res.set_content("Hello 1", "text/plain");
  16246. });
  16247. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16248. res.set_content("Hello 2", "text/plain");
  16249. });
  16250. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16251. res.set_content("Hello 3", "text/plain");
  16252. });
  16253. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16254. res.set_content("Hello 4", "text/plain");
  16255. });
  16256. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16257. for (const auto &x : req.headers) {
  16258. auto key = x.first;
  16259. EXPECT_STRNE("evil", key.c_str());
  16260. }
  16261. });
  16262. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16263. auto se = detail::scope_exit([&] {
  16264. svr.stop();
  16265. thread.join();
  16266. ASSERT_FALSE(svr.is_running());
  16267. });
  16268. svr.wait_until_ready();
  16269. {
  16270. Client cli(HOST, PORT);
  16271. cli.Post("/test1", "A=B",
  16272. "application/x-www-form-urlencoded\r\nevil: hello1");
  16273. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16274. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16275. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16276. }
  16277. }
  16278. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16279. auto server_thread = std::thread([] {
  16280. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16281. default_socket_options(srv);
  16282. sockaddr_in addr{};
  16283. addr.sin_family = AF_INET;
  16284. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16285. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16286. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16287. ::listen(srv, 1);
  16288. sockaddr_in cli_addr{};
  16289. socklen_t cli_len = sizeof(cli_addr);
  16290. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16291. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16292. std::string buf_all;
  16293. char buf[2048];
  16294. ssize_t n;
  16295. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16296. buf_all.append(buf, static_cast<size_t>(n));
  16297. size_t pos;
  16298. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16299. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16300. auto e = request_block.find("\r\n");
  16301. if (e != std::string::npos) {
  16302. auto request_line = request_block.substr(0, e);
  16303. std::string msg =
  16304. "CRLF injection detected in request line: '" + request_line + "'";
  16305. EXPECT_FALSE(true) << msg;
  16306. }
  16307. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16308. ::send(cli,
  16309. #ifdef _WIN32
  16310. static_cast<const char *>(resp.c_str()),
  16311. static_cast<int>(resp.size()),
  16312. #else
  16313. resp.c_str(), resp.size(),
  16314. #endif
  16315. 0);
  16316. buf_all.erase(0, pos + 4);
  16317. }
  16318. }
  16319. detail::close_socket(cli);
  16320. detail::close_socket(srv);
  16321. });
  16322. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16323. auto cli = Client("127.0.0.1", PORT + 1);
  16324. auto headers = Headers{
  16325. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16326. {"Connection", "keep-alive"}};
  16327. auto res = cli.Get("/hi", headers);
  16328. EXPECT_FALSE(res);
  16329. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16330. server_thread.join();
  16331. }
  16332. // A request rejected before any byte reaches the socket must fail right away
  16333. // instead of waiting for a response the server will never send.
  16334. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16335. // The kernel completes the TCP handshake from the listen backlog, so the
  16336. // client connects, but nothing ever reads, responds or closes.
  16337. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16338. default_socket_options(srv);
  16339. sockaddr_in addr{};
  16340. addr.sin_family = AF_INET;
  16341. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16342. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16343. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16344. ASSERT_EQ(0, ::listen(srv, 8));
  16345. auto cli = Client("127.0.0.1", PORT + 1);
  16346. cli.set_read_timeout(10, 0);
  16347. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16348. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16349. std::chrono::steady_clock::now() - start)
  16350. .count();
  16351. };
  16352. {
  16353. Request req;
  16354. req.method = "GE T";
  16355. req.path = "/";
  16356. auto start = std::chrono::steady_clock::now();
  16357. auto res = cli.send(req);
  16358. EXPECT_FALSE(res);
  16359. EXPECT_EQ(Error::Write, res.error());
  16360. EXPECT_LT(elapsed_ms(start), 1000);
  16361. }
  16362. {
  16363. auto start = std::chrono::steady_clock::now();
  16364. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16365. EXPECT_FALSE(res);
  16366. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16367. EXPECT_LT(elapsed_ms(start), 1000);
  16368. }
  16369. EXPECT_FALSE(cli.is_socket_open());
  16370. detail::close_socket(srv);
  16371. }
  16372. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16373. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16374. default_socket_options(srv);
  16375. sockaddr_in addr{};
  16376. addr.sin_family = AF_INET;
  16377. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16378. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16379. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16380. ASSERT_EQ(0, ::listen(srv, 1));
  16381. std::string received;
  16382. auto server_thread = std::thread([&] {
  16383. auto sock = ::accept(srv, nullptr, nullptr);
  16384. if (sock == INVALID_SOCKET) { return; }
  16385. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16386. char buf[2048];
  16387. ssize_t n;
  16388. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16389. received.append(buf, static_cast<size_t>(n));
  16390. }
  16391. detail::close_socket(sock);
  16392. });
  16393. {
  16394. auto cli = Client("127.0.0.1", PORT + 1);
  16395. // "Z" sorts after the default headers, so writing straight to the socket
  16396. // would have sent the request line and those headers before the rejection.
  16397. auto handle =
  16398. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16399. EXPECT_FALSE(handle.is_valid());
  16400. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16401. }
  16402. server_thread.join();
  16403. detail::close_socket(srv);
  16404. EXPECT_TRUE(received.empty()) << received;
  16405. }
  16406. TEST(PathParamsTest, StaticMatch) {
  16407. const auto pattern = "/users/all";
  16408. detail::PathParamsMatcher matcher(pattern);
  16409. Request request;
  16410. request.path = "/users/all";
  16411. ASSERT_TRUE(matcher.match(request));
  16412. std::unordered_map<std::string, std::string> expected_params = {};
  16413. EXPECT_EQ(request.path_params, expected_params);
  16414. }
  16415. TEST(PathParamsTest, StaticMismatch) {
  16416. const auto pattern = "/users/all";
  16417. detail::PathParamsMatcher matcher(pattern);
  16418. Request request;
  16419. request.path = "/users/1";
  16420. ASSERT_FALSE(matcher.match(request));
  16421. }
  16422. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16423. const auto pattern = "/users/:id/subscriptions";
  16424. detail::PathParamsMatcher matcher(pattern);
  16425. Request request;
  16426. request.path = "/users/42/subscriptions";
  16427. ASSERT_TRUE(matcher.match(request));
  16428. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16429. EXPECT_EQ(request.path_params, expected_params);
  16430. }
  16431. TEST(PathParamsTest, SingleParamInTheEnd) {
  16432. const auto pattern = "/users/:id";
  16433. detail::PathParamsMatcher matcher(pattern);
  16434. Request request;
  16435. request.path = "/users/24";
  16436. ASSERT_TRUE(matcher.match(request));
  16437. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16438. EXPECT_EQ(request.path_params, expected_params);
  16439. }
  16440. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16441. const auto pattern = "/users/:id/";
  16442. detail::PathParamsMatcher matcher(pattern);
  16443. Request request;
  16444. request.path = "/users/42/";
  16445. ASSERT_TRUE(matcher.match(request));
  16446. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16447. EXPECT_EQ(request.path_params, expected_params);
  16448. }
  16449. TEST(PathParamsTest, EmptyParam) {
  16450. const auto pattern = "/users/:id/";
  16451. detail::PathParamsMatcher matcher(pattern);
  16452. Request request;
  16453. request.path = "/users//";
  16454. ASSERT_TRUE(matcher.match(request));
  16455. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16456. EXPECT_EQ(request.path_params, expected_params);
  16457. }
  16458. TEST(PathParamsTest, FragmentMismatch) {
  16459. const auto pattern = "/users/:id/";
  16460. detail::PathParamsMatcher matcher(pattern);
  16461. Request request;
  16462. request.path = "/admins/24/";
  16463. ASSERT_FALSE(matcher.match(request));
  16464. }
  16465. TEST(PathParamsTest, ExtraFragments) {
  16466. const auto pattern = "/users/:id";
  16467. detail::PathParamsMatcher matcher(pattern);
  16468. Request request;
  16469. request.path = "/users/42/subscriptions";
  16470. ASSERT_FALSE(matcher.match(request));
  16471. }
  16472. TEST(PathParamsTest, MissingTrailingParam) {
  16473. const auto pattern = "/users/:id";
  16474. detail::PathParamsMatcher matcher(pattern);
  16475. Request request;
  16476. request.path = "/users";
  16477. ASSERT_FALSE(matcher.match(request));
  16478. }
  16479. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16480. const auto pattern = "/users/:id/subscriptions";
  16481. detail::PathParamsMatcher matcher(pattern);
  16482. Request request;
  16483. request.path = "/users/subscriptions";
  16484. ASSERT_FALSE(matcher.match(request));
  16485. }
  16486. TEST(PathParamsTest, MultipleParams) {
  16487. const auto pattern = "/users/:userid/subscriptions/:subid";
  16488. detail::PathParamsMatcher matcher(pattern);
  16489. Request request;
  16490. request.path = "/users/42/subscriptions/2";
  16491. ASSERT_TRUE(matcher.match(request));
  16492. std::unordered_map<std::string, std::string> expected_params = {
  16493. {"userid", "42"}, {"subid", "2"}};
  16494. EXPECT_EQ(request.path_params, expected_params);
  16495. }
  16496. TEST(PathParamsTest, SequenceOfParams) {
  16497. const auto pattern = "/values/:x/:y/:z";
  16498. detail::PathParamsMatcher matcher(pattern);
  16499. Request request;
  16500. request.path = "/values/1/2/3";
  16501. ASSERT_TRUE(matcher.match(request));
  16502. std::unordered_map<std::string, std::string> expected_params = {
  16503. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16504. EXPECT_EQ(request.path_params, expected_params);
  16505. }
  16506. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16507. const auto pattern = "/prefix:suffix";
  16508. detail::PathParamsMatcher matcher(pattern);
  16509. Request request;
  16510. request.path = "/prefix:suffix";
  16511. ASSERT_TRUE(matcher.match(request));
  16512. const std::unordered_map<std::string, std::string> expected_params = {};
  16513. EXPECT_EQ(request.path_params, expected_params);
  16514. }
  16515. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16516. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16517. // calling thread's stack on a long enough path for a quantified pattern;
  16518. // RegexMatcher must refuse to run regex matching on paths beyond
  16519. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16520. detail::RegexMatcher matcher("/files/(.*)");
  16521. Request within_limit;
  16522. within_limit.path = "/files/" + std::string(10, 'A');
  16523. EXPECT_TRUE(matcher.match(within_limit));
  16524. Request over_limit;
  16525. over_limit.path =
  16526. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16527. EXPECT_FALSE(matcher.match(over_limit));
  16528. }
  16529. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16530. Server svr;
  16531. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16532. res.set_content("ok", "text/plain");
  16533. });
  16534. auto port = svr.bind_to_any_port(HOST);
  16535. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16536. auto se = detail::scope_exit([&] {
  16537. svr.stop();
  16538. thread.join();
  16539. ASSERT_FALSE(svr.is_running());
  16540. });
  16541. svr.wait_until_ready();
  16542. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16543. // request URI limit; this used to be able to crash the process.
  16544. std::string path =
  16545. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16546. std::string req = "GET " + path +
  16547. " HTTP/1.1\r\n"
  16548. "Host: " +
  16549. std::string(HOST) + ":" + std::to_string(port) +
  16550. "\r\n"
  16551. "Connection: close\r\n"
  16552. "\r\n";
  16553. std::string response;
  16554. ASSERT_TRUE(send_request(5, req, &response, port));
  16555. EXPECT_NE(std::string::npos, response.find("404"));
  16556. }
  16557. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16558. Server svr;
  16559. auto handler = [](const Request & /*req*/, Response &res) {
  16560. res.set_content("hit", "text/plain");
  16561. };
  16562. // No regex metacharacter, so this one is compared literally
  16563. svr.Get("/literal/route", handler);
  16564. // '.' is a regex metacharacter, so this one must keep regex semantics
  16565. svr.Get("/a.c", handler);
  16566. auto port = svr.bind_to_any_port(HOST);
  16567. std::thread t([&]() { svr.listen_after_bind(); });
  16568. auto se = detail::scope_exit([&] {
  16569. svr.stop();
  16570. t.join();
  16571. ASSERT_FALSE(svr.is_running());
  16572. });
  16573. svr.wait_until_ready();
  16574. Client cli(HOST, port);
  16575. struct {
  16576. const char *path;
  16577. int status;
  16578. } cases[] = {
  16579. {"/literal/route", StatusCode::OK_200},
  16580. {"/literal/routes", StatusCode::NotFound_404},
  16581. {"/literal/rout", StatusCode::NotFound_404},
  16582. {"/abc", StatusCode::OK_200},
  16583. {"/a.c", StatusCode::OK_200},
  16584. };
  16585. for (const auto &x : cases) {
  16586. auto res = cli.Get(x.path);
  16587. ASSERT_TRUE(res) << x.path;
  16588. EXPECT_EQ(x.status, res->status) << x.path;
  16589. }
  16590. }
  16591. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16592. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16593. // from exhausting the stack, so it must only constrain routes that actually
  16594. // run a regular expression. A literal route is matched by comparison and
  16595. // stays usable at any length.
  16596. Server svr;
  16597. const std::string pattern =
  16598. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16599. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16600. res.set_content("hit", "text/plain");
  16601. });
  16602. auto port = svr.bind_to_any_port(HOST);
  16603. std::thread t([&]() { svr.listen_after_bind(); });
  16604. auto se = detail::scope_exit([&] {
  16605. svr.stop();
  16606. t.join();
  16607. ASSERT_FALSE(svr.is_running());
  16608. });
  16609. svr.wait_until_ready();
  16610. Client cli(HOST, port);
  16611. auto res = cli.Get(pattern);
  16612. ASSERT_TRUE(res);
  16613. EXPECT_EQ(StatusCode::OK_200, res->status);
  16614. }
  16615. TEST(ParseUrlTest, VariousPatterns) {
  16616. {
  16617. detail::UrlComponents uc;
  16618. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16619. EXPECT_EQ("http", uc.scheme);
  16620. EXPECT_EQ("example.com", uc.host);
  16621. EXPECT_EQ("8080", uc.port);
  16622. EXPECT_EQ("/path", uc.path);
  16623. EXPECT_EQ("?q=1", uc.query);
  16624. }
  16625. {
  16626. detail::UrlComponents uc;
  16627. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16628. EXPECT_EQ("https", uc.scheme);
  16629. EXPECT_EQ("example.com", uc.host);
  16630. EXPECT_TRUE(uc.port.empty());
  16631. EXPECT_EQ("/path", uc.path);
  16632. }
  16633. {
  16634. detail::UrlComponents uc;
  16635. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16636. EXPECT_EQ("::1", uc.host);
  16637. EXPECT_EQ("8080", uc.port);
  16638. EXPECT_EQ("/path", uc.path);
  16639. }
  16640. {
  16641. detail::UrlComponents uc;
  16642. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16643. }
  16644. {
  16645. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16646. // the path while the connection still targets the bracketed host.
  16647. detail::UrlComponents uc;
  16648. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16649. }
  16650. {
  16651. detail::UrlComponents uc;
  16652. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16653. }
  16654. {
  16655. detail::UrlComponents uc;
  16656. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16657. EXPECT_EQ("::1", uc.host);
  16658. EXPECT_TRUE(uc.port.empty());
  16659. EXPECT_EQ("/path", uc.path);
  16660. }
  16661. {
  16662. detail::UrlComponents uc;
  16663. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16664. EXPECT_TRUE(uc.scheme.empty());
  16665. EXPECT_EQ("example.com", uc.host);
  16666. EXPECT_EQ("/path", uc.path);
  16667. EXPECT_EQ("?q=1", uc.query);
  16668. }
  16669. {
  16670. detail::UrlComponents uc;
  16671. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16672. EXPECT_TRUE(uc.host.empty());
  16673. EXPECT_EQ("/path", uc.path);
  16674. EXPECT_EQ("?q=1", uc.query);
  16675. }
  16676. {
  16677. detail::UrlComponents uc;
  16678. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16679. EXPECT_EQ("example.com", uc.host);
  16680. EXPECT_EQ("8080", uc.port);
  16681. }
  16682. {
  16683. // Unix socket path — must not be parsed as host
  16684. detail::UrlComponents uc;
  16685. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16686. EXPECT_TRUE(uc.host.empty());
  16687. }
  16688. {
  16689. detail::UrlComponents uc;
  16690. ASSERT_TRUE(detail::parse_url("", uc));
  16691. EXPECT_TRUE(uc.host.empty());
  16692. EXPECT_TRUE(uc.path.empty());
  16693. }
  16694. {
  16695. detail::UrlComponents uc;
  16696. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16697. }
  16698. {
  16699. detail::UrlComponents uc;
  16700. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16701. }
  16702. {
  16703. // Accepted by parse_url; callers restrict to http/https
  16704. detail::UrlComponents uc;
  16705. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16706. EXPECT_EQ("ftp", uc.scheme);
  16707. }
  16708. {
  16709. detail::UrlComponents uc;
  16710. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16711. }
  16712. {
  16713. detail::UrlComponents uc;
  16714. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16715. }
  16716. }
  16717. TEST(ParseUrlTest, FragmentHandling) {
  16718. {
  16719. detail::UrlComponents uc;
  16720. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16721. EXPECT_EQ("/path", uc.path);
  16722. EXPECT_TRUE(uc.query.empty());
  16723. }
  16724. {
  16725. detail::UrlComponents uc;
  16726. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16727. EXPECT_TRUE(uc.path.empty());
  16728. EXPECT_TRUE(uc.query.empty());
  16729. }
  16730. }
  16731. TEST(ParseUrlTest, UserinfoHandling) {
  16732. // userinfo, and a backslash some parsers take for '/', are rejected: such
  16733. // parsers would see evil.com as the host.
  16734. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16735. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16736. for (auto url : urls) {
  16737. detail::UrlComponents uc;
  16738. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16739. }
  16740. }
  16741. TEST(ParseUrlTest, IPv6EdgeCases) {
  16742. {
  16743. detail::UrlComponents uc;
  16744. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16745. EXPECT_TRUE(uc.scheme.empty());
  16746. EXPECT_EQ("::1", uc.host);
  16747. EXPECT_EQ("8080", uc.port);
  16748. }
  16749. {
  16750. // Zone ID '%25' is not in [a-fA-F0-9:]
  16751. detail::UrlComponents uc;
  16752. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16753. }
  16754. }
  16755. TEST(ParseUrlTest, SchemeEdgeCases) {
  16756. {
  16757. detail::UrlComponents uc;
  16758. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16759. }
  16760. {
  16761. detail::UrlComponents uc;
  16762. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16763. }
  16764. {
  16765. detail::UrlComponents uc;
  16766. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16767. }
  16768. }
  16769. TEST(ParseUrlTest, PortEdgeCases) {
  16770. {
  16771. detail::UrlComponents uc;
  16772. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16773. EXPECT_TRUE(uc.port.empty());
  16774. EXPECT_EQ("/path", uc.path);
  16775. }
  16776. {
  16777. // parse_url accepts any port string; validation is done by parse_port
  16778. detail::UrlComponents uc;
  16779. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16780. EXPECT_EQ("abc", uc.port);
  16781. }
  16782. }
  16783. TEST(ParseUrlTest, WebSocketPatterns) {
  16784. {
  16785. detail::UrlComponents uc;
  16786. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16787. EXPECT_EQ("ws", uc.scheme);
  16788. EXPECT_EQ("echo.example.com", uc.host);
  16789. EXPECT_EQ("8080", uc.port);
  16790. EXPECT_EQ("/ws", uc.path);
  16791. }
  16792. {
  16793. detail::UrlComponents uc;
  16794. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16795. EXPECT_EQ("wss", uc.scheme);
  16796. EXPECT_EQ("echo.example.com", uc.host);
  16797. EXPECT_TRUE(uc.port.empty());
  16798. EXPECT_EQ("/ws", uc.path);
  16799. }
  16800. }
  16801. TEST(ParseUrlTest, QueryOnly) {
  16802. detail::UrlComponents uc;
  16803. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16804. EXPECT_TRUE(uc.host.empty());
  16805. EXPECT_TRUE(uc.path.empty());
  16806. EXPECT_EQ("?q=1&r=2", uc.query);
  16807. }
  16808. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16809. detail::UrlComponents uc;
  16810. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16811. EXPECT_TRUE(uc.scheme.empty());
  16812. EXPECT_EQ("example.com", uc.host);
  16813. EXPECT_EQ("443", uc.port);
  16814. EXPECT_EQ("/path", uc.path);
  16815. }
  16816. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16817. // If ipv6 regex working, regex match codepath is taken.
  16818. // else port will default to 80 in Client impl
  16819. int clientImplMagicPort = 80;
  16820. int port = 4321;
  16821. // above ports must be different to avoid false negative
  16822. EXPECT_NE(clientImplMagicPort, port);
  16823. std::string ipV6TestURL = "http://[ff06::c3]";
  16824. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16825. CLIENT_PRIVATE_KEY_FILE);
  16826. EXPECT_EQ(cli.port(), port);
  16827. }
  16828. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16829. auto file_path = "./www/dir/index.html";
  16830. auto dir_path = "./www/dir";
  16831. detail::FileStat stat_file(file_path);
  16832. EXPECT_TRUE(stat_file.is_file());
  16833. EXPECT_FALSE(stat_file.is_dir());
  16834. detail::FileStat stat_dir(dir_path);
  16835. EXPECT_FALSE(stat_dir.is_file());
  16836. EXPECT_TRUE(stat_dir.is_dir());
  16837. }
  16838. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16839. // IPv4 with default HTTP port (80)
  16840. EXPECT_EQ("example.com",
  16841. detail::make_host_and_port_string("example.com", 80, false));
  16842. // IPv4 with default HTTPS port (443)
  16843. EXPECT_EQ("example.com",
  16844. detail::make_host_and_port_string("example.com", 443, true));
  16845. // IPv4 with non-default HTTP port
  16846. EXPECT_EQ("example.com:8080",
  16847. detail::make_host_and_port_string("example.com", 8080, false));
  16848. // IPv4 with non-default HTTPS port
  16849. EXPECT_EQ("example.com:8443",
  16850. detail::make_host_and_port_string("example.com", 8443, true));
  16851. // IPv6 with default HTTP port (80)
  16852. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16853. // IPv6 with default HTTPS port (443)
  16854. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16855. // IPv6 with non-default HTTP port
  16856. EXPECT_EQ("[::1]:8080",
  16857. detail::make_host_and_port_string("::1", 8080, false));
  16858. // IPv6 with non-default HTTPS port
  16859. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16860. // IPv6 full address with default port
  16861. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16862. detail::make_host_and_port_string(
  16863. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16864. // IPv6 full address with non-default port
  16865. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16866. detail::make_host_and_port_string(
  16867. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16868. // IPv6 localhost with non-default port
  16869. EXPECT_EQ("[::1]:3000",
  16870. detail::make_host_and_port_string("::1", 3000, false));
  16871. // IPv6 with zone ID (link-local address) with default port
  16872. EXPECT_EQ("[fe80::1%eth0]",
  16873. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16874. // IPv6 with zone ID (link-local address) with non-default port
  16875. EXPECT_EQ("[fe80::1%eth0]:8080",
  16876. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16877. // Edge case: Port 443 with is_ssl=false (should add port)
  16878. EXPECT_EQ("example.com:443",
  16879. detail::make_host_and_port_string("example.com", 443, false));
  16880. // Edge case: Port 80 with is_ssl=true (should add port)
  16881. EXPECT_EQ("example.com:80",
  16882. detail::make_host_and_port_string("example.com", 80, true));
  16883. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16884. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16885. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16886. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16887. // Security fix: Already bracketed IPv6 should not get double brackets
  16888. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16889. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16890. EXPECT_EQ("[::1]:8080",
  16891. detail::make_host_and_port_string("[::1]", 8080, false));
  16892. EXPECT_EQ("[2001:db8::1]:8080",
  16893. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16894. EXPECT_EQ("[fe80::1%eth0]",
  16895. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16896. EXPECT_EQ("[fe80::1%eth0]:8080",
  16897. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16898. // Edge case: Empty host (should return as-is)
  16899. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16900. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16901. // This is a known limitation but shouldn't crash
  16902. EXPECT_EQ("[host:name]",
  16903. detail::make_host_and_port_string("host:name", 80, false));
  16904. // Port number edge cases (no validation, but should not crash)
  16905. EXPECT_EQ("example.com:0",
  16906. detail::make_host_and_port_string("example.com", 0, false));
  16907. EXPECT_EQ("example.com:-1",
  16908. detail::make_host_and_port_string("example.com", -1, false));
  16909. EXPECT_EQ("example.com:65535",
  16910. detail::make_host_and_port_string("example.com", 65535, false));
  16911. EXPECT_EQ("example.com:65536",
  16912. detail::make_host_and_port_string("example.com", 65536, false));
  16913. }
  16914. #ifdef CPPHTTPLIB_SSL_ENABLED
  16915. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16916. httplib::SSLClient cli("roblox.com", 443);
  16917. cli.set_follow_location(true);
  16918. auto res = cli.Get("/");
  16919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16920. EXPECT_EQ(StatusCode::OK_200, res->status);
  16921. }
  16922. #endif
  16923. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16924. Server svr;
  16925. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16926. EXPECT_EQ(res.status, 400);
  16927. });
  16928. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16929. auto se = detail::scope_exit([&] {
  16930. svr.stop();
  16931. thread.join();
  16932. ASSERT_FALSE(svr.is_running());
  16933. });
  16934. svr.wait_until_ready();
  16935. Client cli(HOST, PORT);
  16936. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16937. }
  16938. TEST(InvalidHeaderCharsTest, is_field_name) {
  16939. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16940. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16941. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16942. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16943. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16944. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16945. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16946. EXPECT_FALSE(detail::fields::is_field_name(""));
  16947. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16948. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16949. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16950. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16951. }
  16952. TEST(InvalidHeaderCharsTest, is_field_value) {
  16953. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16954. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16955. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16956. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16957. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16958. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16959. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16960. EXPECT_TRUE(detail::fields::is_field_value(""));
  16961. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16962. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16963. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16964. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16965. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16966. }
  16967. TEST(InvalidHeaderCharsTest, OnServer) {
  16968. Server svr;
  16969. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16970. std::string header = "Not Set";
  16971. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16972. res.set_header(header, "value");
  16973. res.set_content("Page Content Page Content", "text/plain");
  16974. });
  16975. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16976. std::string header = "Not Set";
  16977. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16978. res.set_header("X-Test", header);
  16979. res.set_content("Page Content Page Content", "text/plain");
  16980. });
  16981. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16982. auto se = detail::scope_exit([&] {
  16983. svr.stop();
  16984. thread.join();
  16985. ASSERT_FALSE(svr.is_running());
  16986. });
  16987. svr.wait_until_ready();
  16988. Client cli(HOST, PORT);
  16989. {
  16990. auto res = cli.Get(
  16991. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16993. EXPECT_EQ("Page Content Page Content", res->body);
  16994. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16995. }
  16996. {
  16997. auto res = cli.Get(
  16998. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17000. EXPECT_EQ("Page Content Page Content", res->body);
  17001. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17002. }
  17003. }
  17004. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17005. auto handled = false;
  17006. Server svr;
  17007. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17008. thread t = thread([&] { svr.listen(HOST, PORT); });
  17009. auto se = detail::scope_exit([&] {
  17010. svr.stop();
  17011. t.join();
  17012. ASSERT_FALSE(svr.is_running());
  17013. ASSERT_FALSE(handled);
  17014. });
  17015. svr.wait_until_ready();
  17016. auto req = "POST /test HTTP/1.1\r\n"
  17017. "Content-Length: x\r\n"
  17018. "\r\n";
  17019. std::string response;
  17020. ASSERT_TRUE(send_request(1, req, &response));
  17021. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17022. response.substr(0, response.find("\r\n")));
  17023. }
  17024. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17025. // case-insensitive, and a server that receives a 100-continue expectation in
  17026. // an HTTP/1.0 request MUST ignore it.
  17027. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17028. std::string response;
  17029. ASSERT_TRUE(send_request(1, req, &response, port));
  17030. *got_100 = response.find("100 Continue") != std::string::npos;
  17031. }
  17032. class ExpectTokenTest : public ::testing::Test {
  17033. protected:
  17034. void SetUp() override {
  17035. svr_.Post("/p", [](const Request &, Response &res) {
  17036. res.set_content("ok", "text/plain");
  17037. });
  17038. port_ = svr_.bind_to_any_port(HOST);
  17039. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17040. svr_.wait_until_ready();
  17041. }
  17042. void TearDown() override {
  17043. svr_.stop();
  17044. if (thread_.joinable()) { thread_.join(); }
  17045. }
  17046. std::string request(const char *version, const char *expect_value) const {
  17047. return std::string("POST /p ") + version +
  17048. "\r\n"
  17049. "Host: localhost\r\n"
  17050. "Content-Length: 2\r\n"
  17051. "Connection: close\r\n"
  17052. "Expect: " +
  17053. expect_value +
  17054. "\r\n"
  17055. "\r\n"
  17056. "hi";
  17057. }
  17058. Server svr_;
  17059. int port_ = 0;
  17060. thread thread_;
  17061. };
  17062. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17063. bool got_100 = false;
  17064. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17065. EXPECT_TRUE(got_100);
  17066. }
  17067. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17068. bool got_100 = true;
  17069. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17070. EXPECT_FALSE(got_100);
  17071. }
  17072. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17073. bool got_100 = false;
  17074. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17075. EXPECT_TRUE(got_100);
  17076. }
  17077. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17078. bool got_100 = false;
  17079. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17080. EXPECT_TRUE(got_100);
  17081. }
  17082. // `100 Continue` is sent only when the server starts reading the body, so a
  17083. // request rejected before that never invites the client to send it. The
  17084. // requests below carry the expectation but withhold the body, as a client
  17085. // waiting for `100 Continue` would.
  17086. // A POST that expects `100 Continue` and withholds its two-byte body.
  17087. static std::string expect_headers_only(const std::string &path) {
  17088. return "POST " + path +
  17089. " HTTP/1.1\r\n"
  17090. "Host: localhost\r\n"
  17091. "Content-Length: 2\r\n"
  17092. "Expect: 100-continue\r\n"
  17093. "\r\n";
  17094. }
  17095. class ExpectLazyContinueTest : public ::testing::Test {
  17096. protected:
  17097. void SetUp() override {
  17098. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17099. if (req.path == "/pre-routing") {
  17100. res.status = StatusCode::Unauthorized_401;
  17101. return Server::HandlerResponse::Handled;
  17102. }
  17103. return Server::HandlerResponse::Unhandled;
  17104. });
  17105. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17106. if (req.matched_route == "/pre-request") {
  17107. res.status = StatusCode::Forbidden_403;
  17108. return Server::HandlerResponse::Handled;
  17109. }
  17110. return Server::HandlerResponse::Unhandled;
  17111. });
  17112. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17113. res.set_content("ok", "text/plain");
  17114. });
  17115. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17116. res.set_content("ok", "text/plain");
  17117. });
  17118. svr_.Post("/reader-used", [](const Request &, Response &res,
  17119. const ContentReader &content_reader) {
  17120. std::string body;
  17121. content_reader([&](const char *data, size_t len) {
  17122. body.append(data, len);
  17123. return true;
  17124. });
  17125. res.set_content(body, "text/plain");
  17126. });
  17127. svr_.Post("/reader-unused",
  17128. [](const Request &, Response &res, const ContentReader &) {
  17129. res.set_content("ignored", "text/plain");
  17130. });
  17131. port_ = svr_.bind_to_any_port(HOST);
  17132. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17133. svr_.wait_until_ready();
  17134. }
  17135. void TearDown() override {
  17136. svr_.stop();
  17137. if (thread_.joinable()) { thread_.join(); }
  17138. }
  17139. // Sends `req` and reads until the server closes the connection. Returns
  17140. // false if the read had to wait for the client-side timeout instead.
  17141. bool send_until_closed(const std::string &req, std::string *resp) const {
  17142. auto start = std::chrono::steady_clock::now();
  17143. if (!send_request(3, req, resp, port_)) { return false; }
  17144. auto elapsed = std::chrono::steady_clock::now() - start;
  17145. return elapsed < std::chrono::seconds(2);
  17146. }
  17147. // The final response comes without `100 Continue`, and the server closes
  17148. // the connection since the body may or may not follow.
  17149. void expect_final_without_interim(const std::string &path,
  17150. const char *status_line) const {
  17151. std::string resp;
  17152. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17153. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17154. EXPECT_EQ(0u, resp.find(status_line));
  17155. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17156. }
  17157. Server svr_;
  17158. int port_ = 0;
  17159. thread thread_;
  17160. };
  17161. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17162. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17163. }
  17164. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17165. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17166. }
  17167. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17168. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17169. }
  17170. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17171. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17172. }
  17173. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17174. // The body follows once `100 Continue` has had time to arrive.
  17175. auto req = expect_headers_only("/reader-used");
  17176. req.insert(req.size() - 2, "Connection: close\r\n");
  17177. std::string resp;
  17178. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17179. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17180. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17181. EXPECT_NE(std::string::npos, resp.find("hi"));
  17182. }
  17183. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17184. // Large enough for the client to add `Expect: 100-continue` itself.
  17185. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17186. std::atomic<bool> body_sent{false};
  17187. Client cli(HOST, port_);
  17188. auto res = cli.Post(
  17189. "/pre-request", length,
  17190. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17191. body_sent = true;
  17192. std::string chunk(len, 'x');
  17193. sink.write(chunk.data(), chunk.size());
  17194. return true;
  17195. },
  17196. "application/octet-stream");
  17197. ASSERT_TRUE(res);
  17198. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17199. EXPECT_FALSE(body_sent);
  17200. }
  17201. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17202. Server svr;
  17203. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17204. return StatusCode::ExpectationFailed_417;
  17205. });
  17206. svr.Post("/p", [](const Request &, Response &res) {
  17207. res.set_content("ok", "text/plain");
  17208. });
  17209. auto port = svr.bind_to_any_port(HOST);
  17210. thread t = thread([&] { svr.listen_after_bind(); });
  17211. auto se = detail::scope_exit([&] {
  17212. svr.stop();
  17213. t.join();
  17214. });
  17215. svr.wait_until_ready();
  17216. std::string resp;
  17217. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17218. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17219. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17220. // Exactly one response: the route handler must not run after the 417.
  17221. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17222. }
  17223. #ifndef _WIN32
  17224. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17225. static constexpr char reject[] = "Unauthorized";
  17226. static constexpr char accept[] = "Upload accepted";
  17227. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17228. Server svr;
  17229. svr.set_expect_100_continue_handler(
  17230. [](const Request & /*req*/, Response &res) {
  17231. res.status = StatusCode::Unauthorized_401;
  17232. res.set_content(reject, "text/plain");
  17233. return res.status;
  17234. });
  17235. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17236. res.set_content(accept, "text/plain");
  17237. });
  17238. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17239. auto se = detail::scope_exit([&] {
  17240. svr.stop();
  17241. thread.join();
  17242. ASSERT_FALSE(svr.is_running());
  17243. });
  17244. svr.wait_until_ready();
  17245. {
  17246. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17247. curl_easy_init(), &curl_easy_cleanup};
  17248. ASSERT_NE(curl, nullptr);
  17249. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17250. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17251. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17252. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17253. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17254. &curl_slist_free_all};
  17255. ASSERT_NE(list, nullptr);
  17256. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17257. struct read_data {
  17258. size_t read_size;
  17259. size_t total_size;
  17260. } data = {0, total_size};
  17261. using read_callback_t =
  17262. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17263. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17264. void *userdata) -> size_t {
  17265. read_data *d = (read_data *)userdata;
  17266. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17267. std::fill_n(ptr, size * nmemb, 'A');
  17268. d->read_size += size * nmemb;
  17269. return size * nmemb;
  17270. };
  17271. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17272. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17273. std::vector<char> buffer;
  17274. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17275. using write_callback_t =
  17276. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17277. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17278. void *userdata) -> size_t {
  17279. std::vector<char> *buf = (std::vector<char> *)userdata;
  17280. buf->reserve(buf->size() + size * nmemb + 1);
  17281. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17282. return size * nmemb;
  17283. };
  17284. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17285. {
  17286. const auto res = curl_easy_perform(curl.get());
  17287. ASSERT_EQ(res, CURLE_OK);
  17288. }
  17289. {
  17290. auto response_code = long{};
  17291. const auto res =
  17292. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17293. ASSERT_EQ(res, CURLE_OK);
  17294. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17295. }
  17296. {
  17297. auto dl = curl_off_t{};
  17298. const auto res =
  17299. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17300. ASSERT_EQ(res, CURLE_OK);
  17301. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17302. }
  17303. {
  17304. buffer.push_back('\0');
  17305. ASSERT_STRCASEEQ(buffer.data(), reject);
  17306. }
  17307. }
  17308. }
  17309. #endif
  17310. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17311. // Regression test for #2458.
  17312. //
  17313. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17314. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17315. // ticket can make the client socket spuriously readable during the
  17316. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17317. // the client withholds the body and then blocks reading a response that never
  17318. // comes, failing with `Failed to read connection`.
  17319. //
  17320. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17321. // within the timeout. This raw OpenSSL server deliberately never sends
  17322. // `100 Continue`; the client must still deliver the body and receive 200.
  17323. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17324. signal(SIGPIPE, SIG_IGN);
  17325. const auto port = PORT + 4;
  17326. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17327. ASSERT_NE(srv, INVALID_SOCKET);
  17328. int opt = 1;
  17329. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17330. sockaddr_in addr{};
  17331. addr.sin_family = AF_INET;
  17332. addr.sin_port = htons(static_cast<uint16_t>(port));
  17333. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17334. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17335. ASSERT_EQ(0, ::listen(srv, 1));
  17336. std::atomic<size_t> server_body_bytes{0};
  17337. auto server_thread = std::thread([&] {
  17338. sockaddr_in cli_addr{};
  17339. socklen_t cli_len = sizeof(cli_addr);
  17340. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17341. if (cli == INVALID_SOCKET) { return; }
  17342. // Bound the lifetime of the server side so a buggy client (which never
  17343. // sends the body) cannot make this thread block forever on join.
  17344. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17345. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17346. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17347. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17348. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17349. SSL *ssl = SSL_new(ctx);
  17350. SSL_set_fd(ssl, static_cast<int>(cli));
  17351. if (SSL_accept(ssl) > 0) {
  17352. // Read the request headers. Reading here also flushes the TLS 1.3
  17353. // session tickets to the client. Deliberately do NOT send
  17354. // `100 Continue`.
  17355. std::string buf;
  17356. char tmp[1024];
  17357. while (buf.find("\r\n\r\n") == std::string::npos) {
  17358. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17359. if (n <= 0) { break; }
  17360. buf.append(tmp, static_cast<size_t>(n));
  17361. }
  17362. // A correct client sends the body now; count what arrives.
  17363. auto pos = buf.find("\r\n\r\n");
  17364. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17365. while (body < 4096) {
  17366. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17367. if (n <= 0) { break; }
  17368. body += static_cast<size_t>(n);
  17369. }
  17370. server_body_bytes = body;
  17371. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17372. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17373. SSL_shutdown(ssl);
  17374. }
  17375. SSL_free(ssl);
  17376. detail::close_socket(cli);
  17377. SSL_CTX_free(ctx);
  17378. });
  17379. auto se = detail::scope_exit([&] {
  17380. server_thread.join();
  17381. detail::close_socket(srv);
  17382. });
  17383. SSLClient cli("127.0.0.1", port);
  17384. cli.enable_server_certificate_verification(false);
  17385. cli.set_connection_timeout(5, 0);
  17386. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17387. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17388. std::string body(4096, 'A');
  17389. auto res = cli.Put("/api/test", body, "application/json");
  17390. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17391. EXPECT_EQ(StatusCode::OK_200, res->status);
  17392. EXPECT_EQ(body.size(), server_body_bytes.load());
  17393. }
  17394. #endif
  17395. template <typename S, typename C>
  17396. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17397. svr.Get("/stream", [&](const Request &, Response &res) {
  17398. auto data = new std::string("01234567890123456789");
  17399. res.set_content_provider(
  17400. data->size(), "text/plain",
  17401. [&, data](size_t offset, size_t length, DataSink &sink) {
  17402. const size_t DATA_CHUNK_SIZE = 4;
  17403. const auto &d = *data;
  17404. std::this_thread::sleep_for(std::chrono::seconds(1));
  17405. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17406. return true;
  17407. },
  17408. [data](bool success) {
  17409. EXPECT_FALSE(success);
  17410. delete data;
  17411. });
  17412. });
  17413. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17414. auto i = new size_t(0);
  17415. res.set_content_provider(
  17416. "text/plain",
  17417. [i](size_t, DataSink &sink) {
  17418. if (*i < 5) {
  17419. std::this_thread::sleep_for(std::chrono::seconds(1));
  17420. sink.write("abcd", 4);
  17421. (*i)++;
  17422. } else {
  17423. sink.done();
  17424. }
  17425. return true;
  17426. },
  17427. [i](bool success) {
  17428. EXPECT_FALSE(success);
  17429. delete i;
  17430. });
  17431. });
  17432. svr.Get("/chunked", [&](const Request &, Response &res) {
  17433. auto i = new size_t(0);
  17434. res.set_chunked_content_provider(
  17435. "text/plain",
  17436. [i](size_t, DataSink &sink) {
  17437. if (*i < 5) {
  17438. std::this_thread::sleep_for(std::chrono::seconds(1));
  17439. sink.os << "abcd";
  17440. (*i)++;
  17441. } else {
  17442. sink.done();
  17443. }
  17444. return true;
  17445. },
  17446. [i](bool success) {
  17447. EXPECT_FALSE(success);
  17448. delete i;
  17449. });
  17450. });
  17451. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17452. auto se = detail::scope_exit([&] {
  17453. svr.stop();
  17454. listen_thread.join();
  17455. ASSERT_FALSE(svr.is_running());
  17456. });
  17457. svr.wait_until_ready();
  17458. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17459. {
  17460. auto start = std::chrono::steady_clock::now();
  17461. auto res = cli.Get("/stream");
  17462. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17463. std::chrono::steady_clock::now() - start)
  17464. .count();
  17465. ASSERT_FALSE(res);
  17466. EXPECT_EQ(Error::Read, res.error());
  17467. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17468. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17469. }
  17470. {
  17471. auto start = std::chrono::steady_clock::now();
  17472. auto res = cli.Get("/stream_without_length");
  17473. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17474. std::chrono::steady_clock::now() - start)
  17475. .count();
  17476. ASSERT_FALSE(res);
  17477. EXPECT_EQ(Error::Read, res.error());
  17478. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17479. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17480. }
  17481. {
  17482. auto start = std::chrono::steady_clock::now();
  17483. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17484. EXPECT_EQ("abcd", string(data, data_length));
  17485. return true;
  17486. });
  17487. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17488. std::chrono::steady_clock::now() - start)
  17489. .count();
  17490. ASSERT_FALSE(res);
  17491. EXPECT_EQ(Error::Read, res.error());
  17492. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17493. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17494. }
  17495. }
  17496. TEST(MaxTimeoutTest, ContentStream) {
  17497. time_t timeout = 2000;
  17498. time_t threshold = 200;
  17499. Server svr;
  17500. Client cli("localhost", PORT);
  17501. max_timeout_test(svr, cli, timeout, threshold);
  17502. }
  17503. #ifdef CPPHTTPLIB_SSL_ENABLED
  17504. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17505. time_t timeout = 2000;
  17506. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17508. SSLClient cli("localhost", PORT);
  17509. cli.enable_server_certificate_verification(false);
  17510. max_timeout_test(svr, cli, timeout, threshold);
  17511. }
  17512. #endif
  17513. class EventDispatcher {
  17514. public:
  17515. EventDispatcher() {}
  17516. bool wait_event(DataSink *sink) {
  17517. unique_lock<mutex> lk(m_);
  17518. int id = id_;
  17519. // Wait with timeout to prevent hanging if client disconnects
  17520. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17521. [&] { return cid_ == id; })) {
  17522. return false; // Timeout occurred
  17523. }
  17524. sink->write(message_.data(), message_.size());
  17525. return true;
  17526. }
  17527. void send_event(const string &message) {
  17528. lock_guard<mutex> lk(m_);
  17529. cid_ = id_++;
  17530. message_ = message;
  17531. cv_.notify_all();
  17532. }
  17533. private:
  17534. mutex m_;
  17535. condition_variable cv_;
  17536. atomic_int id_{0};
  17537. atomic_int cid_{-1};
  17538. string message_;
  17539. };
  17540. TEST(ClientInThreadTest, Issue2068) {
  17541. EventDispatcher ed;
  17542. Server svr;
  17543. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17544. res.set_chunked_content_provider("text/event-stream",
  17545. [&](size_t /*offset*/, DataSink &sink) {
  17546. return ed.wait_event(&sink);
  17547. });
  17548. });
  17549. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17550. svr.wait_until_ready();
  17551. thread event_thread([&] {
  17552. int id = 0;
  17553. while (svr.is_running()) {
  17554. this_thread::sleep_for(chrono::milliseconds(500));
  17555. std::stringstream ss;
  17556. ss << "data: " << id << "\n\n";
  17557. ed.send_event(ss.str());
  17558. id++;
  17559. }
  17560. });
  17561. auto se = detail::scope_exit([&] {
  17562. svr.stop();
  17563. listen_thread.join();
  17564. event_thread.join();
  17565. ASSERT_FALSE(svr.is_running());
  17566. });
  17567. {
  17568. auto client = detail::make_unique<Client>(HOST, PORT);
  17569. client->set_read_timeout(std::chrono::minutes(10));
  17570. std::atomic<bool> stop{false};
  17571. std::thread t([&] {
  17572. client->Get("/event1",
  17573. [&](const char *, size_t) -> bool { return !stop; });
  17574. });
  17575. std::this_thread::sleep_for(std::chrono::seconds(2));
  17576. stop = true;
  17577. client->stop();
  17578. t.join();
  17579. // Reset client after thread has finished
  17580. client.reset();
  17581. }
  17582. }
  17583. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17584. auto handled = false;
  17585. Server svr;
  17586. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17587. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17588. auto se = detail::scope_exit([&] {
  17589. svr.stop();
  17590. t.join();
  17591. ASSERT_FALSE(svr.is_running());
  17592. ASSERT_FALSE(handled);
  17593. });
  17594. svr.wait_until_ready();
  17595. // Two Content-Length headers with different values — must be rejected
  17596. auto req = "POST /test HTTP/1.1\r\n"
  17597. "Content-Length: 5\r\n"
  17598. "Content-Length: 10\r\n"
  17599. "\r\n"
  17600. "hello";
  17601. std::string response;
  17602. ASSERT_TRUE(send_request(1, req, &response));
  17603. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17604. response.substr(0, response.find("\r\n")));
  17605. }
  17606. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17607. auto handled = false;
  17608. Server svr;
  17609. svr.Post("/test", [&](const Request &, Response &res) {
  17610. handled = true;
  17611. res.set_content("ok", "text/plain");
  17612. });
  17613. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17614. auto se = detail::scope_exit([&] {
  17615. svr.stop();
  17616. t.join();
  17617. ASSERT_FALSE(svr.is_running());
  17618. ASSERT_TRUE(handled);
  17619. });
  17620. svr.wait_until_ready();
  17621. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17622. auto req = "POST /test HTTP/1.1\r\n"
  17623. "Host: localhost\r\n"
  17624. "Content-Length: 5\r\n"
  17625. "Content-Length: 5\r\n"
  17626. "\r\n"
  17627. "hello";
  17628. std::string response;
  17629. ASSERT_TRUE(send_request(1, req, &response));
  17630. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17631. }
  17632. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17633. Server svr;
  17634. svr.Get("/test", [](const Request &, Response &res) {
  17635. res.set_content("ok", "text/plain");
  17636. });
  17637. auto port = svr.bind_to_any_port(HOST);
  17638. thread t = thread([&] { svr.listen_after_bind(); });
  17639. auto se = detail::scope_exit([&] {
  17640. svr.stop();
  17641. t.join();
  17642. ASSERT_FALSE(svr.is_running());
  17643. });
  17644. svr.wait_until_ready();
  17645. auto status_line = [&](const std::string &host_lines) {
  17646. std::string res;
  17647. send_request(
  17648. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17649. &res, port);
  17650. return res.substr(0, res.find("\r\n"));
  17651. };
  17652. const char *accepted[] = {
  17653. "Host: localhost\r\n",
  17654. "Host: a.example:8080\r\n",
  17655. "Host: my_service\r\n",
  17656. "Host: [::1]:8080\r\n",
  17657. "Host: [fe80::1%25eth0]\r\n",
  17658. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17659. };
  17660. for (auto host_lines : accepted) {
  17661. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17662. }
  17663. const char *rejected[] = {
  17664. "Host: a.example\r\nHost: b.example\r\n",
  17665. "Host: a.example\r\nHost: a.example\r\n",
  17666. "Host: a@b.example\r\n",
  17667. "Host: a.example/b\r\n",
  17668. "Host: a.example\\b\r\n",
  17669. "Host: a.example?b\r\n",
  17670. "Host: a.example#b\r\n",
  17671. "Host: a.example b.example\r\n",
  17672. };
  17673. for (auto host_lines : rejected) {
  17674. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17675. << host_lines;
  17676. }
  17677. }
  17678. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17679. Server svr;
  17680. svr.Get("/", [](const Request &req, Response &res) {
  17681. EXPECT_EQ(2U, req.trailers.size());
  17682. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17683. // Denied
  17684. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17685. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17686. // Accepted
  17687. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17688. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17689. EXPECT_TRUE(req.has_trailer("X-World"));
  17690. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17691. res.set_content("ok", "text/plain");
  17692. });
  17693. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17694. auto se = detail::scope_exit([&] {
  17695. svr.stop();
  17696. t.join();
  17697. ASSERT_FALSE(svr.is_running());
  17698. });
  17699. svr.wait_until_ready();
  17700. const std::string req = "GET / HTTP/1.1\r\n"
  17701. "Transfer-Encoding: chunked\r\n"
  17702. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17703. "\r\n"
  17704. "0\r\n"
  17705. "Content-Length: 10\r\n"
  17706. "Host: internal.local\r\n"
  17707. "Content-Type: malicious/content\r\n"
  17708. "Cookie: any\r\n"
  17709. "Set-Cookie: any\r\n"
  17710. "X-Forwarded-For: attacker.com\r\n"
  17711. "X-Real-Ip: 1.1.1.1\r\n"
  17712. "X-Hello: hello\r\n"
  17713. "X-World: world\r\n"
  17714. "\r\n";
  17715. std::string res;
  17716. ASSERT_TRUE(send_request(1, req, &res));
  17717. }
  17718. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17719. // several field lines, and the combined value is what has to be parsed. A
  17720. // Trailer field split across lines therefore declares every name it lists;
  17721. // reading only the first line silently drops the trailers the later lines
  17722. // declare. The prohibited-trailer filter still applies to every line.
  17723. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17724. Server svr;
  17725. size_t observed_trailer_count = 0;
  17726. std::string observed_hello;
  17727. std::string observed_world;
  17728. bool observed_content_length = true;
  17729. svr.Get("/", [&](const Request &req, Response &res) {
  17730. observed_trailer_count = req.trailers.size();
  17731. observed_hello = req.get_trailer_value("X-Hello");
  17732. observed_world = req.get_trailer_value("X-World");
  17733. observed_content_length = req.has_trailer("Content-Length");
  17734. res.set_content("ok", "text/plain");
  17735. });
  17736. auto port = svr.bind_to_any_port(HOST);
  17737. thread t = thread([&]() { svr.listen_after_bind(); });
  17738. auto se = detail::scope_exit([&] {
  17739. svr.stop();
  17740. t.join();
  17741. ASSERT_FALSE(svr.is_running());
  17742. });
  17743. svr.wait_until_ready();
  17744. const std::string req = "GET / HTTP/1.1\r\n"
  17745. "Host: localhost\r\n"
  17746. "Transfer-Encoding: chunked\r\n"
  17747. "Trailer: X-Hello\r\n"
  17748. "Trailer: X-World, Content-Length\r\n"
  17749. "\r\n"
  17750. "0\r\n"
  17751. "X-Hello: hello\r\n"
  17752. "X-World: world\r\n"
  17753. "Content-Length: 10\r\n"
  17754. "\r\n";
  17755. std::string res;
  17756. ASSERT_TRUE(send_request(1, req, &res, port));
  17757. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17758. // Accepted: both field lines contribute to the declared set
  17759. EXPECT_EQ(2U, observed_trailer_count);
  17760. EXPECT_EQ(observed_hello, "hello");
  17761. EXPECT_EQ(observed_world, "world");
  17762. // Denied: a prohibited name stays prohibited on a later field line
  17763. EXPECT_FALSE(observed_content_length);
  17764. }
  17765. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17766. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17767. // unbounded run of fields that are never declared, because the counter would
  17768. // only advance for declared fields.
  17769. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17770. Server svr;
  17771. bool handler_called = false;
  17772. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17773. handler_called = true;
  17774. res.set_content("ok", "text/plain");
  17775. });
  17776. auto port = svr.bind_to_any_port(HOST);
  17777. thread t = thread([&]() { svr.listen_after_bind(); });
  17778. auto se = detail::scope_exit([&] {
  17779. svr.stop();
  17780. t.join();
  17781. ASSERT_FALSE(svr.is_running());
  17782. });
  17783. svr.wait_until_ready();
  17784. // Declare nothing, then send far more undeclared trailer fields than the
  17785. // header-count limit. Parsing must stop and reject the request rather than
  17786. // read every line.
  17787. std::string req = "GET / HTTP/1.1\r\n"
  17788. "Transfer-Encoding: chunked\r\n"
  17789. "\r\n"
  17790. "0\r\n";
  17791. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17792. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17793. }
  17794. req += "\r\n";
  17795. std::string res;
  17796. ASSERT_TRUE(send_request(1, req, &res, port));
  17797. // The request is rejected before the handler runs.
  17798. EXPECT_FALSE(handler_called);
  17799. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17800. }
  17801. // The set of declared trailer names is capped so a peer cannot grow it without
  17802. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17803. // declared past the cap is not honored, even if the field is actually sent.
  17804. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17805. Server svr;
  17806. // One name inside the cap and one past it, so the test tracks the cap rather
  17807. // than a fixed count.
  17808. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17809. const std::string within_cap_name = "X-T-0";
  17810. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17811. bool observed_within_cap = false;
  17812. bool observed_past_cap = false;
  17813. svr.Get("/", [&](const Request &req, Response &res) {
  17814. observed_within_cap = req.has_trailer(within_cap_name);
  17815. observed_past_cap = req.has_trailer(past_cap_name);
  17816. res.set_content("ok", "text/plain");
  17817. });
  17818. auto port = svr.bind_to_any_port(HOST);
  17819. thread t = thread([&]() { svr.listen_after_bind(); });
  17820. auto se = detail::scope_exit([&] {
  17821. svr.stop();
  17822. t.join();
  17823. ASSERT_FALSE(svr.is_running());
  17824. });
  17825. svr.wait_until_ready();
  17826. // Declare more trailer names than the cap in a single Trailer field, then
  17827. // actually send the first (within the cap) and the last (past it).
  17828. std::string trailer_decl = "Trailer: ";
  17829. for (int i = 0; i < declared_count; i++) {
  17830. if (i != 0) { trailer_decl += ", "; }
  17831. trailer_decl += "X-T-" + std::to_string(i);
  17832. }
  17833. trailer_decl += "\r\n";
  17834. const std::string req = "GET / HTTP/1.1\r\n"
  17835. "Host: localhost\r\n"
  17836. "Transfer-Encoding: chunked\r\n" +
  17837. trailer_decl +
  17838. "\r\n"
  17839. "0\r\n" +
  17840. within_cap_name + ": a\r\n" + past_cap_name +
  17841. ": b\r\n"
  17842. "\r\n";
  17843. std::string res;
  17844. ASSERT_TRUE(send_request(1, req, &res, port));
  17845. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17846. // A name within the cap is honored; one declared past the cap is dropped.
  17847. EXPECT_TRUE(observed_within_cap);
  17848. EXPECT_FALSE(observed_past_cap);
  17849. }
  17850. // A direct client that is not listed in trusted_proxies must not be able to
  17851. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17852. // the peer address on the actual TCP connection determines whether the
  17853. // header is honored.
  17854. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17855. Server svr;
  17856. // Deliberately does NOT include the loopback address the test client
  17857. // actually connects from, so the direct connection is not a trusted proxy.
  17858. svr.set_trusted_proxies({"203.0.113.66"});
  17859. std::string observed_remote_addr;
  17860. svr.Get("/ip", [&](const Request &req, Response &res) {
  17861. observed_remote_addr = req.remote_addr;
  17862. res.set_content("ok", "text/plain");
  17863. });
  17864. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17865. auto se = detail::scope_exit([&] {
  17866. svr.stop();
  17867. t.join();
  17868. ASSERT_FALSE(svr.is_running());
  17869. });
  17870. svr.wait_until_ready();
  17871. Client cli(HOST, PORT);
  17872. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17874. EXPECT_EQ(StatusCode::OK_200, res->status);
  17875. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17876. // ignored entirely and the real connection-level address retained.
  17877. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17878. observed_remote_addr == "127.0.0.1");
  17879. }
  17880. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17881. Server svr;
  17882. std::string observed_remote_addr;
  17883. std::string observed_xff;
  17884. svr.Get("/ip", [&](const Request &req, Response &res) {
  17885. observed_remote_addr = req.remote_addr;
  17886. observed_xff = req.get_header_value("X-Forwarded-For");
  17887. res.set_content("ok", "text/plain");
  17888. });
  17889. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17890. auto se = detail::scope_exit([&] {
  17891. svr.stop();
  17892. t.join();
  17893. ASSERT_FALSE(svr.is_running());
  17894. });
  17895. svr.wait_until_ready();
  17896. Client cli(HOST, PORT);
  17897. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17899. EXPECT_EQ(StatusCode::OK_200, res->status);
  17900. EXPECT_EQ(observed_xff, "203.0.113.66");
  17901. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17902. observed_remote_addr == "127.0.0.1");
  17903. }
  17904. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17905. Server svr;
  17906. svr.set_trusted_proxies({"203.0.113.66"});
  17907. std::string observed_remote_addr;
  17908. std::string observed_xff;
  17909. svr.Get("/ip", [&](const Request &req, Response &res) {
  17910. observed_remote_addr = req.remote_addr;
  17911. observed_xff = req.get_header_value("X-Forwarded-For");
  17912. res.set_content("ok", "text/plain");
  17913. });
  17914. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17915. auto se = detail::scope_exit([&] {
  17916. svr.stop();
  17917. t.join();
  17918. ASSERT_FALSE(svr.is_running());
  17919. });
  17920. svr.wait_until_ready();
  17921. Client cli(HOST, PORT);
  17922. auto res = cli.Get("/ip");
  17923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17924. EXPECT_EQ(StatusCode::OK_200, res->status);
  17925. EXPECT_EQ(observed_xff, "");
  17926. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17927. observed_remote_addr == "127.0.0.1");
  17928. }
  17929. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17930. Server svr;
  17931. // Include the loopback address the test client actually connects from, so
  17932. // the direct connection itself is recognized as the trusted proxy hop.
  17933. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17934. std::string observed_remote_addr;
  17935. std::string observed_xff;
  17936. svr.Get("/ip", [&](const Request &req, Response &res) {
  17937. observed_remote_addr = req.remote_addr;
  17938. observed_xff = req.get_header_value("X-Forwarded-For");
  17939. res.set_content("ok", "text/plain");
  17940. });
  17941. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17942. auto se = detail::scope_exit([&] {
  17943. svr.stop();
  17944. t.join();
  17945. ASSERT_FALSE(svr.is_running());
  17946. });
  17947. svr.wait_until_ready();
  17948. Client cli(HOST, PORT);
  17949. auto res = cli.Get(
  17950. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17952. EXPECT_EQ(StatusCode::OK_200, res->status);
  17953. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17954. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17955. }
  17956. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17957. Server svr;
  17958. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17959. std::string observed_remote_addr;
  17960. std::string observed_xff;
  17961. svr.Get("/ip", [&](const Request &req, Response &res) {
  17962. observed_remote_addr = req.remote_addr;
  17963. observed_xff = req.get_header_value("X-Forwarded-For");
  17964. res.set_content("ok", "text/plain");
  17965. });
  17966. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17967. auto se = detail::scope_exit([&] {
  17968. svr.stop();
  17969. t.join();
  17970. ASSERT_FALSE(svr.is_running());
  17971. });
  17972. svr.wait_until_ready();
  17973. Client cli(HOST, PORT);
  17974. auto res = cli.Get(
  17975. "/ip",
  17976. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17978. EXPECT_EQ(StatusCode::OK_200, res->status);
  17979. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17980. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17981. }
  17982. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17983. Server svr;
  17984. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17985. std::string observed_remote_addr;
  17986. std::string observed_xff;
  17987. svr.Get("/ip", [&](const Request &req, Response &res) {
  17988. observed_remote_addr = req.remote_addr;
  17989. observed_xff = req.get_header_value("X-Forwarded-For");
  17990. res.set_content("ok", "text/plain");
  17991. });
  17992. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17993. auto se = detail::scope_exit([&] {
  17994. svr.stop();
  17995. t.join();
  17996. ASSERT_FALSE(svr.is_running());
  17997. });
  17998. svr.wait_until_ready();
  17999. Client cli(HOST, PORT);
  18000. auto res = cli.Get(
  18001. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18003. EXPECT_EQ(StatusCode::OK_200, res->status);
  18004. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18005. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18006. // and must not be selected.
  18007. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18008. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18009. }
  18010. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18011. Server svr;
  18012. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18013. std::string observed_remote_addr;
  18014. svr.Get("/ip", [&](const Request &req, Response &res) {
  18015. observed_remote_addr = req.remote_addr;
  18016. res.set_content("ok", "text/plain");
  18017. });
  18018. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18019. auto se = detail::scope_exit([&] {
  18020. svr.stop();
  18021. t.join();
  18022. ASSERT_FALSE(svr.is_running());
  18023. });
  18024. svr.wait_until_ready();
  18025. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18026. // a forged address and the trusted proxy's own address; the forged value must
  18027. // not win over the address the trusted proxy actually recorded.
  18028. Client cli(HOST, PORT);
  18029. auto res = cli.Get(
  18030. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18032. EXPECT_EQ(StatusCode::OK_200, res->status);
  18033. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18034. }
  18035. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18036. Server svr;
  18037. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18038. std::string observed_remote_addr;
  18039. std::string observed_xff;
  18040. svr.Get("/ip", [&](const Request &req, Response &res) {
  18041. observed_remote_addr = req.remote_addr;
  18042. observed_xff = req.get_header_value("X-Forwarded-For");
  18043. res.set_content("ok", "text/plain");
  18044. });
  18045. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18046. auto se = detail::scope_exit([&] {
  18047. svr.stop();
  18048. t.join();
  18049. ASSERT_FALSE(svr.is_running());
  18050. });
  18051. svr.wait_until_ready();
  18052. Client cli(HOST, PORT);
  18053. auto res = cli.Get(
  18054. "/ip",
  18055. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18057. EXPECT_EQ(StatusCode::OK_200, res->status);
  18058. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18059. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18060. }
  18061. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18062. Server svr;
  18063. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18064. std::string observed_remote_addr;
  18065. std::string observed_xff;
  18066. svr.Get("/ip", [&](const Request &req, Response &res) {
  18067. observed_remote_addr = req.remote_addr;
  18068. observed_xff = req.get_header_value("X-Forwarded-For");
  18069. res.set_content("ok", "text/plain");
  18070. });
  18071. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18072. auto se = detail::scope_exit([&] {
  18073. svr.stop();
  18074. t.join();
  18075. ASSERT_FALSE(svr.is_running());
  18076. });
  18077. svr.wait_until_ready();
  18078. std::string raw_req =
  18079. "GET /ip HTTP/1.1\r\n"
  18080. "Host: localhost\r\n"
  18081. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18082. "Connection: close\r\n"
  18083. "\r\n";
  18084. std::string out;
  18085. ASSERT_TRUE(send_request(5, raw_req, &out));
  18086. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18087. // Header parser trims surrounding whitespace of the header value
  18088. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18089. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18090. }
  18091. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18092. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18093. // their own X-Forwarded-For as a separate field line rather than extending the
  18094. // one the client sent, so every occurrence has to be taken into account.
  18095. // Reading only the first one hands back the address the client chose.
  18096. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18097. Server svr;
  18098. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18099. std::string observed_remote_addr;
  18100. size_t observed_xff_count = 0;
  18101. svr.Get("/ip", [&](const Request &req, Response &res) {
  18102. observed_remote_addr = req.remote_addr;
  18103. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18104. res.set_content("ok", "text/plain");
  18105. });
  18106. auto port = svr.bind_to_any_port(HOST);
  18107. thread t = thread([&]() { svr.listen_after_bind(); });
  18108. auto se = detail::scope_exit([&] {
  18109. svr.stop();
  18110. t.join();
  18111. ASSERT_FALSE(svr.is_running());
  18112. });
  18113. svr.wait_until_ready();
  18114. // The client supplies the first field line; the trusted proxy appends the
  18115. // address it observed as a second one.
  18116. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18117. "Host: localhost\r\n"
  18118. "X-Forwarded-For: 1.2.3.4\r\n"
  18119. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18120. "Connection: close\r\n"
  18121. "\r\n";
  18122. std::string out;
  18123. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18124. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18125. EXPECT_EQ(observed_xff_count, 2U);
  18126. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18127. // The same chain spread over one field line per hop derives the same client
  18128. // address, i.e. the split and the comma-joined representations agree.
  18129. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18130. "Host: localhost\r\n"
  18131. "X-Forwarded-For: 1.2.3.4\r\n"
  18132. "X-Forwarded-For: 198.51.100.23\r\n"
  18133. "X-Forwarded-For: 192.0.2.45\r\n"
  18134. "Connection: close\r\n"
  18135. "\r\n";
  18136. out.clear();
  18137. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18138. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18139. EXPECT_EQ(observed_xff_count, 3U);
  18140. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18141. }
  18142. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18143. // crash the server (it used to call front() on an empty vector inside
  18144. // get_client_ip). The connection-level remote address must be retained instead.
  18145. static void run_malformed_xff_test(const std::string &xff_value) {
  18146. Server svr;
  18147. svr.set_trusted_proxies({"192.0.2.45"});
  18148. std::string observed_remote_addr;
  18149. svr.Get("/ip", [&](const Request &req, Response &res) {
  18150. observed_remote_addr = req.remote_addr;
  18151. res.set_content("ok", "text/plain");
  18152. });
  18153. int port = 0;
  18154. thread t = thread([&]() {
  18155. port = svr.bind_to_any_port(HOST);
  18156. svr.listen_after_bind();
  18157. });
  18158. auto se = detail::scope_exit([&] {
  18159. svr.stop();
  18160. t.join();
  18161. ASSERT_FALSE(svr.is_running());
  18162. });
  18163. svr.wait_until_ready();
  18164. Client cli(HOST, port);
  18165. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18167. EXPECT_EQ(StatusCode::OK_200, res->status);
  18168. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18169. observed_remote_addr == "127.0.0.1");
  18170. }
  18171. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18172. run_malformed_xff_test("");
  18173. }
  18174. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18175. run_malformed_xff_test(",");
  18176. }
  18177. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18178. run_malformed_xff_test(", , ,");
  18179. }
  18180. // The same rule applies to Accept: a request whose acceptable types are spread
  18181. // over several field lines must be negotiated against all of them.
  18182. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18183. // case-insensitive connection options. Comparing the whole field value against
  18184. // one option misses a client that sends several of them, and misses every
  18185. // casing but the one written in the comparison.
  18186. //
  18187. // Sends req, reads the response, then reuses the same socket for a second
  18188. // request to find out whether the server kept the connection.
  18189. static void probe_connection_reuse(int port, const std::string &req,
  18190. bool *announced_close, bool *reusable) {
  18191. auto error = Error::Success;
  18192. auto sock = detail::create_client_socket(
  18193. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18194. /*connection_timeout_sec=*/5, 0,
  18195. /*read_timeout_sec=*/1, 0,
  18196. /*write_timeout_sec=*/5, 0, std::string(), error);
  18197. ASSERT_NE(sock, INVALID_SOCKET);
  18198. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18199. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18200. "Host: localhost\r\n"
  18201. "Connection: close\r\n"
  18202. "\r\n";
  18203. std::string first_response;
  18204. std::string second_response;
  18205. detail::process_client_socket(
  18206. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18207. [&](Stream &strm) {
  18208. if (strm.write(req.data(), req.size()) !=
  18209. static_cast<ssize_t>(req.size())) {
  18210. return false;
  18211. }
  18212. char buf[512];
  18213. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18214. // Headers plus the two-byte body of the handler below
  18215. while (reader.getline()) {
  18216. first_response += reader.ptr();
  18217. if (first_response.find("ok") != std::string::npos) { break; }
  18218. }
  18219. if (strm.write(second.data(), second.size()) !=
  18220. static_cast<ssize_t>(second.size())) {
  18221. return true;
  18222. }
  18223. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18224. while (reader2.getline()) {
  18225. second_response += reader2.ptr();
  18226. if (second_response.find("ok") != std::string::npos) { break; }
  18227. }
  18228. return true;
  18229. });
  18230. *announced_close =
  18231. first_response.find("Connection: close") != std::string::npos;
  18232. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18233. }
  18234. class ConnectionTokenTest : public ::testing::Test {
  18235. protected:
  18236. void SetUp() override {
  18237. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18238. res.set_content("ok", "text/plain");
  18239. });
  18240. port_ = svr_.bind_to_any_port(HOST);
  18241. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18242. svr_.wait_until_ready();
  18243. }
  18244. void TearDown() override {
  18245. svr_.stop();
  18246. if (thread_.joinable()) { thread_.join(); }
  18247. }
  18248. Server svr_;
  18249. int port_ = 0;
  18250. thread thread_;
  18251. };
  18252. // "close" alongside another option still closes the connection, and the
  18253. // response says so rather than leaving the peer to discover it.
  18254. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18255. bool announced_close = false;
  18256. bool reusable = true;
  18257. probe_connection_reuse(port_,
  18258. "GET /keepalive HTTP/1.1\r\n"
  18259. "Host: localhost\r\n"
  18260. "Connection: keep-alive, close\r\n"
  18261. "\r\n",
  18262. &announced_close, &reusable);
  18263. EXPECT_TRUE(announced_close);
  18264. EXPECT_FALSE(reusable);
  18265. }
  18266. // "close" split over two field lines is the same list, so it is honored too.
  18267. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18268. bool announced_close = false;
  18269. bool reusable = true;
  18270. probe_connection_reuse(port_,
  18271. "GET /keepalive HTTP/1.1\r\n"
  18272. "Host: localhost\r\n"
  18273. "Connection: keep-alive\r\n"
  18274. "Connection: close\r\n"
  18275. "\r\n",
  18276. &announced_close, &reusable);
  18277. EXPECT_TRUE(announced_close);
  18278. EXPECT_FALSE(reusable);
  18279. }
  18280. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18281. // keep-alive in the spelling everyone actually sends keeps its connection.
  18282. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18283. bool announced_close = false;
  18284. bool reusable = false;
  18285. probe_connection_reuse(port_,
  18286. "GET /keepalive HTTP/1.0\r\n"
  18287. "Host: localhost\r\n"
  18288. "Connection: keep-alive\r\n"
  18289. "\r\n",
  18290. &announced_close, &reusable);
  18291. EXPECT_FALSE(announced_close);
  18292. EXPECT_TRUE(reusable);
  18293. }
  18294. // A token the value merely contains is not the token itself.
  18295. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18296. bool announced_close = false;
  18297. bool reusable = false;
  18298. probe_connection_reuse(port_,
  18299. "GET /keepalive HTTP/1.1\r\n"
  18300. "Host: localhost\r\n"
  18301. "Connection: notclose\r\n"
  18302. "\r\n",
  18303. &announced_close, &reusable);
  18304. EXPECT_FALSE(announced_close);
  18305. EXPECT_TRUE(reusable);
  18306. }
  18307. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18308. Server svr;
  18309. std::vector<std::string> observed_types;
  18310. svr.Get("/", [&](const Request &req, Response &res) {
  18311. observed_types = req.accept_content_types;
  18312. res.set_content("ok", "text/plain");
  18313. });
  18314. auto port = svr.bind_to_any_port(HOST);
  18315. thread t = thread([&]() { svr.listen_after_bind(); });
  18316. auto se = detail::scope_exit([&] {
  18317. svr.stop();
  18318. t.join();
  18319. ASSERT_FALSE(svr.is_running());
  18320. });
  18321. svr.wait_until_ready();
  18322. Client cli(HOST, port);
  18323. Headers headers;
  18324. headers.emplace("Accept", "text/plain;q=0.5");
  18325. headers.emplace("Accept", "application/json");
  18326. auto res = cli.Get("/", headers);
  18327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18328. EXPECT_EQ(StatusCode::OK_200, res->status);
  18329. // Sorted by q-value, so the second field line's type comes first
  18330. ASSERT_EQ(2U, observed_types.size());
  18331. EXPECT_EQ("application/json", observed_types[0]);
  18332. EXPECT_EQ("text/plain", observed_types[1]);
  18333. }
  18334. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18335. // empty field line must not contribute a bare comma to the combined value.
  18336. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18337. Server svr;
  18338. std::vector<std::string> observed_types;
  18339. svr.Get("/", [&](const Request &req, Response &res) {
  18340. observed_types = req.accept_content_types;
  18341. res.set_content("ok", "text/plain");
  18342. });
  18343. auto port = svr.bind_to_any_port(HOST);
  18344. thread t = thread([&]() { svr.listen_after_bind(); });
  18345. auto se = detail::scope_exit([&] {
  18346. svr.stop();
  18347. t.join();
  18348. ASSERT_FALSE(svr.is_running());
  18349. });
  18350. svr.wait_until_ready();
  18351. // Empty first field line, then a real one
  18352. std::string raw_req = "GET / HTTP/1.1\r\n"
  18353. "Host: localhost\r\n"
  18354. "Accept:\r\n"
  18355. "Accept: application/json\r\n"
  18356. "Connection: close\r\n"
  18357. "\r\n";
  18358. std::string out;
  18359. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18360. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18361. ASSERT_EQ(1U, observed_types.size());
  18362. EXPECT_EQ("application/json", observed_types[0]);
  18363. }
  18364. // The skip in get_combined_header_value() is what keeps an empty field line
  18365. // from contributing a bare comma. Only a trailing empty field line exercises
  18366. // it: a leading one is already covered by the "combined is still empty" check,
  18367. // and parse_accept_header() now ignores the empty element either way, so the
  18368. // request-level test above can no longer tell the two apart.
  18369. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18370. Headers headers;
  18371. headers.emplace("Accept", "text/html");
  18372. headers.emplace("Accept", "");
  18373. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18374. headers.clear();
  18375. headers.emplace("Accept", "");
  18376. headers.emplace("Accept", "application/json");
  18377. EXPECT_EQ("application/json",
  18378. detail::get_combined_header_value(headers, "Accept"));
  18379. }
  18380. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18381. // An encoding offered on a later Accept-Encoding field line is still offered.
  18382. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18383. Server svr;
  18384. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18385. res.set_content(std::string(1024, 'x'), "text/plain");
  18386. });
  18387. auto port = svr.bind_to_any_port(HOST);
  18388. thread t = thread([&]() { svr.listen_after_bind(); });
  18389. auto se = detail::scope_exit([&] {
  18390. svr.stop();
  18391. t.join();
  18392. ASSERT_FALSE(svr.is_running());
  18393. });
  18394. svr.wait_until_ready();
  18395. Client cli(HOST, port);
  18396. cli.set_decompress(false);
  18397. Headers headers;
  18398. headers.emplace("Accept-Encoding", "identity");
  18399. headers.emplace("Accept-Encoding", "gzip");
  18400. auto res = cli.Get("/", headers);
  18401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18402. EXPECT_EQ(StatusCode::OK_200, res->status);
  18403. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18404. }
  18405. #endif
  18406. #ifndef _WIN32
  18407. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18408. Server svr;
  18409. svr.Post("/post", [&](const Request &req, Response &res) {
  18410. res.set_content(req.body, "text/plain");
  18411. });
  18412. svr.Put("/put", [&](const Request &req, Response &res) {
  18413. res.set_content(req.body, "text/plain");
  18414. });
  18415. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18416. res.set_content(req.body, "text/plain");
  18417. });
  18418. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18419. res.set_content(req.body, "text/plain");
  18420. });
  18421. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18422. auto se = detail::scope_exit([&] {
  18423. svr.stop();
  18424. t.join();
  18425. ASSERT_FALSE(svr.is_running());
  18426. });
  18427. svr.wait_until_ready();
  18428. std::string resp;
  18429. // POST without Content-Length
  18430. ASSERT_TRUE(send_request(5,
  18431. "POST /post HTTP/1.1\r\n"
  18432. "Host: localhost\r\n"
  18433. "Connection: close\r\n"
  18434. "\r\n",
  18435. &resp));
  18436. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18437. // PUT without Content-Length
  18438. resp.clear();
  18439. ASSERT_TRUE(send_request(5,
  18440. "PUT /put HTTP/1.1\r\n"
  18441. "Host: localhost\r\n"
  18442. "Connection: close\r\n"
  18443. "\r\n",
  18444. &resp));
  18445. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18446. // PATCH without Content-Length
  18447. resp.clear();
  18448. ASSERT_TRUE(send_request(5,
  18449. "PATCH /patch HTTP/1.1\r\n"
  18450. "Host: localhost\r\n"
  18451. "Connection: close\r\n"
  18452. "\r\n",
  18453. &resp));
  18454. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18455. // DELETE without Content-Length
  18456. resp.clear();
  18457. ASSERT_TRUE(send_request(5,
  18458. "DELETE /delete HTTP/1.1\r\n"
  18459. "Host: localhost\r\n"
  18460. "Connection: close\r\n"
  18461. "\r\n",
  18462. &resp));
  18463. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18464. }
  18465. #endif
  18466. //==============================================================================
  18467. // open_stream() Tests
  18468. //==============================================================================
  18469. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18470. std::string result;
  18471. char buf[8192];
  18472. ssize_t n;
  18473. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18474. result.append(buf, static_cast<size_t>(n));
  18475. }
  18476. return result;
  18477. }
  18478. // Mock stream for unit tests
  18479. class MockStream : public Stream {
  18480. public:
  18481. std::string data;
  18482. size_t pos = 0;
  18483. ssize_t error_after = -1; // -1 = no error
  18484. explicit MockStream(const std::string &d, ssize_t err = -1)
  18485. : data(d), error_after(err) {}
  18486. bool is_readable() const override { return true; }
  18487. bool wait_readable() const override { return true; }
  18488. bool wait_writable() const override { return true; }
  18489. ssize_t read(char *ptr, size_t size) override {
  18490. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18491. if (pos >= data.size()) return 0;
  18492. size_t limit =
  18493. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18494. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18495. std::memcpy(ptr, data.data() + pos, to_read);
  18496. pos += to_read;
  18497. return static_cast<ssize_t>(to_read);
  18498. }
  18499. ssize_t write(const char *, size_t) override { return -1; }
  18500. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18501. ip = "127.0.0.1";
  18502. port = 0;
  18503. }
  18504. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18505. ip = "127.0.0.1";
  18506. port = 0;
  18507. }
  18508. socket_t socket() const override { return INVALID_SOCKET; }
  18509. time_t duration() const override { return 0; }
  18510. };
  18511. TEST(StreamHandleTest, Basic) {
  18512. ClientImpl::StreamHandle handle;
  18513. EXPECT_FALSE(handle.is_valid());
  18514. handle.response = detail::make_unique<Response>();
  18515. handle.error = Error::Connection;
  18516. EXPECT_FALSE(handle.is_valid());
  18517. handle.error = Error::Success;
  18518. EXPECT_TRUE(handle.is_valid());
  18519. }
  18520. TEST(BodyReaderTest, Basic) {
  18521. MockStream stream("Hello, World!");
  18522. detail::BodyReader reader;
  18523. reader.stream = &stream;
  18524. reader.content_length = 13;
  18525. char buf[32];
  18526. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18527. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18528. EXPECT_TRUE(reader.eof);
  18529. }
  18530. TEST(BodyReaderTest, NoStream) {
  18531. detail::BodyReader reader;
  18532. char buf[32];
  18533. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18534. EXPECT_EQ(Error::Connection, reader.last_error);
  18535. }
  18536. TEST(BodyReaderTest, Error) {
  18537. MockStream stream("Hello, World!", 5);
  18538. detail::BodyReader reader;
  18539. reader.stream = &stream;
  18540. reader.content_length = 13;
  18541. char buf[32];
  18542. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18543. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18544. EXPECT_EQ(Error::Read, reader.last_error);
  18545. }
  18546. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18547. // Mock-based StreamHandle tests relying on private internals are removed.
  18548. class OpenStreamTest : public ::testing::Test {
  18549. protected:
  18550. void SetUp() override {
  18551. svr_.Get("/hello", [](const Request &, Response &res) {
  18552. res.set_content("Hello World!", "text/plain");
  18553. });
  18554. svr_.Get("/large", [](const Request &, Response &res) {
  18555. res.set_content(std::string(10000, 'X'), "text/plain");
  18556. });
  18557. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18558. res.set_content("Hello World!", "image/jpeg");
  18559. res.set_header("Content-Encoding", "UTF-8");
  18560. });
  18561. svr_.Get("/chunked", [](const Request &, Response &res) {
  18562. res.set_chunked_content_provider("text/plain",
  18563. [](size_t offset, DataSink &sink) {
  18564. if (offset < 15) {
  18565. sink.write("chunk", 5);
  18566. return true;
  18567. }
  18568. sink.done();
  18569. return true;
  18570. });
  18571. });
  18572. svr_.Get("/compressible", [](const Request &, Response &res) {
  18573. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18574. DataSink &sink) {
  18575. if (offset < 100 * 1024) {
  18576. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18577. sink.write(chunk.data(), chunk.size());
  18578. return true;
  18579. }
  18580. sink.done();
  18581. return true;
  18582. });
  18583. });
  18584. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18585. [](const Request & /*req*/, Response &res) {
  18586. auto i = new int(0);
  18587. res.set_header("Trailer", "Content-Length, X-Allowed");
  18588. res.set_chunked_content_provider(
  18589. "text/plain",
  18590. [i](size_t /*offset*/, DataSink &sink) {
  18591. switch (*i) {
  18592. case 0: sink.os << "123"; break;
  18593. case 1: sink.os << "456"; break;
  18594. case 2: sink.os << "789"; break;
  18595. case 3: {
  18596. sink.done_with_trailer(
  18597. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18598. } break;
  18599. }
  18600. (*i)++;
  18601. return true;
  18602. },
  18603. [i](bool success) {
  18604. EXPECT_TRUE(success);
  18605. delete i;
  18606. });
  18607. });
  18608. // Echo headers endpoint for header-related tests
  18609. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18610. std::string body;
  18611. for (const auto &h : req.headers) {
  18612. body.append(h.first);
  18613. body.push_back(':');
  18614. body.append(h.second);
  18615. body.push_back('\n');
  18616. }
  18617. res.set_content(body, "text/plain");
  18618. });
  18619. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18620. std::string body;
  18621. for (const auto &h : req.headers) {
  18622. body.append(h.first);
  18623. body.push_back(':');
  18624. body.append(h.second);
  18625. body.push_back('\n');
  18626. }
  18627. res.set_content(body, "text/plain");
  18628. });
  18629. port_ = svr_.bind_to_any_port("127.0.0.1");
  18630. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18631. svr_.wait_until_ready();
  18632. }
  18633. void TearDown() override {
  18634. svr_.stop();
  18635. if (thread_.joinable()) thread_.join();
  18636. }
  18637. Server svr_;
  18638. std::thread thread_;
  18639. int port_ = 0;
  18640. };
  18641. TEST_F(OpenStreamTest, Basic) {
  18642. Client cli("127.0.0.1", port_);
  18643. auto handle = cli.open_stream("GET", "/hello");
  18644. EXPECT_TRUE(handle.is_valid());
  18645. EXPECT_EQ("Hello World!", read_all(handle));
  18646. }
  18647. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18648. Client cli("127.0.0.1", port_);
  18649. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18650. ASSERT_TRUE(handle.is_valid());
  18651. EXPECT_EQ("Hello World!", read_all(handle));
  18652. }
  18653. TEST_F(OpenStreamTest, SmallBuffer) {
  18654. Client cli("127.0.0.1", port_);
  18655. auto handle = cli.open_stream("GET", "/hello");
  18656. std::string result;
  18657. char buf[4];
  18658. ssize_t n;
  18659. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18660. result.append(buf, static_cast<size_t>(n));
  18661. EXPECT_EQ("Hello World!", result);
  18662. }
  18663. TEST_F(OpenStreamTest, DefaultHeaders) {
  18664. Client cli("127.0.0.1", port_);
  18665. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18666. {
  18667. auto handle = cli.open_stream("GET", "/echo-headers");
  18668. ASSERT_TRUE(handle.is_valid());
  18669. auto body = read_all(handle);
  18670. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18671. std::string::npos);
  18672. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18673. std::string::npos);
  18674. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18675. }
  18676. // open_stream POST with body and no explicit content_type should NOT add
  18677. // text/plain Content-Type (behavior differs from non-streaming path), but
  18678. // should include Content-Length
  18679. {
  18680. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18681. ASSERT_TRUE(handle.is_valid());
  18682. auto body = read_all(handle);
  18683. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18684. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18685. }
  18686. // open_stream POST with explicit Content-Type should preserve it
  18687. {
  18688. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18689. {{"Content-Type", "application/custom"}},
  18690. "{}", "application/custom");
  18691. ASSERT_TRUE(handle.is_valid());
  18692. auto body = read_all(handle);
  18693. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18694. }
  18695. // User-specified User-Agent must not be overwritten for stream API
  18696. {
  18697. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18698. {{"User-Agent", "MyAgent/1.2"}});
  18699. ASSERT_TRUE(handle.is_valid());
  18700. auto body = read_all(handle);
  18701. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18702. }
  18703. }
  18704. TEST_F(OpenStreamTest, Large) {
  18705. Client cli("127.0.0.1", port_);
  18706. auto handle = cli.open_stream("GET", "/large");
  18707. EXPECT_EQ(10000u, read_all(handle).size());
  18708. }
  18709. TEST_F(OpenStreamTest, ConnectionError) {
  18710. Client cli("127.0.0.1", 9999);
  18711. auto handle = cli.open_stream("GET", "/hello");
  18712. EXPECT_FALSE(handle.is_valid());
  18713. }
  18714. TEST_F(OpenStreamTest, Chunked) {
  18715. Client cli("127.0.0.1", port_);
  18716. auto handle = cli.open_stream("GET", "/chunked");
  18717. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18718. "Transfer-Encoding") == "chunked");
  18719. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18720. }
  18721. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18722. Client cli("127.0.0.1", port_);
  18723. auto handle =
  18724. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18725. ASSERT_TRUE(handle.is_valid());
  18726. // Consume body to allow trailers to be received/parsed
  18727. auto body = read_all(handle);
  18728. // Explicitly parse trailers (ensure trailers are available for assertion)
  18729. handle.parse_trailers_if_needed();
  18730. EXPECT_EQ(std::string("123456789"), body);
  18731. // The response should include a Trailer header declaring both names
  18732. ASSERT_TRUE(handle.response);
  18733. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18734. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18735. handle.response->get_header_value("Trailer"));
  18736. // Prohibited trailer must not be present
  18737. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18738. // Allowed trailer should be present
  18739. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18740. EXPECT_EQ(std::string("yes"),
  18741. handle.response->get_trailer_value("X-Allowed"));
  18742. // Verify trailers are NOT present as regular headers
  18743. EXPECT_EQ(std::string(""),
  18744. handle.response->get_header_value("Content-Length"));
  18745. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18746. }
  18747. // Accepts one connection on an OS-assigned port, which it hands over through
  18748. // port_promise, reads the request head and sends back response. after_send,
  18749. // if given, runs on the connection before it is closed.
  18750. static std::thread
  18751. serve_single_response(std::promise<int> &port_promise,
  18752. const std::string &response,
  18753. std::function<void(socket_t)> after_send = nullptr) {
  18754. return std::thread([&port_promise, response, after_send] {
  18755. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18756. default_socket_options(srv);
  18757. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18758. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18759. sockaddr_in addr{};
  18760. addr.sin_family = AF_INET;
  18761. addr.sin_port = htons(0); // Let OS assign a free port
  18762. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18763. int opt = 1;
  18764. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18765. #ifdef _WIN32
  18766. reinterpret_cast<const char *>(&opt),
  18767. #else
  18768. &opt,
  18769. #endif
  18770. sizeof(opt));
  18771. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18772. ::listen(srv, 1) != 0) {
  18773. port_promise.set_value(-1);
  18774. detail::close_socket(srv);
  18775. return;
  18776. }
  18777. socklen_t addr_len = sizeof(addr);
  18778. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18779. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18780. sockaddr_in cli_addr{};
  18781. socklen_t cli_len = sizeof(cli_addr);
  18782. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18783. if (cli != INVALID_SOCKET) {
  18784. // Read the complete HTTP request (until the blank line that terminates
  18785. // headers) before sending the response. If the server closes the socket
  18786. // while the client's request data is still unread in the kernel receive
  18787. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18788. // connection on both sides: it discards the client's receive buffer
  18789. // (which already holds our response) and causes any in-progress write on
  18790. // the client to fail with ECONNRESET. Reading all request data first
  18791. // ensures close() emits a graceful FIN.
  18792. {
  18793. char rbuf[256];
  18794. std::string req;
  18795. while (req.find("\r\n\r\n") == std::string::npos) {
  18796. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18797. if (n <= 0) { break; }
  18798. req.append(rbuf, static_cast<size_t>(n));
  18799. }
  18800. }
  18801. ::send(cli,
  18802. #ifdef _WIN32
  18803. static_cast<const char *>(response.c_str()),
  18804. static_cast<int>(response.size()),
  18805. #else
  18806. response.c_str(), response.size(),
  18807. #endif
  18808. 0);
  18809. if (after_send) { after_send(cli); }
  18810. detail::close_socket(cli);
  18811. }
  18812. detail::close_socket(srv);
  18813. });
  18814. }
  18815. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18816. #ifndef _WIN32
  18817. signal(SIGPIPE, SIG_IGN);
  18818. #endif
  18819. std::promise<int> port_promise;
  18820. auto port_future = port_promise.get_future();
  18821. auto server_thread =
  18822. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18823. "Content-Type: text/plain\r\n"
  18824. "Content-Length: not-a-number\r\n"
  18825. "Connection: close\r\n"
  18826. "\r\n"
  18827. "hello");
  18828. auto port = port_future.get();
  18829. ASSERT_GT(port, 0);
  18830. Client cli("127.0.0.1", port);
  18831. auto handle = cli.open_stream("GET", "/");
  18832. EXPECT_FALSE(handle.is_valid());
  18833. server_thread.join();
  18834. }
  18835. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18836. #ifndef _WIN32
  18837. signal(SIGPIPE, SIG_IGN);
  18838. #endif
  18839. std::promise<int> port_promise;
  18840. auto port_future = port_promise.get_future();
  18841. auto server_thread = serve_single_response(
  18842. port_promise, "HTTP/1.1 200 OK\r\n"
  18843. "Content-Type: text/plain\r\n"
  18844. "Content-Length: 99999999999999999999999999\r\n"
  18845. "Connection: close\r\n"
  18846. "\r\n"
  18847. "hello");
  18848. auto port = port_future.get();
  18849. ASSERT_GT(port, 0);
  18850. // Historically std::stoull would throw std::out_of_range here and crash
  18851. // the process, then parsing silently clamped to a bogus framing length and
  18852. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18853. // so the stream fails to open, matching the not-a-number case above. The
  18854. // process still must NOT terminate.
  18855. Client cli("127.0.0.1", port);
  18856. auto handle = cli.open_stream("GET", "/");
  18857. EXPECT_FALSE(handle.is_valid());
  18858. server_thread.join();
  18859. }
  18860. // Serves `response` to the single request `fn` makes with a fresh client.
  18861. template <typename Fn>
  18862. static void with_single_response(const std::string &response, Fn fn) {
  18863. #ifndef _WIN32
  18864. signal(SIGPIPE, SIG_IGN);
  18865. #endif
  18866. std::promise<int> port_promise;
  18867. auto port_future = port_promise.get_future();
  18868. auto server_thread = serve_single_response(port_promise, response);
  18869. auto se = detail::scope_exit([&] { server_thread.join(); });
  18870. auto port = port_future.get();
  18871. ASSERT_GT(port, 0);
  18872. Client cli("127.0.0.1", port);
  18873. fn(cli);
  18874. }
  18875. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  18876. const char *responses[] = {
  18877. "HTTP/1.1 103 Early Hints\r\n"
  18878. "Link: </style.css>; rel=preload\r\n"
  18879. "\r\n"
  18880. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18881. "HTTP/1.1 100 Continue\r\n"
  18882. "X-Note: interim\r\n"
  18883. "\r\n"
  18884. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18885. };
  18886. for (auto response : responses) {
  18887. with_single_response(response, [](Client &cli) {
  18888. auto res = cli.Get("/");
  18889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18890. EXPECT_EQ(StatusCode::OK_200, res->status);
  18891. EXPECT_EQ("ok", res->body);
  18892. });
  18893. }
  18894. }
  18895. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  18896. #ifndef _WIN32
  18897. signal(SIGPIPE, SIG_IGN);
  18898. #endif
  18899. // The server answers the head without asking for the body. Bytes it then
  18900. // reads on the connection would be taken for the body the request declared.
  18901. auto closed_by_client = false;
  18902. std::promise<int> port_promise;
  18903. auto server_thread = serve_single_response(
  18904. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  18905. [&](socket_t sock) {
  18906. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  18907. char buf[256];
  18908. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  18909. });
  18910. Client cli("127.0.0.1", port_promise.get_future().get());
  18911. cli.set_keep_alive(true);
  18912. cli.set_read_timeout(1, 0);
  18913. // Long enough for the client to send Expect: 100-continue.
  18914. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18916. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  18917. cli.Get("/second");
  18918. server_thread.join();
  18919. EXPECT_TRUE(closed_by_client);
  18920. }
  18921. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  18922. // Long enough for the client to send Expect: 100-continue
  18923. with_single_response(
  18924. "HTTP/1.1 103 Early Hints\r\n"
  18925. "Link: </style.css>; rel=preload\r\n"
  18926. "\r\n"
  18927. "HTTP/1.1 401 Unauthorized\r\n"
  18928. "Content-Length: 0\r\n\r\n",
  18929. [](Client &cli) {
  18930. cli.set_read_timeout(2, 0);
  18931. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18933. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  18934. });
  18935. }
  18936. #ifdef CPPHTTPLIB_SSL_ENABLED
  18937. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  18938. #ifndef _WIN32
  18939. signal(SIGPIPE, SIG_IGN);
  18940. #endif
  18941. auto reused = false;
  18942. std::promise<int> port_promise;
  18943. auto server_thread = serve_single_response(
  18944. port_promise,
  18945. "HTTP/1.1 401 Unauthorized\r\n"
  18946. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  18947. "Content-Length: 0\r\n\r\n",
  18948. [&](socket_t sock) {
  18949. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  18950. char buf[256];
  18951. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  18952. });
  18953. Client cli("127.0.0.1", port_promise.get_future().get());
  18954. cli.set_keep_alive(true);
  18955. cli.set_digest_auth("user", "pass");
  18956. cli.set_read_timeout(1, 0);
  18957. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18958. server_thread.join();
  18959. EXPECT_FALSE(reused);
  18960. }
  18961. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  18962. // Any other answer to CONNECT would read as the origin's response.
  18963. struct {
  18964. const char *response;
  18965. bool passed_on;
  18966. } cases[] = {
  18967. {"HTTP/1.1 201 Created\r\n"
  18968. "Set-Cookie: session=from-proxy\r\n"
  18969. "Content-Length: 0\r\n\r\n",
  18970. false},
  18971. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  18972. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  18973. "Content-Length: 0\r\n\r\n",
  18974. true},
  18975. };
  18976. for (const auto &c : cases) {
  18977. std::promise<int> port_promise;
  18978. auto server_thread = serve_single_response(port_promise, c.response);
  18979. SSLClient cli("example.com", 443);
  18980. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  18981. auto res = cli.Get("/");
  18982. server_thread.join();
  18983. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  18984. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  18985. if (res) {
  18986. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18987. }
  18988. }
  18989. }
  18990. #endif
  18991. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18992. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18993. // the chunked coding and drop Content-Length, so a front-end that trusts
  18994. // Content-Length would disagree about where the body ends (response
  18995. // smuggling). The client must reject such a response.
  18996. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18997. for (const char *te : {"chunked", "gzip, chunked"}) {
  18998. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18999. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19000. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19001. "5\r\nhello\r\n0\r\n\r\n";
  19002. with_single_response(response, [&](Client &cli) {
  19003. auto res = cli.Get("/");
  19004. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19005. EXPECT_EQ(Error::Read, res.error()) << te;
  19006. });
  19007. with_single_response(response, [&](Client &cli) {
  19008. auto handle = cli.open_stream("GET", "/");
  19009. EXPECT_FALSE(handle.is_valid()) << te;
  19010. EXPECT_EQ(Error::Read, handle.error) << te;
  19011. });
  19012. }
  19013. }
  19014. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19015. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19016. // closing the connection (unlike a request, which must be rejected).
  19017. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19018. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19019. "Transfer-Encoding: chunked\r\n"
  19020. "Connection: close\r\n"
  19021. "\r\n"
  19022. "5\r\nhello\r\n0\r\n\r\n",
  19023. "HTTP/1.1 200 OK\r\n"
  19024. "Transfer-Encoding: gzip\r\n"
  19025. "Connection: close\r\n"
  19026. "\r\n"
  19027. "hello"}) {
  19028. with_single_response(response, [&](Client &cli) {
  19029. auto res = cli.Get("/");
  19030. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19031. EXPECT_EQ("hello", res->body);
  19032. });
  19033. with_single_response(response, [&](Client &cli) {
  19034. auto handle = cli.open_stream("GET", "/");
  19035. ASSERT_TRUE(handle.is_valid()) << response;
  19036. EXPECT_EQ("hello", read_all(handle));
  19037. });
  19038. }
  19039. }
  19040. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19041. // framing headers describe nothing to read and must not be rejected.
  19042. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19043. const std::string framing = "Content-Length: 5\r\n"
  19044. "Transfer-Encoding: chunked\r\n"
  19045. "Connection: close\r\n"
  19046. "\r\n";
  19047. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19048. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19049. });
  19050. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19051. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19052. });
  19053. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19054. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19055. with_single_response(response, [&](Client &cli) {
  19056. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19057. });
  19058. with_single_response(response, [&](Client &cli) {
  19059. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19060. });
  19061. }
  19062. }
  19063. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19064. // response, is faulty framing, so the connection is not reused after it.
  19065. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19066. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19067. "Content-Length: 0\r\n"
  19068. "Transfer-Encoding: chunked\r\n"
  19069. "\r\n"
  19070. "5\r\nhello\r\n0\r\n\r\n",
  19071. "HTTP/1.0 200 Connection established\r\n"
  19072. "Connection: keep-alive\r\n"
  19073. "Transfer-Encoding: chunked\r\n"
  19074. "\r\n"
  19075. "5\r\nhello\r\n0\r\n\r\n"}) {
  19076. with_single_response(response, [&](Client &cli) {
  19077. cli.set_keep_alive(true);
  19078. auto res = cli.Get("/");
  19079. ASSERT_TRUE(res) << response;
  19080. EXPECT_EQ("hello", res->body);
  19081. EXPECT_FALSE(cli.is_socket_open()) << response;
  19082. });
  19083. }
  19084. }
  19085. // A payload max length of 0 means no limit, however the body is framed.
  19086. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19087. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19088. "Transfer-Encoding: chunked\r\n"
  19089. "\r\n"
  19090. "5\r\nhello\r\n0\r\n\r\n",
  19091. "HTTP/1.1 200 OK\r\n"
  19092. "Connection: close\r\n"
  19093. "\r\n"
  19094. "hello"}) {
  19095. with_single_response(response, [&](Client &cli) {
  19096. cli.set_payload_max_length(0);
  19097. auto res = cli.Get("/");
  19098. ASSERT_TRUE(res) << response;
  19099. EXPECT_EQ("hello", res->body) << response;
  19100. });
  19101. }
  19102. }
  19103. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19104. Server svr;
  19105. svr.set_payload_max_length(0);
  19106. svr.Post("/echo", [](const Request &req, Response &res) {
  19107. res.set_content(req.body, "text/plain");
  19108. });
  19109. auto port = svr.bind_to_any_port(HOST);
  19110. thread t = thread([&] { svr.listen_after_bind(); });
  19111. auto se = detail::scope_exit([&] {
  19112. svr.stop();
  19113. t.join();
  19114. ASSERT_FALSE(svr.is_running());
  19115. });
  19116. svr.wait_until_ready();
  19117. Client cli(HOST, port);
  19118. auto res = cli.Post(
  19119. "/echo",
  19120. [](size_t /*offset*/, DataSink &sink) {
  19121. sink.write("hello", 5);
  19122. sink.done();
  19123. return true;
  19124. },
  19125. "text/plain");
  19126. ASSERT_TRUE(res);
  19127. EXPECT_EQ(StatusCode::OK_200, res->status);
  19128. EXPECT_EQ("hello", res->body);
  19129. }
  19130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19131. TEST_F(OpenStreamTest, Gzip) {
  19132. Client cli("127.0.0.1", port_);
  19133. auto handle = cli.open_stream("GET", "/compressible", {},
  19134. {{"Accept-Encoding", "gzip"}});
  19135. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19136. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19137. }
  19138. #endif
  19139. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19140. TEST_F(OpenStreamTest, Brotli) {
  19141. Client cli("127.0.0.1", port_);
  19142. auto handle =
  19143. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19144. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19145. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19146. }
  19147. #endif
  19148. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19149. TEST_F(OpenStreamTest, Zstd) {
  19150. Client cli("127.0.0.1", port_);
  19151. auto handle = cli.open_stream("GET", "/compressible", {},
  19152. {{"Accept-Encoding", "zstd"}});
  19153. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19154. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19155. }
  19156. #endif
  19157. #ifdef CPPHTTPLIB_SSL_ENABLED
  19158. class SSLOpenStreamTest : public ::testing::Test {
  19159. protected:
  19160. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19161. void SetUp() override {
  19162. svr_.Get("/hello", [](const Request &, Response &res) {
  19163. res.set_content("Hello SSL World!", "text/plain");
  19164. });
  19165. svr_.Get("/chunked", [](const Request &, Response &res) {
  19166. res.set_chunked_content_provider("text/plain",
  19167. [](size_t offset, DataSink &sink) {
  19168. if (offset < 15) {
  19169. sink.write("chunk", 5);
  19170. return true;
  19171. }
  19172. sink.done();
  19173. return true;
  19174. });
  19175. });
  19176. svr_.Post("/echo", [](const Request &req, Response &res) {
  19177. res.set_content(req.body, req.get_header_value("Content-Type"));
  19178. });
  19179. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19180. std::string body = req.body;
  19181. res.set_chunked_content_provider(
  19182. "text/plain", [body](size_t offset, DataSink &sink) {
  19183. if (offset < body.size()) {
  19184. sink.write(body.data() + offset, body.size() - offset);
  19185. }
  19186. sink.done();
  19187. return true;
  19188. });
  19189. });
  19190. port_ = svr_.bind_to_any_port("127.0.0.1");
  19191. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19192. svr_.wait_until_ready();
  19193. }
  19194. void TearDown() override {
  19195. svr_.stop();
  19196. if (thread_.joinable()) thread_.join();
  19197. }
  19198. SSLServer svr_;
  19199. std::thread thread_;
  19200. int port_ = 0;
  19201. };
  19202. TEST_F(SSLOpenStreamTest, Basic) {
  19203. SSLClient cli("127.0.0.1", port_);
  19204. cli.enable_server_certificate_verification(false);
  19205. auto handle = cli.open_stream("GET", "/hello");
  19206. ASSERT_TRUE(handle.is_valid());
  19207. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19208. }
  19209. TEST_F(SSLOpenStreamTest, Chunked) {
  19210. SSLClient cli("127.0.0.1", port_);
  19211. cli.enable_server_certificate_verification(false);
  19212. auto handle = cli.open_stream("GET", "/chunked");
  19213. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19214. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19215. "Transfer-Encoding") == "chunked");
  19216. auto body = read_all(handle);
  19217. EXPECT_EQ("chunkchunkchunk", body);
  19218. }
  19219. TEST_F(SSLOpenStreamTest, Post) {
  19220. SSLClient cli("127.0.0.1", port_);
  19221. cli.enable_server_certificate_verification(false);
  19222. auto handle =
  19223. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19224. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19225. EXPECT_EQ(200, handle.response->status);
  19226. auto body = read_all(handle);
  19227. EXPECT_EQ("Hello SSL POST", body);
  19228. }
  19229. TEST_F(SSLOpenStreamTest, PostChunked) {
  19230. SSLClient cli("127.0.0.1", port_);
  19231. cli.enable_server_certificate_verification(false);
  19232. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19233. "Chunked SSL Data", "text/plain");
  19234. ASSERT_TRUE(handle.is_valid());
  19235. EXPECT_EQ(200, handle.response->status);
  19236. auto body = read_all(handle);
  19237. EXPECT_EQ("Chunked SSL Data", body);
  19238. }
  19239. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19240. // Content-Length is terminated by the server closing the connection. When the
  19241. // SSL peer sends a close_notify after the body, the client must treat it as a
  19242. // clean EOF and return a successful response rather than an error.
  19243. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19244. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19245. ASSERT_TRUE(svr.is_valid());
  19246. svr.set_keep_alive_max_count(1);
  19247. const std::string expected_body = "Hello from connection-close response!";
  19248. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19249. res.set_content_provider("text/plain",
  19250. [&](size_t offset, DataSink &sink) -> bool {
  19251. if (offset < expected_body.size()) {
  19252. sink.write(expected_body.data() + offset,
  19253. expected_body.size() - offset);
  19254. }
  19255. sink.done();
  19256. return true;
  19257. });
  19258. });
  19259. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19260. auto se = detail::scope_exit([&] {
  19261. svr.stop();
  19262. listen_thread.join();
  19263. ASSERT_FALSE(svr.is_running());
  19264. });
  19265. svr.wait_until_ready();
  19266. SSLClient cli(HOST, PORT);
  19267. cli.enable_server_certificate_verification(false);
  19268. auto res = cli.Get("/no-content-length");
  19269. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19270. EXPECT_EQ(StatusCode::OK_200, res->status);
  19271. EXPECT_EQ(expected_body, res->body);
  19272. }
  19273. #endif // CPPHTTPLIB_SSL_ENABLED
  19274. //==============================================================================
  19275. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19276. // results for various scenarios.
  19277. //==============================================================================
  19278. TEST(ParityTest, GetVsOpenStream) {
  19279. Server svr;
  19280. const std::string path = "/parity";
  19281. const std::string content = "Parity test content: hello world";
  19282. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19283. res.set_content(content, "text/plain");
  19284. });
  19285. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19286. auto se = detail::scope_exit([&] {
  19287. svr.stop();
  19288. t.join();
  19289. ASSERT_FALSE(svr.is_running());
  19290. });
  19291. svr.wait_until_ready();
  19292. Client cli(HOST, PORT);
  19293. // Non-stream path
  19294. auto r1 = cli.Get(path);
  19295. ASSERT_TRUE(r1);
  19296. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19297. // Stream path
  19298. auto h = cli.open_stream("GET", path);
  19299. ASSERT_TRUE(h.is_valid());
  19300. EXPECT_EQ(r1->body, read_all(h));
  19301. }
  19302. // Helper to compress data with provided compressor type T
  19303. template <typename Compressor>
  19304. static std::string compress_payload_for_parity(const std::string &in) {
  19305. std::string out;
  19306. Compressor compressor;
  19307. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19308. [&](const char *data, size_t n) {
  19309. out.append(data, n);
  19310. return true;
  19311. });
  19312. EXPECT_TRUE(ok);
  19313. return out;
  19314. }
  19315. // Helper function for compression parity tests
  19316. template <typename Compressor>
  19317. static void test_compression_parity(const std::string &original,
  19318. const std::string &path,
  19319. const std::string &encoding) {
  19320. const std::string compressed =
  19321. compress_payload_for_parity<Compressor>(original);
  19322. Server svr;
  19323. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19324. res.set_content(compressed, "application/octet-stream");
  19325. res.set_header("Content-Encoding", encoding);
  19326. });
  19327. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19328. auto se = detail::scope_exit([&] {
  19329. svr.stop();
  19330. t.join();
  19331. ASSERT_FALSE(svr.is_running());
  19332. });
  19333. svr.wait_until_ready();
  19334. Client cli(HOST, PORT);
  19335. // Non-streaming
  19336. {
  19337. auto res = cli.Get(path);
  19338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19339. EXPECT_EQ(StatusCode::OK_200, res->status);
  19340. EXPECT_EQ(original, res->body);
  19341. }
  19342. // Streaming
  19343. {
  19344. auto h = cli.open_stream("GET", path);
  19345. ASSERT_TRUE(h.is_valid());
  19346. EXPECT_EQ(original, read_all(h));
  19347. }
  19348. }
  19349. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19350. TEST(ParityTest, Gzip) {
  19351. test_compression_parity<detail::gzip_compressor>(
  19352. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19353. }
  19354. #endif
  19355. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19356. TEST(ParityTest, Brotli) {
  19357. test_compression_parity<detail::brotli_compressor>(
  19358. "Hello, brotli parity test payload", "/parity-br", "br");
  19359. }
  19360. #endif
  19361. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19362. TEST(ParityTest, Zstd) {
  19363. test_compression_parity<detail::zstd_compressor>(
  19364. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19365. }
  19366. #endif
  19367. //==============================================================================
  19368. // New Stream API Tests
  19369. //==============================================================================
  19370. inline std::string read_body(httplib::stream::Result &result) {
  19371. std::string body;
  19372. while (result.next()) {
  19373. body.append(result.data(), result.size());
  19374. }
  19375. return body;
  19376. }
  19377. TEST(ClientConnectionTest, Basic) {
  19378. httplib::ClientConnection conn;
  19379. EXPECT_FALSE(conn.is_open());
  19380. conn.sock = 1;
  19381. EXPECT_TRUE(conn.is_open());
  19382. httplib::ClientConnection conn2(std::move(conn));
  19383. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19384. conn2.sock = INVALID_SOCKET;
  19385. }
  19386. // Unified test server for all stream::* tests
  19387. class StreamApiTest : public ::testing::Test {
  19388. protected:
  19389. void SetUp() override {
  19390. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19391. res.set_content("Hello World!", "text/plain");
  19392. });
  19393. svr_.Get("/echo-params",
  19394. [](const httplib::Request &req, httplib::Response &res) {
  19395. std::string r;
  19396. for (const auto &p : req.params) {
  19397. if (!r.empty()) r += "&";
  19398. r += p.first + "=" + p.second;
  19399. }
  19400. res.set_content(r, "text/plain");
  19401. });
  19402. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19403. res.set_content(req.body, req.get_header_value("Content-Type"));
  19404. });
  19405. svr_.Post("/echo-headers",
  19406. [](const httplib::Request &req, httplib::Response &res) {
  19407. std::string r;
  19408. for (const auto &h : req.headers)
  19409. r += h.first + ": " + h.second + "\n";
  19410. res.set_content(r, "text/plain");
  19411. });
  19412. svr_.Post("/echo-params",
  19413. [](const httplib::Request &req, httplib::Response &res) {
  19414. std::string r = "params:";
  19415. for (const auto &p : req.params)
  19416. r += p.first + "=" + p.second + ";";
  19417. res.set_content(r + " body:" + req.body, "text/plain");
  19418. });
  19419. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19420. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19421. });
  19422. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19423. res.set_content("PUT:" + req.body, "text/plain");
  19424. });
  19425. svr_.Patch("/echo",
  19426. [](const httplib::Request &req, httplib::Response &res) {
  19427. res.set_content("PATCH:" + req.body, "text/plain");
  19428. });
  19429. svr_.Delete(
  19430. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19431. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19432. "text/plain");
  19433. });
  19434. svr_.Get("/head-test",
  19435. [](const httplib::Request &, httplib::Response &res) {
  19436. res.set_content("body for HEAD", "text/plain");
  19437. });
  19438. svr_.Options("/options",
  19439. [](const httplib::Request &, httplib::Response &res) {
  19440. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19441. });
  19442. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19443. svr_.wait_until_ready();
  19444. }
  19445. void TearDown() override {
  19446. svr_.stop();
  19447. if (thread_.joinable()) thread_.join();
  19448. }
  19449. httplib::Server svr_;
  19450. std::thread thread_;
  19451. };
  19452. // stream::Get tests
  19453. TEST_F(StreamApiTest, GetBasic) {
  19454. httplib::Client cli(HOST, PORT);
  19455. auto result = httplib::stream::Get(cli, "/hello");
  19456. ASSERT_TRUE(result.is_valid());
  19457. EXPECT_EQ(200, result.status());
  19458. EXPECT_EQ("Hello World!", read_body(result));
  19459. }
  19460. TEST_F(StreamApiTest, GetWithParams) {
  19461. httplib::Client cli(HOST, PORT);
  19462. httplib::Params params{{"foo", "bar"}};
  19463. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19464. ASSERT_TRUE(result.is_valid());
  19465. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19466. }
  19467. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19468. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19469. httplib::Client cli(HOST, PORT);
  19470. cli.set_payload_max_length(0);
  19471. auto result = httplib::stream::Get(cli, "/hello");
  19472. ASSERT_TRUE(result.is_valid());
  19473. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19474. EXPECT_EQ("Hello World!", read_body(result));
  19475. }
  19476. #endif
  19477. TEST_F(StreamApiTest, GetConnectionError) {
  19478. httplib::Client cli(HOST, 9999);
  19479. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19480. }
  19481. TEST_F(StreamApiTest, Get404) {
  19482. httplib::Client cli(HOST, PORT);
  19483. auto result = httplib::stream::Get(cli, "/nonexistent");
  19484. EXPECT_TRUE(result.is_valid());
  19485. EXPECT_EQ(404, result.status());
  19486. }
  19487. // stream::Post tests
  19488. TEST_F(StreamApiTest, PostBasic) {
  19489. httplib::Client cli(HOST, PORT);
  19490. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19491. "application/json");
  19492. ASSERT_TRUE(result.is_valid());
  19493. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19494. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19495. }
  19496. TEST_F(StreamApiTest, PostWithHeaders) {
  19497. httplib::Client cli(HOST, PORT);
  19498. httplib::Headers headers{{"X-Custom", "value"}};
  19499. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19500. "text/plain");
  19501. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19502. }
  19503. TEST_F(StreamApiTest, PostWithParams) {
  19504. httplib::Client cli(HOST, PORT);
  19505. httplib::Params params{{"k", "v"}};
  19506. auto result =
  19507. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19508. auto body = read_body(result);
  19509. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19510. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19511. }
  19512. TEST_F(StreamApiTest, PostLarge) {
  19513. httplib::Client cli(HOST, PORT);
  19514. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19515. size_t total = 0;
  19516. while (result.next()) {
  19517. total += result.size();
  19518. }
  19519. EXPECT_EQ(100u * 1024u, total);
  19520. }
  19521. // stream::Put/Patch tests
  19522. TEST_F(StreamApiTest, PutAndPatch) {
  19523. httplib::Client cli(HOST, PORT);
  19524. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19525. EXPECT_EQ("PUT:test", read_body(put));
  19526. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19527. EXPECT_EQ("PATCH:test", read_body(patch));
  19528. }
  19529. // stream::Delete tests
  19530. TEST_F(StreamApiTest, Delete) {
  19531. httplib::Client cli(HOST, PORT);
  19532. auto del1 = httplib::stream::Delete(cli, "/resource");
  19533. EXPECT_EQ("Deleted", read_body(del1));
  19534. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19535. EXPECT_EQ("Deleted:data", read_body(del2));
  19536. }
  19537. // stream::Head/Options tests
  19538. TEST_F(StreamApiTest, HeadAndOptions) {
  19539. httplib::Client cli(HOST, PORT);
  19540. auto head = httplib::stream::Head(cli, "/head-test");
  19541. EXPECT_TRUE(head.is_valid());
  19542. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19543. auto opts = httplib::stream::Options(cli, "/options");
  19544. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19545. }
  19546. // SSL stream::* tests
  19547. #ifdef CPPHTTPLIB_SSL_ENABLED
  19548. class SSLStreamApiTest : public ::testing::Test {
  19549. protected:
  19550. void SetUp() override {
  19551. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19552. res.set_content("Hello SSL!", "text/plain");
  19553. });
  19554. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19555. res.set_content(req.body, "text/plain");
  19556. });
  19557. port_ = svr_.bind_to_any_port("127.0.0.1");
  19558. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19559. svr_.wait_until_ready();
  19560. }
  19561. void TearDown() override {
  19562. svr_.stop();
  19563. if (thread_.joinable()) thread_.join();
  19564. }
  19565. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19566. std::thread thread_;
  19567. int port_ = 0;
  19568. };
  19569. TEST_F(SSLStreamApiTest, GetAndPost) {
  19570. httplib::SSLClient cli("127.0.0.1", port_);
  19571. cli.enable_server_certificate_verification(false);
  19572. auto get = httplib::stream::Get(cli, "/hello");
  19573. EXPECT_EQ("Hello SSL!", read_body(get));
  19574. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19575. EXPECT_EQ("test", read_body(post));
  19576. }
  19577. #endif
  19578. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19579. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19580. // BodyReader
  19581. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19582. // Test that read timeout during streaming is detected
  19583. // Use a large content-length response where server delays mid-stream
  19584. Server svr;
  19585. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19586. // Send a large response with delay in the middle
  19587. res.set_content_provider(
  19588. 1000, // content_length
  19589. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19590. if (offset < 100) {
  19591. // Send first 100 bytes immediately
  19592. std::string data(100, 'A');
  19593. sink.write(data.c_str(), data.size());
  19594. return true;
  19595. }
  19596. // Then delay longer than client timeout
  19597. std::this_thread::sleep_for(std::chrono::seconds(3));
  19598. std::string data(900, 'B');
  19599. sink.write(data.c_str(), data.size());
  19600. return true;
  19601. });
  19602. });
  19603. auto port = 8091;
  19604. std::thread t([&]() { svr.listen("localhost", port); });
  19605. svr.wait_until_ready();
  19606. Client cli("localhost", port);
  19607. cli.set_read_timeout(1, 0); // 1 second timeout
  19608. auto handle = cli.open_stream("GET", "/slow-stream");
  19609. ASSERT_TRUE(handle.is_valid());
  19610. char buf[256];
  19611. ssize_t total = 0;
  19612. ssize_t n;
  19613. bool got_error = false;
  19614. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19615. total += n;
  19616. }
  19617. if (n < 0) {
  19618. got_error = true;
  19619. // Should be timeout or read error
  19620. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19621. handle.get_read_error() == Error::Read)
  19622. << "Actual error: " << to_string(handle.get_read_error());
  19623. }
  19624. // Either we got an error, or we got less data than expected
  19625. EXPECT_TRUE(got_error || total < 1000)
  19626. << "Expected timeout but got all " << total << " bytes";
  19627. svr.stop();
  19628. t.join();
  19629. }
  19630. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19631. // Test connection closed detection via BodyReader
  19632. Server svr;
  19633. std::atomic<bool> close_now{false};
  19634. svr.Get("/will-close", [&](const Request &, Response &res) {
  19635. res.set_content_provider(
  19636. 10000, // Large content_length that we won't fully send
  19637. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19638. if (offset < 100) {
  19639. std::string data(100, 'X');
  19640. sink.write(data.c_str(), data.size());
  19641. return true;
  19642. }
  19643. // Wait for signal then abort
  19644. while (!close_now) {
  19645. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19646. }
  19647. return false; // Abort - server will close connection
  19648. });
  19649. });
  19650. auto port = 8092;
  19651. std::thread t([&]() { svr.listen("localhost", port); });
  19652. svr.wait_until_ready();
  19653. Client cli("localhost", port);
  19654. auto handle = cli.open_stream("GET", "/will-close");
  19655. ASSERT_TRUE(handle.is_valid());
  19656. char buf[256];
  19657. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19658. EXPECT_GT(n, 0) << "First read should succeed";
  19659. // Signal server to close
  19660. close_now = true;
  19661. // Keep reading until error or EOF
  19662. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19663. // Keep reading
  19664. }
  19665. // Should get an error since content_length wasn't satisfied
  19666. if (n < 0) {
  19667. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19668. handle.get_read_error() == Error::Read)
  19669. << "Actual error: " << to_string(handle.get_read_error());
  19670. }
  19671. svr.stop();
  19672. t.join();
  19673. }
  19674. #ifdef CPPHTTPLIB_SSL_ENABLED
  19675. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19676. // Test that read timeout during SSL streaming is detected
  19677. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19678. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19679. res.set_content_provider(
  19680. 1000, "text/plain",
  19681. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19682. if (offset < 100) {
  19683. std::string data(100, 'A');
  19684. sink.write(data.c_str(), data.size());
  19685. return true;
  19686. }
  19687. std::this_thread::sleep_for(std::chrono::seconds(3));
  19688. std::string data(900, 'B');
  19689. sink.write(data.c_str(), data.size());
  19690. return true;
  19691. });
  19692. });
  19693. auto port = 8093;
  19694. std::thread t([&]() { svr.listen("localhost", port); });
  19695. svr.wait_until_ready();
  19696. SSLClient cli("localhost", port);
  19697. cli.enable_server_certificate_verification(false);
  19698. cli.set_read_timeout(1, 0); // 1 second timeout
  19699. auto handle = cli.open_stream("GET", "/slow-stream");
  19700. ASSERT_TRUE(handle.is_valid());
  19701. char buf[256];
  19702. ssize_t total = 0;
  19703. ssize_t n;
  19704. bool got_error = false;
  19705. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19706. total += n;
  19707. }
  19708. if (n < 0) {
  19709. got_error = true;
  19710. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19711. handle.get_read_error() == Error::Read)
  19712. << "Actual error: " << to_string(handle.get_read_error());
  19713. }
  19714. EXPECT_TRUE(got_error || total < 1000)
  19715. << "Expected timeout but got all " << total << " bytes";
  19716. svr.stop();
  19717. t.join();
  19718. }
  19719. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19720. // Test SSL connection closed detection
  19721. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19722. std::atomic<bool> close_now{false};
  19723. svr.Get("/will-close", [&](const Request &, Response &res) {
  19724. res.set_content_provider(
  19725. 10000, "text/plain",
  19726. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19727. if (offset < 100) {
  19728. std::string data(100, 'X');
  19729. sink.write(data.c_str(), data.size());
  19730. return true;
  19731. }
  19732. while (!close_now) {
  19733. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19734. }
  19735. return false;
  19736. });
  19737. });
  19738. auto port = 8094;
  19739. std::thread t([&]() { svr.listen("localhost", port); });
  19740. svr.wait_until_ready();
  19741. SSLClient cli("localhost", port);
  19742. cli.enable_server_certificate_verification(false);
  19743. auto handle = cli.open_stream("GET", "/will-close");
  19744. ASSERT_TRUE(handle.is_valid());
  19745. char buf[256];
  19746. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19747. EXPECT_GT(n, 0);
  19748. // Signal server to close
  19749. close_now = true;
  19750. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19751. // Keep reading
  19752. }
  19753. if (n < 0) {
  19754. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19755. handle.get_read_error() == Error::Read)
  19756. << "Actual error: " << to_string(handle.get_read_error());
  19757. }
  19758. svr.stop();
  19759. t.join();
  19760. }
  19761. #endif
  19762. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19763. using namespace httplib;
  19764. // Create a test file
  19765. const char *fname = "etag_testfile.txt";
  19766. const char *content = "etag-content";
  19767. {
  19768. std::ofstream ofs(fname);
  19769. ofs << content;
  19770. ASSERT_TRUE(ofs.good());
  19771. }
  19772. Server svr;
  19773. svr.set_mount_point("/static", ".");
  19774. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19775. svr.wait_until_ready();
  19776. Client cli(HOST, PORT);
  19777. // First request: should get 200 with ETag header
  19778. auto res1 = cli.Get("/static/etag_testfile.txt");
  19779. ASSERT_TRUE(res1);
  19780. ASSERT_EQ(200, res1->status);
  19781. ASSERT_TRUE(res1->has_header("ETag"));
  19782. std::string etag = res1->get_header_value("ETag");
  19783. EXPECT_FALSE(etag.empty());
  19784. // Verify ETag format: W/"hex-hex"
  19785. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19786. EXPECT_EQ('W', etag[0]);
  19787. EXPECT_EQ('/', etag[1]);
  19788. EXPECT_EQ('"', etag[2]);
  19789. EXPECT_EQ('"', etag.back());
  19790. // Exact match: expect 304 Not Modified
  19791. Headers h2 = {{"If-None-Match", etag}};
  19792. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19793. ASSERT_TRUE(res2);
  19794. EXPECT_EQ(304, res2->status);
  19795. // Wildcard match: expect 304 Not Modified
  19796. Headers h3 = {{"If-None-Match", "*"}};
  19797. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19798. ASSERT_TRUE(res3);
  19799. EXPECT_EQ(304, res3->status);
  19800. // Non-matching ETag: expect 200
  19801. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19802. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19803. ASSERT_TRUE(res4);
  19804. EXPECT_EQ(200, res4->status);
  19805. // Multiple ETags with one matching: expect 304
  19806. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19807. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19808. ASSERT_TRUE(res5);
  19809. EXPECT_EQ(304, res5->status);
  19810. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19811. // that equivalent to the single comma-separated list above, so the match on
  19812. // the second line must still be found.
  19813. Headers h6;
  19814. h6.emplace("If-None-Match", "W/\"other\"");
  19815. h6.emplace("If-None-Match", etag);
  19816. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19817. ASSERT_TRUE(res6);
  19818. EXPECT_EQ(304, res6->status);
  19819. svr.stop();
  19820. t.join();
  19821. std::remove(fname);
  19822. }
  19823. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19824. using namespace httplib;
  19825. Server svr;
  19826. svr.set_mount_point("/static", ".");
  19827. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19828. svr.wait_until_ready();
  19829. Client cli(HOST, PORT);
  19830. // Send If-None-Match: * to a non-existent file
  19831. Headers h = {{"If-None-Match", "*"}};
  19832. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19834. EXPECT_EQ(404, res->status);
  19835. svr.stop();
  19836. t.join();
  19837. }
  19838. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19839. using namespace httplib;
  19840. // Create a test file
  19841. const char *fname = "etag_boundary_testfile.txt";
  19842. const char *content = "boundary-test";
  19843. {
  19844. std::ofstream ofs(fname);
  19845. ofs << content;
  19846. ASSERT_TRUE(ofs.good());
  19847. }
  19848. Server svr;
  19849. svr.set_mount_point("/static", ".");
  19850. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19851. svr.wait_until_ready();
  19852. Client cli(HOST, PORT);
  19853. // Get the actual ETag
  19854. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19855. ASSERT_TRUE(res1);
  19856. ASSERT_EQ(200, res1->status);
  19857. ASSERT_TRUE(res1->has_header("ETag"));
  19858. std::string etag = res1->get_header_value("ETag");
  19859. // Test 1: Very long ETag value (longer than actual ETag)
  19860. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19861. Headers h1 = {{"If-None-Match", "W/"
  19862. "\"very-long-etag-value-that-is-much-longer-"
  19863. "than-the-actual-etag-value\""}};
  19864. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19865. ASSERT_TRUE(res2);
  19866. EXPECT_EQ(200, res2->status); // Should not match
  19867. // Test 2: Long string followed by wildcard
  19868. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19869. // string)
  19870. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19871. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19872. ASSERT_TRUE(res3);
  19873. EXPECT_EQ(304, res3->status); // Should match on "*"
  19874. // Test 3: Wildcard followed by long string
  19875. // Should match on "*" immediately and return 304
  19876. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19877. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19878. ASSERT_TRUE(res4);
  19879. EXPECT_EQ(304, res4->status); // Should match on "*"
  19880. // Test 4: Multiple long non-matching values
  19881. // Should NOT match and return 200 (test that all comparisons are safe)
  19882. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19883. "W/\"second-long-non-matching-value\", "
  19884. "W/\"third-long-non-matching-value\""}};
  19885. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19886. ASSERT_TRUE(res5);
  19887. EXPECT_EQ(200, res5->status); // Should not match
  19888. // Test 5: Single character that is not "*" (edge case)
  19889. Headers h5 = {{"If-None-Match", "X"}};
  19890. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19891. ASSERT_TRUE(res6);
  19892. EXPECT_EQ(200, res6->status); // Should not match
  19893. svr.stop();
  19894. t.join();
  19895. std::remove(fname);
  19896. }
  19897. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19898. using namespace httplib;
  19899. // Create a test file
  19900. const char *fname = "ims_testfile.txt";
  19901. const char *content = "if-modified-since-test";
  19902. {
  19903. std::ofstream ofs(fname);
  19904. ofs << content;
  19905. ASSERT_TRUE(ofs.good());
  19906. }
  19907. Server svr;
  19908. svr.set_mount_point("/static", ".");
  19909. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19910. svr.wait_until_ready();
  19911. Client cli(HOST, PORT);
  19912. // First request: should get 200 with Last-Modified header
  19913. auto res1 = cli.Get("/static/ims_testfile.txt");
  19914. ASSERT_TRUE(res1);
  19915. ASSERT_EQ(200, res1->status);
  19916. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19917. std::string last_modified = res1->get_header_value("Last-Modified");
  19918. EXPECT_FALSE(last_modified.empty());
  19919. // If-Modified-Since with same time: expect 304
  19920. Headers h2 = {{"If-Modified-Since", last_modified}};
  19921. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19922. ASSERT_TRUE(res2);
  19923. EXPECT_EQ(304, res2->status);
  19924. // If-Modified-Since with future time: expect 304
  19925. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19926. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19927. ASSERT_TRUE(res3);
  19928. EXPECT_EQ(304, res3->status);
  19929. // If-Modified-Since with past time: expect 200
  19930. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19931. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19932. ASSERT_TRUE(res4);
  19933. EXPECT_EQ(200, res4->status);
  19934. // If-None-Match takes precedence over If-Modified-Since
  19935. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19936. ASSERT_TRUE(res1->has_header("ETag"));
  19937. std::string etag = res1->get_header_value("ETag");
  19938. Headers h5 = {{"If-None-Match", etag},
  19939. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19940. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19941. ASSERT_TRUE(res5);
  19942. EXPECT_EQ(304, res5->status);
  19943. svr.stop();
  19944. t.join();
  19945. std::remove(fname);
  19946. }
  19947. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19948. using namespace httplib;
  19949. Server svr;
  19950. // Endpoint that returns compressible content
  19951. svr.Get("/compressible", [](const Request &, Response &res) {
  19952. // Return a large enough body to trigger compression
  19953. std::string body(1000, 'a');
  19954. res.set_content(body, "text/plain");
  19955. });
  19956. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19957. svr.wait_until_ready();
  19958. Client cli(HOST, PORT);
  19959. // Request with gzip support: should get Vary header when compressed
  19960. cli.set_compress(true);
  19961. auto res1 = cli.Get("/compressible");
  19962. ASSERT_TRUE(res1);
  19963. EXPECT_EQ(200, res1->status);
  19964. // If Content-Encoding is set, Vary should also be set
  19965. if (res1->has_header("Content-Encoding")) {
  19966. EXPECT_TRUE(res1->has_header("Vary"));
  19967. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19968. }
  19969. // Request without Accept-Encoding header: should not have compression
  19970. Headers h_no_compress;
  19971. auto res2 = cli.Get("/compressible", h_no_compress);
  19972. ASSERT_TRUE(res2);
  19973. EXPECT_EQ(200, res2->status);
  19974. // Verify Vary header is present when compression is applied
  19975. // (the exact behavior depends on server configuration)
  19976. svr.stop();
  19977. t.join();
  19978. }
  19979. TEST(ETagTest, IfRangeWithETag) {
  19980. using namespace httplib;
  19981. // Create a test file with known content
  19982. const char *fname = "if_range_testfile.txt";
  19983. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19984. {
  19985. std::ofstream ofs(fname);
  19986. ofs << content;
  19987. ASSERT_TRUE(ofs.good());
  19988. }
  19989. Server svr;
  19990. svr.set_mount_point("/static", ".");
  19991. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19992. svr.wait_until_ready();
  19993. Client cli(HOST, PORT);
  19994. // First request: get ETag
  19995. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19996. ASSERT_TRUE(res1);
  19997. ASSERT_EQ(200, res1->status);
  19998. ASSERT_TRUE(res1->has_header("ETag"));
  19999. std::string etag = res1->get_header_value("ETag");
  20000. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20001. // Since our server generates weak ETags (W/"..."), If-Range with our
  20002. // ETag should NOT result in partial content - it should return full content.
  20003. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20004. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20005. ASSERT_TRUE(res2);
  20006. // Weak ETag in If-Range -> full content (200), not partial (206)
  20007. EXPECT_EQ(200, res2->status);
  20008. EXPECT_EQ(content, res2->body);
  20009. EXPECT_FALSE(res2->has_header("Content-Range"));
  20010. // Range request with non-matching If-Range (ETag): should get 200 (full
  20011. // content)
  20012. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20013. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20014. ASSERT_TRUE(res3);
  20015. EXPECT_EQ(200, res3->status);
  20016. EXPECT_EQ(content, res3->body);
  20017. EXPECT_FALSE(res3->has_header("Content-Range"));
  20018. // Range request with strong ETag (hypothetical - our server doesn't generate
  20019. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20020. // should return full content)
  20021. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20022. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20023. ASSERT_TRUE(res4);
  20024. EXPECT_EQ(200, res4->status);
  20025. EXPECT_EQ(content, res4->body);
  20026. EXPECT_FALSE(res4->has_header("Content-Range"));
  20027. svr.stop();
  20028. t.join();
  20029. std::remove(fname);
  20030. }
  20031. TEST(ETagTest, IfRangeWithDate) {
  20032. using namespace httplib;
  20033. // Create a test file
  20034. const char *fname = "if_range_date_testfile.txt";
  20035. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20036. {
  20037. std::ofstream ofs(fname);
  20038. ofs << content;
  20039. ASSERT_TRUE(ofs.good());
  20040. }
  20041. Server svr;
  20042. svr.set_mount_point("/static", ".");
  20043. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20044. svr.wait_until_ready();
  20045. Client cli(HOST, PORT);
  20046. // First request: get Last-Modified
  20047. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20048. ASSERT_TRUE(res1);
  20049. ASSERT_EQ(200, res1->status);
  20050. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20051. std::string last_modified = res1->get_header_value("Last-Modified");
  20052. // Range request with matching If-Range (date): should get 206
  20053. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20054. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20055. ASSERT_TRUE(res2);
  20056. EXPECT_EQ(206, res2->status);
  20057. EXPECT_EQ("FGHIJ", res2->body);
  20058. // Range request with old If-Range date: should get 200 (full content)
  20059. Headers h3 = {{"Range", "bytes=5-9"},
  20060. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20061. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20062. ASSERT_TRUE(res3);
  20063. EXPECT_EQ(200, res3->status);
  20064. EXPECT_EQ(content, res3->body);
  20065. // Range request with future If-Range date: should get 206
  20066. Headers h4 = {{"Range", "bytes=0-4"},
  20067. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20068. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20069. ASSERT_TRUE(res4);
  20070. EXPECT_EQ(206, res4->status);
  20071. EXPECT_EQ("ABCDE", res4->body);
  20072. svr.stop();
  20073. t.join();
  20074. std::remove(fname);
  20075. }
  20076. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20077. using namespace httplib;
  20078. const char *fname = "etag_malformed.txt";
  20079. const char *content = "malformed-etag";
  20080. {
  20081. std::ofstream ofs(fname);
  20082. ofs << content;
  20083. ASSERT_TRUE(ofs.good());
  20084. }
  20085. Server svr;
  20086. svr.set_mount_point("/static", ".");
  20087. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20088. svr.wait_until_ready();
  20089. Client cli(HOST, PORT);
  20090. // baseline: should get 200 and an ETag
  20091. auto res1 = cli.Get("/static/etag_malformed.txt");
  20092. ASSERT_TRUE(res1);
  20093. ASSERT_EQ(200, res1->status);
  20094. ASSERT_TRUE(res1->has_header("ETag"));
  20095. // Malformed ETag value (missing quotes) should be treated as non-matching
  20096. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20097. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20098. ASSERT_TRUE(res_bad);
  20099. EXPECT_EQ(200, res_bad->status);
  20100. // Whitespace-only header value should be considered invalid / non-matching
  20101. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20102. "Host: localhost\r\n"
  20103. "If-None-Match: \r\n"
  20104. "Connection: close\r\n"
  20105. "\r\n";
  20106. std::string out;
  20107. ASSERT_TRUE(send_request(5, raw_req, &out));
  20108. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20109. svr.stop();
  20110. t.join();
  20111. std::remove(fname);
  20112. }
  20113. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20114. using namespace httplib;
  20115. const char *fname = "ims_invalid_format.txt";
  20116. const char *content = "ims-bad-format";
  20117. {
  20118. std::ofstream ofs(fname);
  20119. ofs << content;
  20120. ASSERT_TRUE(ofs.good());
  20121. }
  20122. Server svr;
  20123. svr.set_mount_point("/static", ".");
  20124. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20125. svr.wait_until_ready();
  20126. Client cli(HOST, PORT);
  20127. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20128. ASSERT_TRUE(res1);
  20129. ASSERT_EQ(200, res1->status);
  20130. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20131. // If-Modified-Since with invalid format should not result in 304
  20132. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20133. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20134. ASSERT_TRUE(res_bad);
  20135. EXPECT_EQ(200, res_bad->status);
  20136. // If-Range with invalid date format should be treated as mismatch -> full
  20137. // content (200)
  20138. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20139. {"If-Range", "invalid-date"}};
  20140. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20141. ASSERT_TRUE(res_ifrange);
  20142. EXPECT_EQ(200, res_ifrange->status);
  20143. svr.stop();
  20144. t.join();
  20145. std::remove(fname);
  20146. }
  20147. TEST(ETagTest, IfRangeWithMalformedETag) {
  20148. using namespace httplib;
  20149. const char *fname = "ifrange_malformed.txt";
  20150. const std::string content = "0123456789";
  20151. {
  20152. std::ofstream ofs(fname);
  20153. ofs << content;
  20154. ASSERT_TRUE(ofs.good());
  20155. }
  20156. Server svr;
  20157. svr.set_mount_point("/static", ".");
  20158. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20159. svr.wait_until_ready();
  20160. Client cli(HOST, PORT);
  20161. // First request: get ETag
  20162. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20163. ASSERT_TRUE(res1);
  20164. ASSERT_EQ(200, res1->status);
  20165. ASSERT_TRUE(res1->has_header("ETag"));
  20166. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20167. // full content (200)
  20168. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20169. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20170. ASSERT_TRUE(res2);
  20171. EXPECT_EQ(200, res2->status);
  20172. EXPECT_EQ(content, res2->body);
  20173. svr.stop();
  20174. t.join();
  20175. std::remove(fname);
  20176. }
  20177. TEST(ETagTest, ExtremeLargeDateValues) {
  20178. using namespace httplib;
  20179. const char *fname = "ims_extreme_date.txt";
  20180. const char *content = "ims-extreme-date";
  20181. {
  20182. std::ofstream ofs(fname);
  20183. ofs << content;
  20184. ASSERT_TRUE(ofs.good());
  20185. }
  20186. Server svr;
  20187. svr.set_mount_point("/static", ".");
  20188. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20189. svr.wait_until_ready();
  20190. Client cli(HOST, PORT);
  20191. auto res1 = cli.Get(std::string("/static/") + fname);
  20192. ASSERT_TRUE(res1);
  20193. ASSERT_EQ(200, res1->status);
  20194. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20195. // Extremely large year that may overflow date parsing routines.
  20196. Headers h_large_date = {
  20197. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20198. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20199. ASSERT_TRUE(res_bad);
  20200. // Expect server to treat this as invalid/mismatch and return full content
  20201. EXPECT_EQ(200, res_bad->status);
  20202. // If-Range with extremely large date should be treated as mismatch -> full
  20203. // content (200)
  20204. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20205. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20206. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20207. ASSERT_TRUE(res_ifrange);
  20208. EXPECT_EQ(200, res_ifrange->status);
  20209. svr.stop();
  20210. t.join();
  20211. std::remove(fname);
  20212. }
  20213. TEST(ETagTest, NegativeFileModificationTime) {
  20214. using namespace httplib;
  20215. const char *fname = "ims_negative_mtime.txt";
  20216. const std::string content = "negative-mtime";
  20217. {
  20218. std::ofstream ofs(fname);
  20219. ofs << content;
  20220. ASSERT_TRUE(ofs.good());
  20221. }
  20222. // Try to set file mtime to a negative value. This may fail on some
  20223. // platforms/filesystems; if it fails, the test will still verify server
  20224. // behaves safely by performing a regular conditional request.
  20225. #if defined(__APPLE__) || defined(__linux__)
  20226. bool set_negative = false;
  20227. do {
  20228. struct timeval times[2];
  20229. // access time: now
  20230. times[0].tv_sec = time(nullptr);
  20231. times[0].tv_usec = 0;
  20232. // modification time: negative (e.g., -1)
  20233. times[1].tv_sec = -1;
  20234. times[1].tv_usec = 0;
  20235. if (utimes(fname, times) == 0) { set_negative = true; }
  20236. } while (0);
  20237. #else
  20238. bool set_negative = false;
  20239. #endif
  20240. Server svr;
  20241. svr.set_mount_point("/static", ".");
  20242. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20243. svr.wait_until_ready();
  20244. Client cli(HOST, PORT);
  20245. auto res1 = cli.Get(std::string("/static/") + fname);
  20246. ASSERT_TRUE(res1);
  20247. ASSERT_EQ(200, res1->status);
  20248. bool has_last_modified = res1->has_header("Last-Modified");
  20249. std::string last_modified;
  20250. if (has_last_modified) {
  20251. last_modified = res1->get_header_value("Last-Modified");
  20252. }
  20253. if (set_negative) {
  20254. // If we successfully set a negative mtime, ensure server returns a
  20255. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20256. // with an old date and ensure server handles it without crash.
  20257. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20258. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20259. ASSERT_TRUE(res2);
  20260. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20261. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20262. } else {
  20263. // Could not set negative mtime on this platform; fall back to verifying
  20264. // that normal invalid/malformed dates are treated safely (non-304).
  20265. Headers h_bad_date = {
  20266. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20267. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20268. ASSERT_TRUE(res_bad);
  20269. EXPECT_EQ(200, res_bad->status);
  20270. }
  20271. svr.stop();
  20272. t.join();
  20273. std::remove(fname);
  20274. }
  20275. //==============================================================================
  20276. // Integration Tests with Server
  20277. //==============================================================================
  20278. class SSEIntegrationTest : public ::testing::Test {
  20279. protected:
  20280. void SetUp() override {
  20281. stop_server_.store(false);
  20282. events_.clear();
  20283. server_ = httplib::detail::make_unique<Server>();
  20284. setup_server();
  20285. start_server();
  20286. }
  20287. void TearDown() override {
  20288. stop_server_.store(true);
  20289. event_cv_.notify_all();
  20290. server_->stop();
  20291. if (server_thread_.joinable()) { server_thread_.join(); }
  20292. }
  20293. void setup_server() {
  20294. // Simple SSE endpoint
  20295. server_->Get("/events", [this](const Request &req, Response &res) {
  20296. auto last_id = req.get_header_value("Last-Event-ID");
  20297. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20298. res.set_chunked_content_provider(
  20299. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20300. std::unique_lock<std::mutex> lock(event_mutex_);
  20301. if (event_cv_.wait_for(
  20302. lock, std::chrono::milliseconds(200), [this] {
  20303. return !events_.empty() || stop_server_.load();
  20304. })) {
  20305. if (stop_server_.load()) { return false; }
  20306. if (!events_.empty()) {
  20307. std::string event = events_.front();
  20308. events_.erase(events_.begin());
  20309. sink.write(event.data(), event.size());
  20310. return true;
  20311. }
  20312. }
  20313. return !stop_server_.load();
  20314. });
  20315. });
  20316. // Endpoint that returns error
  20317. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20318. res.status = 500;
  20319. res.set_content("Internal Server Error", "text/plain");
  20320. });
  20321. // Endpoint for custom event types
  20322. server_->Get("/custom-events", [](const Request &, Response &res) {
  20323. res.set_chunked_content_provider(
  20324. "text/event-stream", [](size_t offset, DataSink &sink) {
  20325. if (offset == 0) {
  20326. std::string event = "event: update\ndata: updated\n\n"
  20327. "event: delete\ndata: deleted\n\n";
  20328. sink.write(event.data(), event.size());
  20329. }
  20330. return false; // End stream after sending
  20331. });
  20332. });
  20333. }
  20334. void start_server() {
  20335. port_ = server_->bind_to_any_port(HOST);
  20336. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20337. // Wait for server to start
  20338. while (!server_->is_running()) {
  20339. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20340. }
  20341. }
  20342. int get_port() const { return port_; }
  20343. void send_event(const std::string &event) {
  20344. std::lock_guard<std::mutex> lock(event_mutex_);
  20345. events_.push_back(event);
  20346. event_cv_.notify_all();
  20347. }
  20348. std::unique_ptr<Server> server_;
  20349. std::thread server_thread_;
  20350. std::mutex event_mutex_;
  20351. std::condition_variable event_cv_;
  20352. std::vector<std::string> events_;
  20353. std::atomic<bool> stop_server_{false};
  20354. std::string last_received_event_id_;
  20355. int port_ = 0;
  20356. };
  20357. //==============================================================================
  20358. // SSE Parsing Tests
  20359. //==============================================================================
  20360. class SSEParsingTest : public SSEIntegrationTest {
  20361. protected:
  20362. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20363. // A trailing sentinel event tells when the whole stream has been parsed.
  20364. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20365. auto body = stream + "event: end\ndata: end\n\n";
  20366. server_->Get("/parse", [body](const Request &, Response &res) {
  20367. res.set_content(body, "text/event-stream");
  20368. });
  20369. return collect("/parse");
  20370. }
  20371. // Runs SSEClient against path until an "end" event arrives and returns the
  20372. // messages dispatched before it
  20373. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20374. Client client(HOST, get_port());
  20375. sse::SSEClient sse(client, path);
  20376. std::mutex mutex;
  20377. std::condition_variable cv;
  20378. std::vector<sse::SSEMessage> messages;
  20379. auto done = false;
  20380. sse.on_message([&](const sse::SSEMessage &msg) {
  20381. std::lock_guard<std::mutex> lock(mutex);
  20382. // Ignore a replay from a reconnect that races with stop()
  20383. if (!done) { messages.push_back(msg); }
  20384. });
  20385. sse.on_event("end", [&](const sse::SSEMessage &) {
  20386. std::lock_guard<std::mutex> lock(mutex);
  20387. done = true;
  20388. cv.notify_all();
  20389. });
  20390. sse.set_reconnect_interval(100);
  20391. sse.start_async();
  20392. {
  20393. std::unique_lock<std::mutex> lock(mutex);
  20394. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20395. }
  20396. sse.stop();
  20397. EXPECT_TRUE(done);
  20398. return messages;
  20399. }
  20400. };
  20401. TEST_F(SSEParsingTest, SingleLineData) {
  20402. auto msgs = parse("data: hello\n\n");
  20403. ASSERT_EQ(msgs.size(), 1u);
  20404. EXPECT_EQ(msgs[0].data, "hello");
  20405. EXPECT_EQ(msgs[0].event, "message");
  20406. }
  20407. TEST_F(SSEParsingTest, MultiLineData) {
  20408. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20409. ASSERT_EQ(msgs.size(), 1u);
  20410. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20411. }
  20412. TEST_F(SSEParsingTest, CustomEventType) {
  20413. auto msgs = parse("event: update\ndata: payload\n\n");
  20414. ASSERT_EQ(msgs.size(), 1u);
  20415. EXPECT_EQ(msgs[0].event, "update");
  20416. EXPECT_EQ(msgs[0].data, "payload");
  20417. }
  20418. TEST_F(SSEParsingTest, EventIdHandling) {
  20419. auto msgs = parse("id: 12345\ndata: test\n\n");
  20420. ASSERT_EQ(msgs.size(), 1u);
  20421. EXPECT_EQ(msgs[0].id, "12345");
  20422. }
  20423. TEST_F(SSEParsingTest, EmptyEventId) {
  20424. auto msgs = parse("id:\ndata: test\n\n");
  20425. ASSERT_EQ(msgs.size(), 1u);
  20426. EXPECT_EQ(msgs[0].id, "");
  20427. }
  20428. TEST_F(SSEParsingTest, CommentsIgnored) {
  20429. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20430. ASSERT_EQ(msgs.size(), 1u);
  20431. EXPECT_EQ(msgs[0].data, "hello");
  20432. EXPECT_EQ(msgs[0].event, "message");
  20433. }
  20434. TEST_F(SSEParsingTest, ColonInValue) {
  20435. auto msgs = parse("data: hello:world:test\n\n");
  20436. ASSERT_EQ(msgs.size(), 1u);
  20437. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20438. }
  20439. TEST_F(SSEParsingTest, FieldNameOnly) {
  20440. // A line without a colon is a field name with an empty value
  20441. auto msgs = parse("data\n\n");
  20442. ASSERT_EQ(msgs.size(), 1u);
  20443. EXPECT_EQ(msgs[0].data, "");
  20444. }
  20445. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20446. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20447. ASSERT_EQ(msgs.size(), 1u);
  20448. EXPECT_EQ(msgs[0].event, "update");
  20449. EXPECT_EQ(msgs[0].data, "hello");
  20450. }
  20451. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20452. auto msgs = parse("data\r\n\r\n");
  20453. ASSERT_EQ(msgs.size(), 1u);
  20454. EXPECT_EQ(msgs[0].data, "");
  20455. }
  20456. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20457. auto msgs = parse("event: update\rdata: hello\r\r");
  20458. ASSERT_EQ(msgs.size(), 1u);
  20459. EXPECT_EQ(msgs[0].event, "update");
  20460. EXPECT_EQ(msgs[0].data, "hello");
  20461. }
  20462. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20463. // Chunk boundaries fall inside every \r\n and right before the first one
  20464. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20465. "\n\r", "\nevent: end\ndata: end\n\n"};
  20466. server_->Get("/split", [chunks](const Request &, Response &res) {
  20467. auto i = std::make_shared<size_t>(0);
  20468. res.set_chunked_content_provider(
  20469. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20470. if (*i == chunks.size()) {
  20471. sink.done();
  20472. } else {
  20473. sink.write(chunks[*i].data(), chunks[*i].size());
  20474. (*i)++;
  20475. }
  20476. return true;
  20477. });
  20478. });
  20479. auto msgs = collect("/split");
  20480. ASSERT_EQ(msgs.size(), 1u);
  20481. EXPECT_EQ(msgs[0].event, "update");
  20482. EXPECT_EQ(msgs[0].data, "hello");
  20483. }
  20484. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20485. // Only a BOM at the start of the stream is ignored
  20486. auto msgs = parse("\xEF\xBB\xBF"
  20487. "data: first\n\n"
  20488. "\xEF\xBB\xBF"
  20489. "data: second\n\n");
  20490. ASSERT_EQ(msgs.size(), 1u);
  20491. EXPECT_EQ(msgs[0].data, "first");
  20492. }
  20493. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20494. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20495. ASSERT_EQ(msgs.size(), 1u);
  20496. EXPECT_EQ(msgs[0].data, "hello");
  20497. EXPECT_EQ(msgs[0].event, "message");
  20498. }
  20499. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20500. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20501. ASSERT_EQ(msgs.size(), 2u);
  20502. EXPECT_EQ(msgs[0].data, "hello");
  20503. EXPECT_EQ(msgs[1].data, "hello");
  20504. }
  20505. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20506. // An event without data is not dispatched, and its type must not leak
  20507. // into the next event
  20508. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20509. ASSERT_EQ(msgs.size(), 1u);
  20510. EXPECT_EQ(msgs[0].event, "message");
  20511. EXPECT_EQ(msgs[0].data, "hello");
  20512. }
  20513. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20514. // The first connection sends only an id; the second echoes back the
  20515. // Last-Event-ID it was reconnected with
  20516. std::atomic<int> connection_count{0};
  20517. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20518. if (connection_count++ == 0) {
  20519. res.set_content("id: 42\n\n", "text/event-stream");
  20520. } else {
  20521. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20522. "\n\nevent: end\ndata: end\n\n",
  20523. "text/event-stream");
  20524. }
  20525. });
  20526. auto msgs = collect("/id-only");
  20527. ASSERT_EQ(msgs.size(), 1u);
  20528. EXPECT_EQ(msgs[0].data, "42");
  20529. }
  20530. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20531. // The first connection sets an id and then clears it with an empty one; the
  20532. // second reports whether it was reconnected with a Last-Event-ID
  20533. std::atomic<int> connection_count{0};
  20534. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20535. if (connection_count++ == 0) {
  20536. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20537. "text/event-stream");
  20538. } else {
  20539. res.set_content(
  20540. std::string("data: ") +
  20541. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20542. "\n\nevent: end\ndata: end\n\n",
  20543. "text/event-stream");
  20544. }
  20545. });
  20546. auto msgs = collect("/id-clear");
  20547. ASSERT_EQ(msgs.size(), 3u);
  20548. EXPECT_EQ(msgs[0].id, "1");
  20549. EXPECT_EQ(msgs[1].id, "");
  20550. EXPECT_EQ(msgs[2].data, "not sent");
  20551. }
  20552. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20553. // The first connection sets an id and then sends ids that cannot be carried
  20554. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20555. // with
  20556. std::atomic<int> connection_count{0};
  20557. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20558. if (connection_count++ == 0) {
  20559. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20560. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20561. "text/event-stream");
  20562. } else {
  20563. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20564. "\n\nevent: end\ndata: end\n\n",
  20565. "text/event-stream");
  20566. }
  20567. });
  20568. auto msgs = collect("/id-unsendable");
  20569. ASSERT_EQ(msgs.size(), 1u);
  20570. EXPECT_EQ(msgs[0].data, "42");
  20571. }
  20572. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20573. auto msgs = parse("event: notification\nid: evt-42\n"
  20574. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20575. ASSERT_EQ(msgs.size(), 1u);
  20576. EXPECT_EQ(msgs[0].event, "notification");
  20577. EXPECT_EQ(msgs[0].id, "evt-42");
  20578. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20579. }
  20580. TEST(SSEMessageTest, Clear) {
  20581. sse::SSEMessage msg;
  20582. msg.event = "custom";
  20583. msg.data = "some data";
  20584. msg.id = "123";
  20585. msg.clear();
  20586. EXPECT_EQ(msg.event, "message");
  20587. EXPECT_EQ(msg.data, "");
  20588. EXPECT_EQ(msg.id, "");
  20589. }
  20590. //==============================================================================
  20591. // SSE Integration Tests
  20592. //==============================================================================
  20593. // Test: Successful connection and on_open callback
  20594. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20595. // Add a simple endpoint that sends one event and closes
  20596. server_->Get("/simple-event", [](const Request &, Response &res) {
  20597. res.set_chunked_content_provider(
  20598. "text/event-stream", [](size_t offset, DataSink &sink) {
  20599. if (offset == 0) {
  20600. std::string event = "data: hello\n\n";
  20601. sink.write(event.data(), event.size());
  20602. }
  20603. return false; // Close stream after sending
  20604. });
  20605. });
  20606. Client client("localhost", get_port());
  20607. sse::SSEClient sse(client, "/simple-event");
  20608. std::atomic<bool> open_called{false};
  20609. std::atomic<bool> message_received{false};
  20610. sse.on_open([&open_called]() { open_called.store(true); });
  20611. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20612. if (msg.data == "hello") { message_received.store(true); }
  20613. });
  20614. sse.set_reconnect_interval(100);
  20615. sse.set_max_reconnect_attempts(1);
  20616. // Start async
  20617. sse.start_async();
  20618. // Wait for message to be processed
  20619. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20620. sse.stop();
  20621. EXPECT_TRUE(open_called.load());
  20622. EXPECT_TRUE(message_received.load());
  20623. }
  20624. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20625. // A data line that never ends.
  20626. server_->Get("/endless-line", [](const Request &, Response &res) {
  20627. res.set_chunked_content_provider(
  20628. "text/event-stream", [](size_t offset, DataSink &sink) {
  20629. if (offset == 0) { sink.write("data: ", 6); }
  20630. std::string chunk(64 * 1024, 'A');
  20631. return sink.write(chunk.data(), chunk.size());
  20632. });
  20633. });
  20634. Client client("localhost", get_port());
  20635. // Lift the payload limit, so that only the event limit can end this endless
  20636. // stream.
  20637. client.set_payload_max_length(0);
  20638. sse::SSEClient sse(client, "/endless-line");
  20639. std::atomic<bool> too_long{false};
  20640. sse.on_error([&](Error err) {
  20641. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20642. });
  20643. sse.set_max_reconnect_attempts(1);
  20644. sse.start_async();
  20645. for (int i = 0; i < 500 && !too_long; i++) {
  20646. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20647. }
  20648. sse.stop();
  20649. EXPECT_TRUE(too_long);
  20650. }
  20651. // Test: on_message callback
  20652. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20653. // Endpoint that sends multiple events then closes
  20654. server_->Get("/multi-event", [](const Request &, Response &res) {
  20655. res.set_chunked_content_provider(
  20656. "text/event-stream", [](size_t offset, DataSink &sink) {
  20657. if (offset == 0) {
  20658. std::string events = "data: message1\n\ndata: message2\n\n";
  20659. sink.write(events.data(), events.size());
  20660. }
  20661. return false;
  20662. });
  20663. });
  20664. Client client("localhost", get_port());
  20665. sse::SSEClient sse(client, "/multi-event");
  20666. std::vector<std::string> received_messages;
  20667. std::mutex messages_mutex;
  20668. sse.on_message([&](const sse::SSEMessage &msg) {
  20669. std::lock_guard<std::mutex> lock(messages_mutex);
  20670. received_messages.push_back(msg.data);
  20671. });
  20672. sse.set_reconnect_interval(100);
  20673. sse.set_max_reconnect_attempts(1);
  20674. sse.start_async();
  20675. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20676. sse.stop();
  20677. std::lock_guard<std::mutex> lock(messages_mutex);
  20678. EXPECT_GE(received_messages.size(), 2u);
  20679. if (received_messages.size() >= 2) {
  20680. EXPECT_EQ(received_messages[0], "message1");
  20681. EXPECT_EQ(received_messages[1], "message2");
  20682. }
  20683. }
  20684. // Test: on_event for specific types
  20685. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20686. Client client("localhost", get_port());
  20687. sse::SSEClient sse(client, "/custom-events");
  20688. std::atomic<bool> update_received{false};
  20689. std::atomic<bool> delete_received{false};
  20690. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20691. if (msg.data == "updated") { update_received.store(true); }
  20692. });
  20693. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20694. if (msg.data == "deleted") { delete_received.store(true); }
  20695. });
  20696. sse.set_max_reconnect_attempts(1);
  20697. sse.start_async();
  20698. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20699. sse.stop();
  20700. EXPECT_TRUE(update_received.load());
  20701. EXPECT_TRUE(delete_received.load());
  20702. }
  20703. // Test: on_error callback on connection failure
  20704. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20705. // Connect to a non-existent port
  20706. Client client("localhost", 59999);
  20707. sse::SSEClient sse(client, "/events");
  20708. std::atomic<bool> error_called{false};
  20709. Error received_error = Error::Success;
  20710. sse.on_error([&](Error err) {
  20711. error_called.store(true);
  20712. received_error = err;
  20713. });
  20714. sse.set_reconnect_interval(50);
  20715. sse.set_max_reconnect_attempts(1);
  20716. sse.start_async();
  20717. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20718. sse.stop();
  20719. EXPECT_TRUE(error_called.load());
  20720. EXPECT_NE(received_error, Error::Success);
  20721. }
  20722. // Test: Last-Event-ID header sent on reconnect
  20723. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20724. // Endpoint that sends event with ID
  20725. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20726. res.set_chunked_content_provider(
  20727. "text/event-stream", [](size_t offset, DataSink &sink) {
  20728. if (offset == 0) {
  20729. std::string event = "id: evt-123\ndata: test\n\n";
  20730. sink.write(event.data(), event.size());
  20731. }
  20732. return false;
  20733. });
  20734. });
  20735. Client client("localhost", get_port());
  20736. sse::SSEClient sse(client, "/event-with-id");
  20737. std::atomic<bool> id_received{false};
  20738. sse.on_message([&](const sse::SSEMessage &msg) {
  20739. if (!msg.id.empty()) { id_received.store(true); }
  20740. });
  20741. sse.set_reconnect_interval(100);
  20742. sse.set_max_reconnect_attempts(1);
  20743. sse.start_async();
  20744. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20745. sse.stop();
  20746. EXPECT_TRUE(id_received.load());
  20747. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20748. }
  20749. // Test: Manual stop
  20750. TEST_F(SSEIntegrationTest, ManualStop) {
  20751. // Endpoint that sends one event and stays open briefly
  20752. std::atomic<bool> handler_running{true};
  20753. server_->Get("/stay-open", [&handler_running](const Request &,
  20754. Response &res) {
  20755. res.set_chunked_content_provider(
  20756. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20757. if (offset == 0) {
  20758. std::string event = "data: connected\n\n";
  20759. sink.write(event.data(), event.size());
  20760. }
  20761. // Keep connection open while handler_running is true
  20762. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20763. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20764. }
  20765. return false;
  20766. });
  20767. });
  20768. Client client("localhost", get_port());
  20769. sse::SSEClient sse(client, "/stay-open");
  20770. std::atomic<bool> connected{false};
  20771. sse.on_open([&connected]() { connected.store(true); });
  20772. sse.set_reconnect_interval(100);
  20773. sse.set_max_reconnect_attempts(1);
  20774. sse.start_async();
  20775. // Wait for connection to establish
  20776. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20777. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20778. }
  20779. EXPECT_TRUE(connected.load());
  20780. EXPECT_TRUE(sse.is_connected());
  20781. // Signal handler to stop
  20782. handler_running.store(false);
  20783. // Stop SSE client
  20784. sse.stop();
  20785. EXPECT_FALSE(sse.is_connected());
  20786. }
  20787. // Test: SSEClient with custom headers
  20788. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20789. // Setup a server endpoint that checks for custom header
  20790. std::atomic<bool> header_received{false};
  20791. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20792. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20793. header_received.store(true);
  20794. }
  20795. res.set_chunked_content_provider("text/event-stream",
  20796. [](size_t, DataSink &) { return false; });
  20797. });
  20798. Client client("localhost", get_port());
  20799. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20800. sse::SSEClient sse(client, "/header-check", headers);
  20801. sse.set_max_reconnect_attempts(1);
  20802. sse.start_async();
  20803. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20804. sse.stop();
  20805. EXPECT_TRUE(header_received.load());
  20806. }
  20807. // Test: Reconnect interval configuration
  20808. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20809. Client client("localhost", get_port());
  20810. sse::SSEClient sse(client, "/events");
  20811. auto &result = sse.set_reconnect_interval(500);
  20812. // Builder pattern should return reference to self
  20813. EXPECT_EQ(&result, &sse);
  20814. }
  20815. // Test: Max reconnect attempts
  20816. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20817. // Connect to non-existent port to force reconnects
  20818. Client client("localhost", 59998);
  20819. sse::SSEClient sse(client, "/events");
  20820. std::atomic<int> error_count{0};
  20821. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20822. sse.set_reconnect_interval(50);
  20823. sse.set_max_reconnect_attempts(2);
  20824. auto start = std::chrono::steady_clock::now();
  20825. sse.start(); // Blocking call
  20826. auto end = std::chrono::steady_clock::now();
  20827. // Should have stopped after 2 failed attempts
  20828. EXPECT_GE(error_count.load(), 2);
  20829. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20830. auto duration =
  20831. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20832. #ifdef _WIN32
  20833. // Windows is much slower for socket connection failures
  20834. EXPECT_LT(duration.count(), 7000);
  20835. #else
  20836. EXPECT_LT(duration.count(), 1000);
  20837. #endif
  20838. }
  20839. // Test: Multi-line data in integration
  20840. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20841. // Endpoint with multi-line data
  20842. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20843. res.set_chunked_content_provider(
  20844. "text/event-stream", [](size_t offset, DataSink &sink) {
  20845. if (offset == 0) {
  20846. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20847. sink.write(event.data(), event.size());
  20848. }
  20849. return false;
  20850. });
  20851. });
  20852. Client client("localhost", get_port());
  20853. sse::SSEClient sse(client, "/multiline-data");
  20854. std::string received_data;
  20855. std::mutex data_mutex;
  20856. sse.on_message([&](const sse::SSEMessage &msg) {
  20857. std::lock_guard<std::mutex> lock(data_mutex);
  20858. received_data = msg.data;
  20859. });
  20860. sse.set_reconnect_interval(100);
  20861. sse.set_max_reconnect_attempts(1);
  20862. sse.start_async();
  20863. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20864. sse.stop();
  20865. std::lock_guard<std::mutex> lock(data_mutex);
  20866. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20867. }
  20868. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20869. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20870. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20871. DataSink &sink) {
  20872. if (offset == 0) {
  20873. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20874. sink.write(events.data(), events.size());
  20875. }
  20876. return false;
  20877. });
  20878. });
  20879. Client client("localhost", get_port());
  20880. sse::SSEClient sse(client, "/empty-data-lines");
  20881. std::mutex mutex;
  20882. std::condition_variable cv;
  20883. std::vector<std::string> received;
  20884. sse.on_message([&](const sse::SSEMessage &msg) {
  20885. std::lock_guard<std::mutex> lock(mutex);
  20886. received.push_back(msg.data);
  20887. cv.notify_all();
  20888. });
  20889. sse.set_max_reconnect_attempts(1);
  20890. sse.start_async();
  20891. {
  20892. std::unique_lock<std::mutex> lock(mutex);
  20893. cv.wait_for(lock, std::chrono::seconds(2),
  20894. [&] { return received.size() >= 3; });
  20895. }
  20896. sse.stop();
  20897. ASSERT_GE(received.size(), 3u);
  20898. EXPECT_EQ(received[0], "");
  20899. EXPECT_EQ(received[1], "\nhello");
  20900. EXPECT_EQ(received[2], "");
  20901. }
  20902. // Test: Auto-reconnect after server disconnection
  20903. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20904. std::atomic<int> connection_count{0};
  20905. std::atomic<int> message_count{0};
  20906. // Endpoint that sends one event and closes, forcing reconnect
  20907. server_->Get("/reconnect-test",
  20908. [&connection_count](const Request &, Response &res) {
  20909. connection_count.fetch_add(1);
  20910. res.set_chunked_content_provider(
  20911. "text/event-stream", [](size_t offset, DataSink &sink) {
  20912. if (offset == 0) {
  20913. std::string event = "data: hello\n\n";
  20914. sink.write(event.data(), event.size());
  20915. }
  20916. return false; // Close connection after sending
  20917. });
  20918. });
  20919. Client client("localhost", get_port());
  20920. sse::SSEClient sse(client, "/reconnect-test");
  20921. sse.on_message([&message_count](const sse::SSEMessage &) {
  20922. message_count.fetch_add(1);
  20923. });
  20924. sse.set_reconnect_interval(100);
  20925. sse.set_max_reconnect_attempts(3);
  20926. sse.start_async();
  20927. // Wait long enough for multiple reconnects
  20928. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20929. sse.stop();
  20930. // Should have connected multiple times (initial + reconnects)
  20931. EXPECT_GE(connection_count.load(), 2);
  20932. // Should have received messages from multiple connections
  20933. EXPECT_GE(message_count.load(), 2);
  20934. }
  20935. // Test: A retry field that is not all ASCII digits is ignored
  20936. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20937. std::atomic<int> connection_count{0};
  20938. server_->Get("/bad-retry",
  20939. [&connection_count](const Request &, Response &res) {
  20940. connection_count.fetch_add(1);
  20941. res.set_chunked_content_provider(
  20942. "text/event-stream", [](size_t offset, DataSink &sink) {
  20943. if (offset == 0) {
  20944. std::string event = "retry: -1\ndata: hello\n\n";
  20945. sink.write(event.data(), event.size());
  20946. }
  20947. return false;
  20948. });
  20949. });
  20950. Client client("localhost", get_port());
  20951. sse::SSEClient sse(client, "/bad-retry");
  20952. sse.set_reconnect_interval(10000);
  20953. sse.start_async();
  20954. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20955. sse.stop();
  20956. EXPECT_EQ(connection_count.load(), 1);
  20957. }
  20958. // Test: A retry field of all ASCII digits sets the reconnection time
  20959. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20960. std::mutex mutex;
  20961. std::condition_variable cv;
  20962. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20963. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20964. {
  20965. std::lock_guard<std::mutex> lock(mutex);
  20966. connected_at.push_back(std::chrono::steady_clock::now());
  20967. cv.notify_all();
  20968. }
  20969. res.set_chunked_content_provider(
  20970. "text/event-stream", [](size_t offset, DataSink &sink) {
  20971. if (offset == 0) {
  20972. std::string event = "retry: 0\ndata: hello\n\n";
  20973. sink.write(event.data(), event.size());
  20974. }
  20975. return false;
  20976. });
  20977. });
  20978. Client client("localhost", get_port());
  20979. sse::SSEClient sse(client, "/zero-retry");
  20980. sse.set_reconnect_interval(10000);
  20981. sse.start_async();
  20982. {
  20983. std::unique_lock<std::mutex> lock(mutex);
  20984. cv.wait_for(lock, std::chrono::seconds(5),
  20985. [&] { return connected_at.size() >= 2; });
  20986. }
  20987. sse.stop();
  20988. // The server-supplied interval is applied, but never below 100ms, so
  20989. // "retry: 0" does not cause a busy reconnect loop
  20990. std::lock_guard<std::mutex> lock(mutex);
  20991. ASSERT_GE(connected_at.size(), 2u);
  20992. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20993. connected_at[1] - connected_at[0])
  20994. .count();
  20995. EXPECT_GE(interval_ms, 100);
  20996. }
  20997. // Test: Last-Event-ID sent on reconnect
  20998. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20999. std::atomic<int> connection_count{0};
  21000. std::vector<std::string> received_last_event_ids;
  21001. std::mutex id_mutex;
  21002. // Endpoint that checks Last-Event-ID header and sends event with ID
  21003. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21004. int conn = connection_count.fetch_add(1);
  21005. // Capture the Last-Event-ID header from each connection
  21006. {
  21007. std::lock_guard<std::mutex> lock(id_mutex);
  21008. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21009. }
  21010. res.set_chunked_content_provider(
  21011. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21012. if (offset == 0) {
  21013. std::string event =
  21014. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21015. sink.write(event.data(), event.size());
  21016. }
  21017. return false;
  21018. });
  21019. });
  21020. Client client("localhost", get_port());
  21021. sse::SSEClient sse(client, "/reconnect-with-id");
  21022. sse.set_reconnect_interval(100);
  21023. sse.set_max_reconnect_attempts(3);
  21024. sse.start_async();
  21025. // Wait for at least 2 connections
  21026. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21027. sse.stop();
  21028. // Verify behavior
  21029. std::lock_guard<std::mutex> lock(id_mutex);
  21030. EXPECT_GE(received_last_event_ids.size(), 2u);
  21031. // First connection should have no Last-Event-ID
  21032. if (!received_last_event_ids.empty()) {
  21033. EXPECT_EQ(received_last_event_ids[0], "");
  21034. }
  21035. // Second connection should have Last-Event-ID from first connection
  21036. if (received_last_event_ids.size() >= 2) {
  21037. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21038. }
  21039. }
  21040. // Test: set_headers updates headers used on reconnect
  21041. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21042. std::vector<std::string> received_tokens;
  21043. std::mutex token_mutex;
  21044. // Endpoint that captures Authorization header
  21045. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21046. {
  21047. std::lock_guard<std::mutex> lock(token_mutex);
  21048. received_tokens.push_back(req.get_header_value("Authorization"));
  21049. }
  21050. res.set_chunked_content_provider(
  21051. "text/event-stream", [](size_t offset, DataSink &sink) {
  21052. if (offset == 0) {
  21053. std::string event = "data: hello\n\n";
  21054. sink.write(event.data(), event.size());
  21055. }
  21056. return false; // Close connection to trigger reconnect
  21057. });
  21058. });
  21059. Client client("localhost", get_port());
  21060. Headers headers = {{"Authorization", "Bearer old-token"}};
  21061. sse::SSEClient sse(client, "/auth-check", headers);
  21062. // Update headers on each successful connection
  21063. sse.on_open(
  21064. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21065. sse.set_reconnect_interval(100);
  21066. sse.set_max_reconnect_attempts(3);
  21067. sse.start_async();
  21068. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21069. sse.stop();
  21070. std::lock_guard<std::mutex> lock(token_mutex);
  21071. ASSERT_GE(received_tokens.size(), 2u);
  21072. // First connection uses original header
  21073. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21074. // Second connection uses updated header from set_headers
  21075. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21076. }
  21077. // Test: 401 allows reconnection (so on_error can refresh headers)
  21078. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21079. std::atomic<int> connection_count{0};
  21080. // Endpoint: returns 401 on first attempt, 200 on second
  21081. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21082. int conn = connection_count.fetch_add(1);
  21083. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21084. res.status = StatusCode::Unauthorized_401;
  21085. res.set_content("Unauthorized", "text/plain");
  21086. return;
  21087. }
  21088. res.set_chunked_content_provider(
  21089. "text/event-stream", [](size_t offset, DataSink &sink) {
  21090. if (offset == 0) {
  21091. std::string event = "data: authenticated\n\n";
  21092. sink.write(event.data(), event.size());
  21093. }
  21094. return false;
  21095. });
  21096. });
  21097. Client client("localhost", get_port());
  21098. Headers headers = {{"Authorization", "Bearer expired"}};
  21099. sse::SSEClient sse(client, "/auth-retry", headers);
  21100. std::atomic<bool> message_received{false};
  21101. // Refresh token on error
  21102. sse.on_error(
  21103. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21104. sse.on_message([&](const sse::SSEMessage &msg) {
  21105. if (msg.data == "authenticated") { message_received.store(true); }
  21106. });
  21107. sse.set_reconnect_interval(100);
  21108. sse.set_max_reconnect_attempts(3);
  21109. sse.start_async();
  21110. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21111. sse.stop();
  21112. // Should have reconnected after 401 and succeeded with new token
  21113. EXPECT_GE(connection_count.load(), 2);
  21114. EXPECT_TRUE(message_received.load());
  21115. }
  21116. TEST(Issue2318Test, EmptyHostString) {
  21117. {
  21118. httplib::Client cli_empty("", PORT);
  21119. auto res = cli_empty.Get("/");
  21120. ASSERT_FALSE(res);
  21121. EXPECT_EQ(httplib::Error::Connection, res.error());
  21122. }
  21123. {
  21124. httplib::Client cli(" ", PORT);
  21125. auto res = cli.Get("/");
  21126. ASSERT_FALSE(res);
  21127. EXPECT_EQ(httplib::Error::Connection, res.error());
  21128. }
  21129. }
  21130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21131. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21132. Server svr;
  21133. // Set a small payload limit (1KB)
  21134. svr.set_payload_max_length(1024);
  21135. svr.Post("/test", [&](const Request &req, Response &res) {
  21136. res.set_content("Body size: " + std::to_string(req.body.size()),
  21137. "text/plain");
  21138. });
  21139. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21140. auto se = detail::scope_exit([&] {
  21141. svr.stop();
  21142. listen_thread.join();
  21143. });
  21144. svr.wait_until_ready();
  21145. // Create data that compresses well but exceeds limit when decompressed
  21146. // 8KB of repeated null bytes compresses to a very small size
  21147. std::string original_data(8 * 1024, '\0');
  21148. // Compress the data using gzip
  21149. std::string compressed_data;
  21150. detail::gzip_compressor compressor;
  21151. compressor.compress(original_data.data(), original_data.size(), true,
  21152. [&](const char *data, size_t size) {
  21153. compressed_data.append(data, size);
  21154. return true;
  21155. });
  21156. // Verify compression worked (compressed should be much smaller)
  21157. ASSERT_LT(compressed_data.size(), original_data.size());
  21158. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21159. // Send compressed data with Content-Encoding: gzip
  21160. Client cli(HOST, PORT);
  21161. Headers headers = {{"Content-Encoding", "gzip"}};
  21162. auto res =
  21163. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21164. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21166. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21167. }
  21168. #endif
  21169. // ============================================================================
  21170. // OpenSSL-Specific Tests
  21171. // ============================================================================
  21172. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21173. X509 *readCertificate(const std::string &strFileName) {
  21174. std::ifstream inStream(strFileName);
  21175. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21176. std::istreambuf_iterator<char>());
  21177. if (strCertPEM.empty()) return (nullptr);
  21178. BIO *pbCert = BIO_new(BIO_s_mem());
  21179. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21180. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21181. BIO_free(pbCert);
  21182. return (pCert);
  21183. }
  21184. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21185. std::ifstream inStream(strFileName);
  21186. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21187. std::istreambuf_iterator<char>());
  21188. if (strPrivateKeyPEM.empty()) return (nullptr);
  21189. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21190. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21191. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21192. BIO_free(pbPrivKey);
  21193. return (pPrivateKey);
  21194. }
  21195. TEST(BindServerTest, UpdateCerts) {
  21196. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21197. int port = svr.bind_to_any_port("0.0.0.0");
  21198. ASSERT_TRUE(svr.is_valid());
  21199. ASSERT_TRUE(port > 0);
  21200. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21201. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21202. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21203. ASSERT_TRUE(cert != nullptr);
  21204. ASSERT_TRUE(ca_cert != nullptr);
  21205. ASSERT_TRUE(key != nullptr);
  21206. X509_STORE *cert_store = X509_STORE_new();
  21207. X509_STORE_add_cert(cert_store, ca_cert);
  21208. // svr.update_certs(cert, key, cert_store); // deprecated
  21209. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21210. CLIENT_CA_CERT_FILE);
  21211. ASSERT_TRUE(svr.is_valid());
  21212. svr.stop();
  21213. X509_STORE_free(cert_store);
  21214. X509_free(cert);
  21215. X509_free(ca_cert);
  21216. EVP_PKEY_free(key);
  21217. }
  21218. // Test that update_certs() updates client CA list correctly
  21219. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21220. // Start with file-based constructor
  21221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21222. ASSERT_TRUE(svr.is_valid());
  21223. // Initially no client CA list should be set
  21224. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21225. ASSERT_TRUE(ssl_ctx != nullptr);
  21226. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21227. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21228. EXPECT_EQ(0, count_before);
  21229. // Now update with client CA (PEM string)
  21230. std::string cert_pem, key_pem, ca_pem;
  21231. read_file(SERVER_CERT_FILE, cert_pem);
  21232. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21233. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21234. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21235. ASSERT_TRUE(svr.is_valid());
  21236. // Now client CA list should be set
  21237. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21238. ASSERT_TRUE(ca_list_after != nullptr);
  21239. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21240. }
  21241. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21242. // Test that the file-path SSLServer constructor properly sets the client CA
  21243. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21244. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21245. ASSERT_TRUE(svr.is_valid());
  21246. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21247. ASSERT_TRUE(ssl_ctx != nullptr);
  21248. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21249. ASSERT_TRUE(ca_list != nullptr);
  21250. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21251. }
  21252. #endif
  21253. // ============================================================================
  21254. // MbedTLS-Specific Tests
  21255. // ============================================================================
  21256. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21257. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21258. using namespace httplib::tls;
  21259. // Track if callback was invoked
  21260. bool callback_invoked = false;
  21261. // The callback receives void* ctx which is actually MbedTlsContext*
  21262. // We can access the mbedtls_ssl_config via the context
  21263. auto setup_callback = [&callback_invoked](void *ctx) {
  21264. callback_invoked = true;
  21265. // Cast to MbedTlsContext* to access the ssl config
  21266. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21267. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21268. // Use static variables to hold certificate data (simplified for test)
  21269. static mbedtls_x509_crt own_cert;
  21270. static mbedtls_pk_context own_key;
  21271. static mbedtls_x509_crt ca_chain;
  21272. static bool initialized = false;
  21273. if (!initialized) {
  21274. mbedtls_x509_crt_init(&own_cert);
  21275. mbedtls_pk_init(&own_key);
  21276. mbedtls_x509_crt_init(&ca_chain);
  21277. // Load server certificate
  21278. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21279. return false;
  21280. }
  21281. // Load server private key.
  21282. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21283. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21284. #if MBEDTLS_VERSION_MAJOR == 3
  21285. ,
  21286. mbedtls_ctr_drbg_random, nullptr
  21287. #endif
  21288. ) != 0) {
  21289. return false;
  21290. }
  21291. // Load CA chain for client verification
  21292. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21293. return false;
  21294. }
  21295. initialized = true;
  21296. }
  21297. // Configure the SSL config
  21298. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21299. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21300. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21301. // Set minimum TLS version using mbedTLS native API
  21302. #if MBEDTLS_VERSION_MAJOR >= 3
  21303. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21304. #else
  21305. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21306. MBEDTLS_SSL_MINOR_VERSION_3);
  21307. #endif
  21308. return true;
  21309. };
  21310. SSLServer svr(setup_callback);
  21311. ASSERT_TRUE(svr.is_valid());
  21312. ASSERT_TRUE(callback_invoked);
  21313. svr.Get("/test", [&](const Request &req, Response &res) {
  21314. res.set_content("test", "text/plain");
  21315. auto cert = req.peer_cert();
  21316. ASSERT_TRUE(static_cast<bool>(cert));
  21317. auto common_name = cert.subject_cn();
  21318. EXPECT_EQ("Common Name", common_name);
  21319. });
  21320. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21321. auto se = detail::scope_exit([&] {
  21322. svr.stop();
  21323. t.join();
  21324. ASSERT_FALSE(svr.is_running());
  21325. });
  21326. svr.wait_until_ready();
  21327. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21328. cli.enable_server_certificate_verification(false);
  21329. cli.set_connection_timeout(30);
  21330. auto res = cli.Get("/test");
  21331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21332. ASSERT_EQ(StatusCode::OK_200, res->status);
  21333. }
  21334. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21335. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21336. // keep-alive SSL session, which reads through that config in
  21337. // mbedtls_ssl_close_notify.
  21338. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21340. ASSERT_TRUE(svr.is_valid());
  21341. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21342. res.set_content("test", "text/plain");
  21343. });
  21344. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21345. auto se = detail::scope_exit([&] {
  21346. svr.stop();
  21347. t.join();
  21348. ASSERT_FALSE(svr.is_running());
  21349. });
  21350. svr.wait_until_ready();
  21351. {
  21352. SSLClient cli(HOST, PORT);
  21353. cli.enable_server_certificate_verification(false);
  21354. cli.set_keep_alive(true);
  21355. auto res = cli.Get("/test");
  21356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21357. ASSERT_EQ(StatusCode::OK_200, res->status);
  21358. // cli is destructed here with the keep-alive SSL session still open.
  21359. }
  21360. }
  21361. #endif
  21362. // WebSocket Tests
  21363. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21364. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21365. // defining the meaning of these bits has been negotiated.
  21366. auto make_frame = [](uint8_t first_byte) {
  21367. std::string frame;
  21368. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21369. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21370. frame += "Hello";
  21371. return frame;
  21372. };
  21373. // RSV1 set (0x40)
  21374. {
  21375. detail::BufferStream strm;
  21376. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21377. ws::Opcode opcode;
  21378. std::string payload;
  21379. bool fin;
  21380. EXPECT_EQ(
  21381. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21382. ws::impl::FrameRead::Fail);
  21383. }
  21384. // RSV2 set (0x20)
  21385. {
  21386. detail::BufferStream strm;
  21387. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21388. ws::Opcode opcode;
  21389. std::string payload;
  21390. bool fin;
  21391. EXPECT_EQ(
  21392. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21393. ws::impl::FrameRead::Fail);
  21394. }
  21395. // RSV3 set (0x10)
  21396. {
  21397. detail::BufferStream strm;
  21398. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21399. ws::Opcode opcode;
  21400. std::string payload;
  21401. bool fin;
  21402. EXPECT_EQ(
  21403. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21404. ws::impl::FrameRead::Fail);
  21405. }
  21406. // No RSV bits set - should succeed
  21407. {
  21408. detail::BufferStream strm;
  21409. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21410. ws::Opcode opcode;
  21411. std::string payload;
  21412. bool fin;
  21413. EXPECT_EQ(
  21414. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21415. ws::impl::FrameRead::Ok);
  21416. EXPECT_EQ(ws::Opcode::Text, opcode);
  21417. EXPECT_EQ("Hello", payload);
  21418. EXPECT_TRUE(fin);
  21419. }
  21420. }
  21421. TEST(WebSocketTest, ControlFrameValidation) {
  21422. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21423. // payload length <= 125.
  21424. // Ping with FIN=0 - must be rejected
  21425. {
  21426. detail::BufferStream strm;
  21427. std::string frame;
  21428. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21429. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21430. strm.write(frame.data(), frame.size());
  21431. ws::Opcode opcode;
  21432. std::string payload;
  21433. bool fin;
  21434. EXPECT_EQ(
  21435. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21436. ws::impl::FrameRead::Fail);
  21437. }
  21438. // Close with FIN=0 - must be rejected
  21439. {
  21440. detail::BufferStream strm;
  21441. std::string frame;
  21442. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21443. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21444. strm.write(frame.data(), frame.size());
  21445. ws::Opcode opcode;
  21446. std::string payload;
  21447. bool fin;
  21448. EXPECT_EQ(
  21449. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21450. ws::impl::FrameRead::Fail);
  21451. }
  21452. // Ping with payload_len=126 (extended length) - must be rejected
  21453. {
  21454. detail::BufferStream strm;
  21455. std::string frame;
  21456. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21457. frame += static_cast<char>(126); // payload_len=126 (>125)
  21458. frame += static_cast<char>(0x00); // extended length high byte
  21459. frame += static_cast<char>(126); // extended length low byte
  21460. frame += std::string(126, 'x');
  21461. strm.write(frame.data(), frame.size());
  21462. ws::Opcode opcode;
  21463. std::string payload;
  21464. bool fin;
  21465. EXPECT_EQ(
  21466. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21467. ws::impl::FrameRead::Fail);
  21468. }
  21469. // Ping with FIN=1 and payload_len=125 - should succeed
  21470. {
  21471. detail::BufferStream strm;
  21472. std::string frame;
  21473. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21474. frame += static_cast<char>(125); // payload_len=125
  21475. frame += std::string(125, 'x');
  21476. strm.write(frame.data(), frame.size());
  21477. ws::Opcode opcode;
  21478. std::string payload;
  21479. bool fin;
  21480. EXPECT_EQ(
  21481. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21482. ws::impl::FrameRead::Ok);
  21483. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21484. EXPECT_EQ(125u, payload.size());
  21485. EXPECT_TRUE(fin);
  21486. }
  21487. }
  21488. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21489. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21490. // length MUST be 0.
  21491. // MSB set - must be rejected
  21492. {
  21493. detail::BufferStream strm;
  21494. std::string frame;
  21495. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21496. frame += static_cast<char>(127); // 64-bit extended length
  21497. frame += static_cast<char>(0x80); // MSB set (invalid)
  21498. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21499. strm.write(frame.data(), frame.size());
  21500. ws::Opcode opcode;
  21501. std::string payload;
  21502. bool fin;
  21503. EXPECT_EQ(
  21504. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21505. ws::impl::FrameRead::Fail);
  21506. }
  21507. // MSB clear - should pass length parsing (will be rejected by max_len,
  21508. // but that's a different check; use a small length to verify)
  21509. {
  21510. detail::BufferStream strm;
  21511. std::string frame;
  21512. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21513. frame += static_cast<char>(127); // 64-bit extended length
  21514. frame += std::string(7, '\0'); // high bytes = 0
  21515. frame += static_cast<char>(0x03); // length = 3
  21516. frame += "abc";
  21517. strm.write(frame.data(), frame.size());
  21518. ws::Opcode opcode;
  21519. std::string payload;
  21520. bool fin;
  21521. EXPECT_EQ(
  21522. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21523. ws::impl::FrameRead::Ok);
  21524. EXPECT_EQ(ws::Opcode::Text, opcode);
  21525. EXPECT_EQ("abc", payload);
  21526. }
  21527. }
  21528. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21529. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21530. // Valid UTF-8
  21531. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21532. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21533. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21534. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21535. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21536. // Invalid UTF-8
  21537. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21538. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21539. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21540. EXPECT_FALSE(
  21541. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21542. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21543. }
  21544. TEST(WebSocketTest, ConnectAndDisconnect) {
  21545. Server svr;
  21546. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21547. std::string msg;
  21548. while (ws.read(msg)) {}
  21549. });
  21550. auto port = svr.bind_to_any_port(HOST);
  21551. std::thread t([&]() { svr.listen_after_bind(); });
  21552. svr.wait_until_ready();
  21553. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21554. auto res = client.connect();
  21555. ASSERT_TRUE(res);
  21556. EXPECT_EQ(Error::Success, res.error());
  21557. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21558. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21559. EXPECT_TRUE(client.is_open());
  21560. client.close();
  21561. EXPECT_FALSE(client.is_open());
  21562. svr.stop();
  21563. t.join();
  21564. }
  21565. TEST(WebSocketTest, ValidURL) {
  21566. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21567. EXPECT_TRUE(ws1.is_valid());
  21568. ws::WebSocketClient ws2("ws://example.com/path");
  21569. EXPECT_TRUE(ws2.is_valid());
  21570. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21571. EXPECT_TRUE(ws3.is_valid());
  21572. #ifdef CPPHTTPLIB_SSL_ENABLED
  21573. ws::WebSocketClient wss1("wss://example.com/path");
  21574. EXPECT_TRUE(wss1.is_valid());
  21575. ws::WebSocketClient wss2("wss://example.com:443/path");
  21576. EXPECT_TRUE(wss2.is_valid());
  21577. #endif
  21578. }
  21579. TEST(WebSocketTest, InvalidURL) {
  21580. // No scheme
  21581. ws::WebSocketClient ws1("localhost:8080/path");
  21582. EXPECT_FALSE(ws1.is_valid());
  21583. // No path
  21584. ws::WebSocketClient ws2("ws://localhost:8080");
  21585. EXPECT_FALSE(ws2.is_valid());
  21586. // Empty string
  21587. ws::WebSocketClient ws3("");
  21588. EXPECT_FALSE(ws3.is_valid());
  21589. // Missing host
  21590. ws::WebSocketClient ws4("ws://:8080/path");
  21591. EXPECT_FALSE(ws4.is_valid());
  21592. // Port number overflow — should not crash
  21593. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21594. EXPECT_FALSE(ws5.is_valid());
  21595. // Port out of range
  21596. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21597. EXPECT_FALSE(ws6.is_valid());
  21598. }
  21599. TEST(WebSocketTest, UnsupportedScheme) {
  21600. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21601. ws::WebSocketClient ws1("http://localhost:8080/path");
  21602. EXPECT_FALSE(ws1.is_valid());
  21603. ws::WebSocketClient ws2("https://localhost:8080/path");
  21604. EXPECT_FALSE(ws2.is_valid());
  21605. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21606. EXPECT_FALSE(ws3.is_valid());
  21607. #else
  21608. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21609. std::invalid_argument);
  21610. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21611. std::invalid_argument);
  21612. #endif
  21613. }
  21614. TEST(WebSocketTest, ConnectWhenInvalid) {
  21615. ws::WebSocketClient ws("not a valid url");
  21616. EXPECT_FALSE(ws.is_valid());
  21617. auto res = ws.connect();
  21618. EXPECT_FALSE(res);
  21619. EXPECT_EQ(Error::Connection, res.error());
  21620. EXPECT_EQ(-1, res.status());
  21621. }
  21622. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21623. // Grab a port that is free, then close it again so nothing listens there
  21624. Server svr;
  21625. auto port = svr.bind_to_any_port(HOST);
  21626. svr.stop();
  21627. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21628. auto res = client.connect();
  21629. ASSERT_FALSE(res);
  21630. EXPECT_EQ(Error::Connection, res.error());
  21631. EXPECT_EQ(-1, res.status());
  21632. }
  21633. TEST(WebSocketTest, DefaultPort) {
  21634. ws::WebSocketClient ws1("ws://example.com/path");
  21635. EXPECT_TRUE(ws1.is_valid());
  21636. // ws:// defaults to port 80 (verified by successful parse)
  21637. #ifdef CPPHTTPLIB_SSL_ENABLED
  21638. ws::WebSocketClient ws2("wss://example.com/path");
  21639. EXPECT_TRUE(ws2.is_valid());
  21640. // wss:// defaults to port 443 (verified by successful parse)
  21641. #endif
  21642. }
  21643. TEST(WebSocketTest, IPv6LiteralAddress) {
  21644. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21645. EXPECT_TRUE(ws1.is_valid());
  21646. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21647. EXPECT_TRUE(ws2.is_valid());
  21648. }
  21649. TEST(WebSocketTest, ComplexPath) {
  21650. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21651. EXPECT_TRUE(ws1.is_valid());
  21652. ws::WebSocketClient ws2("ws://localhost:8080/");
  21653. EXPECT_TRUE(ws2.is_valid());
  21654. }
  21655. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21656. Server svr;
  21657. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21658. std::string msg;
  21659. while (ws.read(msg)) {}
  21660. });
  21661. auto port = svr.bind_to_any_port(HOST);
  21662. std::thread t([&]() { svr.listen_after_bind(); });
  21663. svr.wait_until_ready();
  21664. auto another_host = "example.com";
  21665. auto wrong_ip = "192.0.2.1";
  21666. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21667. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21668. ASSERT_TRUE(client.connect());
  21669. EXPECT_TRUE(client.is_open());
  21670. client.close();
  21671. svr.stop();
  21672. t.join();
  21673. }
  21674. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21675. Server svr;
  21676. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21677. std::string msg;
  21678. while (ws.read(msg)) {}
  21679. });
  21680. auto port = svr.bind_to_any_port(HOST);
  21681. std::thread t([&]() { svr.listen_after_bind(); });
  21682. svr.wait_until_ready();
  21683. auto wrong_ip = "192.0.2.1";
  21684. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21685. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21686. client.set_connection_timeout(1);
  21687. client.set_read_timeout(1);
  21688. client.set_write_timeout(1);
  21689. EXPECT_FALSE(client.connect());
  21690. EXPECT_FALSE(client.is_open());
  21691. svr.stop();
  21692. t.join();
  21693. }
  21694. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21695. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21696. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21697. // (RFC 6761) is only a map key and the Host header value.
  21698. auto host = "target.invalid";
  21699. Server svr;
  21700. std::string received_host;
  21701. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21702. received_host = req.get_header_value("Host");
  21703. std::string msg;
  21704. while (ws.read(msg)) {}
  21705. });
  21706. auto port = svr.bind_to_any_port(HOST);
  21707. std::thread t([&]() { svr.listen_after_bind(); });
  21708. // ASSERT_* below returns from the test body, which would leave t joinable
  21709. // and make ~thread call std::terminate.
  21710. auto se = detail::scope_exit([&] {
  21711. svr.stop();
  21712. if (t.joinable()) { t.join(); }
  21713. });
  21714. svr.wait_until_ready();
  21715. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21716. std::to_string(port) + "/ws");
  21717. client.set_hostname_addr_map({{host, HOST}});
  21718. ASSERT_TRUE(client.connect());
  21719. EXPECT_TRUE(client.is_open());
  21720. client.close();
  21721. svr.stop();
  21722. t.join();
  21723. // The mapping only redirects the connection; the identity stays host_.
  21724. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21725. }
  21726. class WebSocketIntegrationTest : public ::testing::Test {
  21727. protected:
  21728. void SetUp() override {
  21729. server_ = httplib::detail::make_unique<Server>();
  21730. setup_server();
  21731. start_server();
  21732. }
  21733. void TearDown() override {
  21734. server_->stop();
  21735. if (server_thread_.joinable()) { server_thread_.join(); }
  21736. }
  21737. void setup_server() {
  21738. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21739. std::string msg;
  21740. ws::ReadResult ret;
  21741. while ((ret = ws.read(msg))) {
  21742. if (ret == ws::Binary) {
  21743. ws.send(msg.data(), msg.size());
  21744. } else {
  21745. ws.send(msg);
  21746. }
  21747. }
  21748. });
  21749. server_->WebSocket("/ws-echo-string",
  21750. [](const Request &, ws::WebSocket &ws) {
  21751. std::string msg;
  21752. while (ws.read(msg)) {
  21753. ws.send("echo: " + msg);
  21754. }
  21755. });
  21756. server_->WebSocket(
  21757. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21758. // Echo back request metadata
  21759. ws.send("path:" + req.path);
  21760. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21761. std::string msg;
  21762. while (ws.read(msg)) {}
  21763. });
  21764. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21765. std::string msg;
  21766. ws.read(msg); // wait for a message
  21767. ws.close();
  21768. });
  21769. server_->WebSocket("/ws-close-status",
  21770. [](const Request &, ws::WebSocket &ws) {
  21771. std::string msg;
  21772. ws.read(msg); // wait for a message
  21773. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21774. });
  21775. server_->WebSocket(
  21776. "/ws-subprotocol",
  21777. [](const Request &, ws::WebSocket &ws) {
  21778. std::string msg;
  21779. while (ws.read(msg)) {
  21780. ws.send(msg);
  21781. }
  21782. },
  21783. [](const std::vector<std::string> &protocols) -> std::string {
  21784. for (const auto &p : protocols) {
  21785. if (p == "graphql-ws") { return p; }
  21786. }
  21787. return "";
  21788. });
  21789. server_->WebSocket(
  21790. "/ws-subprotocol-unoffered",
  21791. [](const Request &, ws::WebSocket &ws) {
  21792. std::string msg;
  21793. while (ws.read(msg)) {
  21794. ws.send(msg);
  21795. }
  21796. },
  21797. [](const std::vector<std::string> &) -> std::string {
  21798. return "admin";
  21799. });
  21800. }
  21801. void start_server() {
  21802. port_ = server_->bind_to_any_port(HOST);
  21803. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21804. server_->wait_until_ready();
  21805. }
  21806. std::unique_ptr<Server> server_;
  21807. std::thread server_thread_;
  21808. int port_ = 0;
  21809. };
  21810. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21811. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21812. "/ws-echo");
  21813. ASSERT_TRUE(client.connect());
  21814. ASSERT_TRUE(client.is_open());
  21815. ASSERT_TRUE(client.send("Hello WebSocket"));
  21816. std::string msg;
  21817. EXPECT_EQ(ws::Text, client.read(msg));
  21818. EXPECT_EQ("Hello WebSocket", msg);
  21819. client.close();
  21820. }
  21821. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21822. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21823. "/ws-echo");
  21824. ASSERT_TRUE(client.connect());
  21825. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21826. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21827. std::string msg;
  21828. EXPECT_EQ(ws::Binary, client.read(msg));
  21829. EXPECT_EQ(binary_data, msg);
  21830. client.close();
  21831. }
  21832. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21833. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21834. "/ws-echo");
  21835. ASSERT_TRUE(client.connect());
  21836. for (int i = 0; i < 10; i++) {
  21837. auto text = "message " + std::to_string(i);
  21838. ASSERT_TRUE(client.send(text));
  21839. std::string msg;
  21840. ASSERT_TRUE(client.read(msg));
  21841. EXPECT_EQ(text, msg);
  21842. }
  21843. client.close();
  21844. }
  21845. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21846. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21847. "/ws-close");
  21848. ASSERT_TRUE(client.connect());
  21849. // Send a message to trigger the server to close
  21850. ASSERT_TRUE(client.send("trigger close"));
  21851. // The server will close, so read should return false
  21852. std::string msg;
  21853. EXPECT_FALSE(client.read(msg));
  21854. EXPECT_FALSE(client.is_open());
  21855. }
  21856. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21857. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21858. "/ws-echo");
  21859. ASSERT_TRUE(client.connect());
  21860. // 128KB message
  21861. std::string large_data(128 * 1024, 'X');
  21862. ASSERT_TRUE(client.send(large_data));
  21863. std::string msg;
  21864. ASSERT_TRUE(client.read(msg));
  21865. EXPECT_EQ(large_data, msg);
  21866. client.close();
  21867. }
  21868. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21869. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21870. "/ws-echo");
  21871. ASSERT_TRUE(client.connect());
  21872. const int num_threads = 4;
  21873. std::vector<std::thread> threads;
  21874. std::atomic<int> send_count{0};
  21875. for (int t = 0; t < num_threads; t++) {
  21876. threads.emplace_back([&client, &send_count, t]() {
  21877. for (int i = 0; i < 5; i++) {
  21878. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21879. if (client.send(text)) { send_count++; }
  21880. }
  21881. });
  21882. }
  21883. for (auto &th : threads) {
  21884. th.join();
  21885. }
  21886. int received = 0;
  21887. std::string msg;
  21888. while (received < send_count.load()) {
  21889. if (!client.read(msg)) { break; }
  21890. received++;
  21891. }
  21892. EXPECT_EQ(send_count.load(), received);
  21893. client.close();
  21894. }
  21895. TEST_F(WebSocketIntegrationTest, ReadString) {
  21896. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21897. "/ws-echo-string");
  21898. ASSERT_TRUE(client.connect());
  21899. ASSERT_TRUE(client.send("hello"));
  21900. std::string msg;
  21901. ASSERT_TRUE(client.read(msg));
  21902. EXPECT_EQ("echo: hello", msg);
  21903. ASSERT_TRUE(client.send("world"));
  21904. ASSERT_TRUE(client.read(msg));
  21905. EXPECT_EQ("echo: world", msg);
  21906. client.close();
  21907. }
  21908. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21909. Headers headers = {{"X-Test-Header", "test-value"}};
  21910. ws::WebSocketClient client(
  21911. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21912. ASSERT_TRUE(client.connect());
  21913. std::string msg;
  21914. ASSERT_TRUE(client.read(msg));
  21915. EXPECT_EQ("path:/ws-request-info", msg);
  21916. ASSERT_TRUE(client.read(msg));
  21917. EXPECT_EQ("header:test-value", msg);
  21918. client.close();
  21919. }
  21920. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21921. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21922. "/ws-echo");
  21923. client.set_read_timeout(1, 0); // 1 second
  21924. ASSERT_TRUE(client.connect());
  21925. // Don't send anything — server echo handler waits for a message, so read()
  21926. // should time out. The connection survives it: nothing was consumed.
  21927. std::string msg;
  21928. EXPECT_EQ(client.read(msg), ws::Timeout);
  21929. EXPECT_TRUE(client.is_open());
  21930. // And it is still usable afterwards.
  21931. EXPECT_TRUE(client.send("after timeout"));
  21932. EXPECT_EQ(client.read(msg), ws::Text);
  21933. EXPECT_EQ(msg, "after timeout");
  21934. }
  21935. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21936. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21937. "/ws-echo");
  21938. client.set_read_timeout(1, 0);
  21939. ASSERT_TRUE(client.connect());
  21940. ASSERT_TRUE(client.send("first"));
  21941. std::string msg;
  21942. ASSERT_EQ(client.read(msg), ws::Text);
  21943. ASSERT_EQ(msg, "first");
  21944. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21945. // not be used with a read timeout: it would reprocess the previous message.
  21946. EXPECT_EQ(client.read(msg), ws::Timeout);
  21947. EXPECT_EQ(msg, "first");
  21948. }
  21949. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21950. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21951. "/ws-echo");
  21952. ASSERT_TRUE(client.connect());
  21953. // Setting it once the connection is open reaches the live stream, not just
  21954. // the seed for the next connect().
  21955. client.set_read_timeout(1, 0);
  21956. std::string msg;
  21957. EXPECT_EQ(client.read(msg), ws::Timeout);
  21958. EXPECT_TRUE(client.is_open());
  21959. }
  21960. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21961. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21962. "/ws-echo");
  21963. client.set_read_timeout(5, 0);
  21964. ASSERT_TRUE(client.connect());
  21965. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21966. // The server should reject it and close the connection.
  21967. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21968. client.send(oversized);
  21969. // The server's read() should have failed due to payload limit,
  21970. // so our read() should return false (connection closed).
  21971. std::string msg;
  21972. EXPECT_FALSE(client.read(msg));
  21973. }
  21974. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21975. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21976. "/ws-echo");
  21977. client.set_read_timeout(10, 0);
  21978. ASSERT_TRUE(client.connect());
  21979. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21980. // This should succeed.
  21981. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21982. ASSERT_TRUE(client.send(at_limit));
  21983. std::string msg;
  21984. ASSERT_TRUE(client.read(msg));
  21985. EXPECT_EQ(at_limit.size(), msg.size());
  21986. client.close();
  21987. }
  21988. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21989. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21990. "/nonexistent");
  21991. auto res = client.connect();
  21992. EXPECT_FALSE(res);
  21993. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21994. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21995. EXPECT_FALSE(client.is_open());
  21996. }
  21997. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21998. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21999. "/ws-echo");
  22000. ASSERT_TRUE(client.connect());
  22001. ASSERT_TRUE(client.send(""));
  22002. std::string msg;
  22003. EXPECT_EQ(ws::Text, client.read(msg));
  22004. EXPECT_EQ("", msg);
  22005. client.close();
  22006. }
  22007. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22008. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22009. "/ws-echo");
  22010. // First connection
  22011. ASSERT_TRUE(client.connect());
  22012. ASSERT_TRUE(client.send("first"));
  22013. std::string msg;
  22014. ASSERT_TRUE(client.read(msg));
  22015. EXPECT_EQ("first", msg);
  22016. client.close();
  22017. EXPECT_FALSE(client.is_open());
  22018. // Reconnect using the same client object
  22019. ASSERT_TRUE(client.connect());
  22020. ASSERT_TRUE(client.is_open());
  22021. ASSERT_TRUE(client.send("second"));
  22022. ASSERT_TRUE(client.read(msg));
  22023. EXPECT_EQ("second", msg);
  22024. client.close();
  22025. }
  22026. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22027. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22028. "/ws-close-status");
  22029. ASSERT_TRUE(client.connect());
  22030. // Trigger the server to close with GoingAway status
  22031. ASSERT_TRUE(client.send("trigger"));
  22032. // read() should return false after receiving the close frame
  22033. std::string msg;
  22034. EXPECT_FALSE(client.read(msg));
  22035. EXPECT_FALSE(client.is_open());
  22036. }
  22037. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22039. "/ws-echo");
  22040. ASSERT_TRUE(client.connect());
  22041. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22042. EXPECT_FALSE(client.is_open());
  22043. }
  22044. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22045. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22046. ws::WebSocketClient client(
  22047. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22048. ASSERT_TRUE(client.connect());
  22049. // Server should have selected graphql-ws
  22050. EXPECT_EQ("graphql-ws", client.subprotocol());
  22051. client.close();
  22052. }
  22053. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22054. Headers headers;
  22055. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22056. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22057. ws::WebSocketClient client(
  22058. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22059. ASSERT_TRUE(client.connect());
  22060. // The offer on the second field line counts too, so graphql-ws is selected
  22061. EXPECT_EQ("graphql-ws", client.subprotocol());
  22062. client.close();
  22063. }
  22064. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22065. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22066. ws::WebSocketClient client(
  22067. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22068. ASSERT_TRUE(client.connect());
  22069. // Server should not have selected any subprotocol
  22070. EXPECT_TRUE(client.subprotocol().empty());
  22071. client.close();
  22072. }
  22073. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22074. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22075. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22076. "/ws-subprotocol-unoffered",
  22077. headers);
  22078. ASSERT_TRUE(client.connect());
  22079. EXPECT_TRUE(client.subprotocol().empty());
  22080. client.close();
  22081. }
  22082. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22083. // Connect without requesting any subprotocol
  22084. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22085. "/ws-subprotocol");
  22086. ASSERT_TRUE(client.connect());
  22087. EXPECT_TRUE(client.subprotocol().empty());
  22088. client.close();
  22089. }
  22090. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22091. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22092. "/ws-echo");
  22093. client.set_tcp_nodelay(true);
  22094. client.set_connection_timeout(3, 0);
  22095. bool socket_options_called = false;
  22096. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22097. ASSERT_TRUE(client.connect());
  22098. ASSERT_TRUE(client.is_open());
  22099. EXPECT_TRUE(socket_options_called);
  22100. ASSERT_TRUE(client.send("hello"));
  22101. std::string msg;
  22102. auto result = client.read(msg);
  22103. EXPECT_EQ(result, ws::ReadResult::Text);
  22104. EXPECT_EQ(msg, "hello");
  22105. client.close();
  22106. }
  22107. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22108. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22109. "/ws-echo");
  22110. client.set_connection_timeout(std::chrono::seconds(3));
  22111. client.set_write_timeout(std::chrono::seconds(3));
  22112. // A sub-second remainder exercises the seconds/microseconds split.
  22113. client.set_read_timeout(std::chrono::milliseconds(1500));
  22114. ASSERT_TRUE(client.connect());
  22115. auto start = std::chrono::steady_clock::now();
  22116. std::string msg;
  22117. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22118. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22119. std::chrono::steady_clock::now() - start)
  22120. .count();
  22121. // Above 1s so that dropping the microseconds half of the split fails here.
  22122. // Ignoring the setter altogether would not reach this line at all: a client
  22123. // waits forever by default.
  22124. EXPECT_GE(elapsed, 1400);
  22125. EXPECT_LT(elapsed, 30000);
  22126. }
  22127. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22128. Server svr;
  22129. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22130. if (!req.has_header("Authorization")) {
  22131. res.status = StatusCode::Unauthorized_401;
  22132. res.set_content("Unauthorized", "text/plain");
  22133. return Server::HandlerResponse::Handled;
  22134. }
  22135. return Server::HandlerResponse::Unhandled;
  22136. });
  22137. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22138. std::string msg;
  22139. while (ws.read(msg)) {
  22140. ws.send(msg);
  22141. }
  22142. });
  22143. auto port = svr.bind_to_any_port("localhost");
  22144. std::thread t([&]() { svr.listen_after_bind(); });
  22145. svr.wait_until_ready();
  22146. // Without Authorization header - should be rejected before upgrade
  22147. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22148. EXPECT_FALSE(client1.connect());
  22149. // The rejection is framed like any other HTTP response
  22150. {
  22151. Client cli("localhost", port);
  22152. Headers headers = {{"Upgrade", "websocket"},
  22153. {"Connection", "Upgrade"},
  22154. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22155. {"Sec-WebSocket-Version", "13"}};
  22156. auto res = cli.Get("/ws", headers);
  22157. ASSERT_TRUE(res);
  22158. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22159. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22160. EXPECT_EQ("Unauthorized", res->body);
  22161. }
  22162. // With Authorization header - should succeed
  22163. Headers headers = {{"Authorization", "Bearer token123"}};
  22164. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22165. headers);
  22166. ASSERT_TRUE(client2.connect());
  22167. ASSERT_TRUE(client2.send("hello"));
  22168. std::string msg;
  22169. ASSERT_TRUE(client2.read(msg));
  22170. EXPECT_EQ("hello", msg);
  22171. client2.close();
  22172. svr.stop();
  22173. t.join();
  22174. }
  22175. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22176. Server svr;
  22177. std::atomic<int> pre_request_calls{0};
  22178. std::atomic<bool> route_matched{false};
  22179. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22180. pre_request_calls++;
  22181. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22182. if (req.get_header_value("Authorization") != "Bearer token123") {
  22183. res.status = StatusCode::Unauthorized_401;
  22184. res.set_content("Unauthorized", "text/plain");
  22185. return Server::HandlerResponse::Handled;
  22186. }
  22187. return Server::HandlerResponse::Unhandled;
  22188. });
  22189. std::atomic<bool> handler_called{false};
  22190. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22191. handler_called = true;
  22192. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22193. });
  22194. auto port = svr.bind_to_any_port("localhost");
  22195. std::thread t([&]() { svr.listen_after_bind(); });
  22196. svr.wait_until_ready();
  22197. // Without Authorization header - should be rejected before upgrade
  22198. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22199. "/ws/1");
  22200. EXPECT_FALSE(client1.connect());
  22201. EXPECT_FALSE(handler_called);
  22202. EXPECT_EQ(1, pre_request_calls);
  22203. EXPECT_TRUE(route_matched);
  22204. // The rejection is an ordinary HTTP response, not a protocol switch
  22205. {
  22206. Client cli("localhost", port);
  22207. Headers headers = {{"Upgrade", "websocket"},
  22208. {"Connection", "Upgrade"},
  22209. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22210. {"Sec-WebSocket-Version", "13"}};
  22211. auto res = cli.Get("/ws/1", headers);
  22212. ASSERT_TRUE(res);
  22213. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22214. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22215. EXPECT_EQ("Unauthorized", res->body);
  22216. }
  22217. EXPECT_FALSE(handler_called);
  22218. // With Authorization header - should succeed
  22219. Headers headers = {{"Authorization", "Bearer token123"}};
  22220. ws::WebSocketClient client2(
  22221. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22222. ASSERT_TRUE(client2.connect());
  22223. std::string msg;
  22224. ASSERT_TRUE(client2.read(msg));
  22225. EXPECT_EQ("/ws/:id 2", msg);
  22226. EXPECT_TRUE(handler_called);
  22227. client2.close();
  22228. svr.stop();
  22229. t.join();
  22230. }
  22231. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22232. Server svr;
  22233. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22234. // A read timeout is how a handler gets control back. Without it, a handler
  22235. // parked in read() can never write on the connection it is reading.
  22236. ws.set_read_timeout(std::chrono::milliseconds(100));
  22237. std::string msg;
  22238. while (ws.is_open()) {
  22239. auto r = ws.read(msg);
  22240. if (r == httplib::ws::Timeout) {
  22241. ws.send("tick");
  22242. continue;
  22243. }
  22244. if (r == httplib::ws::Fail) { break; }
  22245. ws.send(msg);
  22246. }
  22247. });
  22248. auto port = svr.bind_to_any_port("localhost");
  22249. std::thread t([&]() { svr.listen_after_bind(); });
  22250. svr.wait_until_ready();
  22251. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22252. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22253. ASSERT_TRUE(client.connect());
  22254. // The client sends nothing, so anything it receives came out of the
  22255. // handler's timeout path.
  22256. std::string msg;
  22257. ASSERT_EQ(client.read(msg), ws::Text);
  22258. EXPECT_EQ("tick", msg);
  22259. client.close();
  22260. svr.stop();
  22261. t.join();
  22262. }
  22263. // Stream::read may return fewer bytes than asked for. This is that contract at
  22264. // its worst -- one byte per call -- which is what a frame header straddling a
  22265. // read buffer's boundary looks like to the frame parser.
  22266. class WsByteAtATimeStream : public Stream {
  22267. public:
  22268. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22269. bool is_readable() const override { return true; }
  22270. bool wait_readable() const override { return true; }
  22271. bool wait_writable() const override { return true; }
  22272. ssize_t read(char *ptr, size_t size) override {
  22273. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22274. *ptr = data_[pos_++];
  22275. return 1;
  22276. }
  22277. ssize_t write(const char *, size_t size) override {
  22278. return static_cast<ssize_t>(size);
  22279. }
  22280. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22281. ip = "127.0.0.1";
  22282. port = 0;
  22283. }
  22284. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22285. ip = "127.0.0.1";
  22286. port = 0;
  22287. }
  22288. socket_t socket() const override { return INVALID_SOCKET; }
  22289. time_t duration() const override { return 0; }
  22290. private:
  22291. std::string data_;
  22292. size_t pos_ = 0;
  22293. };
  22294. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22295. // The payload uses the 16-bit extended length, so the header, the length
  22296. // and the mask key are all multi-byte fields here. Each used to be read
  22297. // with a single read() call, which fails as soon as one is split. The
  22298. // payload is also a little over one read chunk, so it is read in two.
  22299. std::string body;
  22300. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22301. body += static_cast<char>(i % 251);
  22302. }
  22303. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22304. std::string frame;
  22305. frame += static_cast<char>(0x81); // FIN + Text
  22306. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22307. frame += static_cast<char>(body.size() >> 8);
  22308. frame += static_cast<char>(body.size() & 0xff);
  22309. for (size_t i = 0; i < 4; i++) {
  22310. frame += static_cast<char>(mask[i]);
  22311. }
  22312. for (size_t i = 0; i < body.size(); i++) {
  22313. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22314. }
  22315. WsByteAtATimeStream strm(frame);
  22316. ws::Opcode opcode;
  22317. std::string payload;
  22318. bool fin = false;
  22319. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22320. /*expect_masked=*/true, body.size()),
  22321. ws::impl::FrameRead::Ok);
  22322. EXPECT_TRUE(fin);
  22323. EXPECT_EQ(opcode, ws::Opcode::Text);
  22324. EXPECT_EQ(payload, body);
  22325. }
  22326. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22327. std::string body(2000, 'x');
  22328. std::string frame;
  22329. frame += static_cast<char>(0x82); // FIN + Binary
  22330. frame += static_cast<char>(126); // 16-bit length follows
  22331. frame += static_cast<char>(body.size() >> 8);
  22332. frame += static_cast<char>(body.size() & 0xff);
  22333. frame += body;
  22334. detail::BufferStream strm;
  22335. strm.write(frame.data(), frame.size());
  22336. ws::Opcode opcode;
  22337. std::string payload;
  22338. bool fin;
  22339. EXPECT_EQ(
  22340. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22341. ws::impl::FrameRead::Ok);
  22342. EXPECT_EQ(body, payload);
  22343. }
  22344. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22345. // The header announces the largest payload allowed, and only 3 bytes of it
  22346. // ever arrive.
  22347. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22348. std::string frame;
  22349. frame += static_cast<char>(0x82); // FIN + Binary
  22350. frame += static_cast<char>(127); // 64-bit length follows
  22351. for (int shift = 56; shift >= 0; shift -= 8) {
  22352. frame += static_cast<char>((len >> shift) & 0xff);
  22353. }
  22354. frame += "abc";
  22355. detail::BufferStream strm;
  22356. strm.write(frame.data(), frame.size());
  22357. ws::Opcode opcode;
  22358. std::string payload;
  22359. bool fin;
  22360. EXPECT_EQ(
  22361. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22362. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22363. ws::impl::FrameRead::Fail);
  22364. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22365. }
  22366. TEST(WebSocketTest, QueryStringInHandshake) {
  22367. Server svr;
  22368. std::mutex mtx;
  22369. std::string received_target;
  22370. std::string received_token;
  22371. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22372. {
  22373. std::lock_guard<std::mutex> lock(mtx);
  22374. received_target = req.target;
  22375. if (req.has_param("token")) {
  22376. received_token = req.get_param_value("token");
  22377. }
  22378. }
  22379. std::string msg;
  22380. while (ws.read(msg)) {
  22381. ws.send(msg);
  22382. }
  22383. });
  22384. auto port = svr.bind_to_any_port("localhost");
  22385. std::thread t([&]() { svr.listen_after_bind(); });
  22386. svr.wait_until_ready();
  22387. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22388. "/ws?token=ABC&session=123");
  22389. ASSERT_TRUE(client.connect());
  22390. // Round-trip ensures the handler has run and captured the request.
  22391. ASSERT_TRUE(client.send("hello"));
  22392. std::string msg;
  22393. ASSERT_TRUE(client.read(msg));
  22394. EXPECT_EQ("hello", msg);
  22395. client.close();
  22396. {
  22397. std::lock_guard<std::mutex> lock(mtx);
  22398. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22399. EXPECT_EQ("ABC", received_token);
  22400. }
  22401. svr.stop();
  22402. t.join();
  22403. }
  22404. // Run a handshake against a throwaway server and hand the request the server
  22405. // received back to the caller, so tests can assert on the headers the client
  22406. // actually put on the wire.
  22407. static void capture_websocket_handshake_request(
  22408. const Headers &client_headers,
  22409. std::function<void(const Request &, int port)> verify) {
  22410. Server svr;
  22411. std::mutex mtx;
  22412. Request received;
  22413. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22414. {
  22415. std::lock_guard<std::mutex> lock(mtx);
  22416. received = req;
  22417. }
  22418. std::string msg;
  22419. while (ws.read(msg)) {
  22420. ws.send(msg);
  22421. }
  22422. });
  22423. auto port = svr.bind_to_any_port("localhost");
  22424. std::thread t([&]() { svr.listen_after_bind(); });
  22425. auto se = detail::scope_exit([&] {
  22426. svr.stop();
  22427. t.join();
  22428. });
  22429. svr.wait_until_ready();
  22430. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22431. client_headers);
  22432. ASSERT_TRUE(client.connect());
  22433. ASSERT_TRUE(client.send("hello"));
  22434. std::string msg;
  22435. ASSERT_TRUE(client.read(msg));
  22436. client.close();
  22437. {
  22438. std::lock_guard<std::mutex> lock(mtx);
  22439. verify(received, port);
  22440. }
  22441. }
  22442. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22443. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22444. // Non-default port must be present in the Host header. Default ports
  22445. // (80/443) are omitted; that logic is covered by
  22446. // MakeHostAndPortStringTest.
  22447. EXPECT_EQ("localhost:" + std::to_string(port),
  22448. req.get_header_value("Host"));
  22449. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22450. req.get_header_value("User-Agent"));
  22451. EXPECT_FALSE(req.has_header("Accept"));
  22452. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22453. EXPECT_FALSE(req.has_header("Content-Length"));
  22454. });
  22455. }
  22456. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22457. capture_websocket_handshake_request(
  22458. {{"Host", "example.com"},
  22459. {"User-Agent", "custom-agent"},
  22460. {"X-Custom", "value"}},
  22461. [](const Request &req, int) {
  22462. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22463. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22464. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22465. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22466. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22467. });
  22468. }
  22469. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22470. capture_websocket_handshake_request(
  22471. {{"Upgrade", "bogus"},
  22472. {"Connection", "close"},
  22473. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22474. {"Sec-WebSocket-Version", "8"}},
  22475. [](const Request &req, int) {
  22476. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22477. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22478. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22479. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22480. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22481. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22482. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22483. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22484. req.get_header_value("Sec-WebSocket-Key"));
  22485. });
  22486. }
  22487. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22488. // A header the client refuses to send must abort the handshake before any
  22489. // part of it reaches the wire; a lone request line would otherwise sit in
  22490. // the peer's buffer as a truncated request.
  22491. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22492. ASSERT_NE(INVALID_SOCKET, srv);
  22493. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22494. sockaddr_in addr{};
  22495. addr.sin_family = AF_INET;
  22496. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22497. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22498. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22499. ASSERT_EQ(0, ::listen(srv, 1));
  22500. sockaddr_in bound{};
  22501. socklen_t bound_len = sizeof(bound);
  22502. ASSERT_EQ(
  22503. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22504. auto port = ntohs(bound.sin_port);
  22505. ssize_t received = -1;
  22506. std::thread t([&] {
  22507. // Bound every blocking call so a regression fails the test with a bad
  22508. // value instead of hanging the suite.
  22509. fd_set rfds;
  22510. FD_ZERO(&rfds);
  22511. FD_SET(srv, &rfds);
  22512. timeval tv{5, 0};
  22513. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22514. 0) {
  22515. return;
  22516. }
  22517. sockaddr_in cli_addr{};
  22518. socklen_t cli_len = sizeof(cli_addr);
  22519. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22520. if (cli == INVALID_SOCKET) { return; }
  22521. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22522. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22523. char buf[4096];
  22524. received = ::recv(cli, buf, sizeof(buf), 0);
  22525. });
  22526. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22527. // connect() has already shut the socket down by the time it returns false,
  22528. // so the peer sees EOF without waiting for the client to be destroyed.
  22529. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22530. {{"X-Bad", "a\r\nInjected: 1"}});
  22531. EXPECT_FALSE(client.connect());
  22532. t.join();
  22533. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22534. EXPECT_EQ(0, received);
  22535. }
  22536. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22537. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22538. // contains "upgrade" as a substring is a different token and must not
  22539. // start a WebSocket handshake.
  22540. auto make_request = [](const std::vector<std::string> &connection_values) {
  22541. Request req;
  22542. req.method = "GET";
  22543. req.headers.emplace("Upgrade", "websocket");
  22544. for (const auto &value : connection_values) {
  22545. req.headers.emplace("Connection", value);
  22546. }
  22547. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22548. req.headers.emplace("Sec-WebSocket-Version", "13");
  22549. return req;
  22550. };
  22551. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22552. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22553. EXPECT_TRUE(
  22554. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22555. EXPECT_TRUE(
  22556. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22557. EXPECT_TRUE(
  22558. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22559. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22560. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22561. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22562. EXPECT_FALSE(
  22563. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22564. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22565. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22566. }
  22567. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22568. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22569. // asks recipients to match each protocol-name case-insensitively, and RFC
  22570. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22571. // client naming websocket alongside another protocol, or on a second field
  22572. // line, is offering websocket; a value that merely contains "websocket" as a
  22573. // substring is a different protocol name and is not.
  22574. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22575. Request req;
  22576. req.method = "GET";
  22577. for (const auto &value : upgrade_values) {
  22578. req.headers.emplace("Upgrade", value);
  22579. }
  22580. req.headers.emplace("Connection", "Upgrade");
  22581. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22582. req.headers.emplace("Sec-WebSocket-Version", "13");
  22583. return req;
  22584. };
  22585. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22586. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22587. EXPECT_TRUE(
  22588. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22589. EXPECT_TRUE(
  22590. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22591. EXPECT_TRUE(
  22592. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22593. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22594. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22595. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22596. EXPECT_FALSE(
  22597. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22598. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22599. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22600. }
  22601. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22602. Server svr;
  22603. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22604. auto port = svr.bind_to_any_port("localhost");
  22605. std::thread t([&]() { svr.listen_after_bind(); });
  22606. auto se = detail::scope_exit([&] {
  22607. svr.stop();
  22608. t.join();
  22609. });
  22610. svr.wait_until_ready();
  22611. Headers headers = {{"Upgrade", "websocket"},
  22612. {"Connection", "notupgrade"},
  22613. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22614. {"Sec-WebSocket-Version", "13"}};
  22615. Client cli("localhost", port);
  22616. auto res = cli.Get("/ws", headers);
  22617. // The route exists only as a WebSocket route, so a request that fails the
  22618. // handshake check falls through to ordinary routing.
  22619. ASSERT_TRUE(res);
  22620. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22621. }
  22622. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22623. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22624. // Connection value is the only thing left for the client to reject.
  22625. Server svr;
  22626. svr.Get("/ws", [](const Request &req, Response &res) {
  22627. res.status = StatusCode::SwitchingProtocol_101;
  22628. res.set_header("Upgrade", "websocket");
  22629. res.set_header("Connection", "notupgrade");
  22630. res.set_header("Sec-WebSocket-Accept",
  22631. detail::websocket_accept_key(
  22632. req.get_header_value("Sec-WebSocket-Key")));
  22633. });
  22634. auto port = svr.bind_to_any_port("localhost");
  22635. std::thread t([&]() { svr.listen_after_bind(); });
  22636. auto se = detail::scope_exit([&] {
  22637. svr.stop();
  22638. t.join();
  22639. });
  22640. svr.wait_until_ready();
  22641. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22642. auto res = client.connect();
  22643. EXPECT_FALSE(res);
  22644. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22645. EXPECT_FALSE(client.is_open());
  22646. }
  22647. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22648. Server svr;
  22649. svr.Get("/ws", [](const Request &req, Response &res) {
  22650. res.status = StatusCode::SwitchingProtocol_101;
  22651. res.set_header("Upgrade", "websocket");
  22652. res.set_header("Connection", "Upgrade");
  22653. res.set_header("Sec-WebSocket-Accept",
  22654. detail::websocket_accept_key(
  22655. req.get_header_value("Sec-WebSocket-Key")));
  22656. res.set_header("Sec-WebSocket-Protocol", "admin");
  22657. });
  22658. auto port = svr.bind_to_any_port("localhost");
  22659. std::thread t([&]() { svr.listen_after_bind(); });
  22660. auto se = detail::scope_exit([&] {
  22661. svr.stop();
  22662. t.join();
  22663. });
  22664. svr.wait_until_ready();
  22665. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22666. // Server selects a subprotocol the client never offered
  22667. {
  22668. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22669. ws::WebSocketClient client(url, headers);
  22670. auto res = client.connect();
  22671. EXPECT_FALSE(res);
  22672. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22673. EXPECT_FALSE(client.is_open());
  22674. EXPECT_TRUE(client.subprotocol().empty());
  22675. }
  22676. // Client offered none but the server named one anyway
  22677. {
  22678. ws::WebSocketClient client(url);
  22679. auto res = client.connect();
  22680. EXPECT_FALSE(res);
  22681. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22682. EXPECT_FALSE(client.is_open());
  22683. EXPECT_TRUE(client.subprotocol().empty());
  22684. }
  22685. }
  22686. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22687. // The socket path doubles as the URL host, so it must not contain '/'.
  22688. const char *shard = getenv("GTEST_SHARD_INDEX");
  22689. const std::string sock_path =
  22690. shard ? std::string("httplib-ws-") + shard + ".sock"
  22691. : std::string("httplib-ws.sock");
  22692. std::remove(sock_path.c_str());
  22693. Server svr;
  22694. std::mutex mtx;
  22695. std::string received_host;
  22696. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22697. {
  22698. std::lock_guard<std::mutex> lock(mtx);
  22699. received_host = req.get_header_value("Host");
  22700. }
  22701. std::string msg;
  22702. while (ws.read(msg)) {
  22703. ws.send(msg);
  22704. }
  22705. });
  22706. svr.set_address_family(AF_UNIX);
  22707. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22708. auto se = detail::scope_exit([&] {
  22709. svr.stop();
  22710. t.join();
  22711. std::remove(sock_path.c_str());
  22712. });
  22713. svr.wait_until_ready();
  22714. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22715. client.set_address_family(AF_UNIX);
  22716. ASSERT_TRUE(client.connect());
  22717. ASSERT_TRUE(client.send("hello"));
  22718. std::string msg;
  22719. ASSERT_TRUE(client.read(msg));
  22720. client.close();
  22721. {
  22722. std::lock_guard<std::mutex> lock(mtx);
  22723. // There is no host:port for a Unix socket, so the same "localhost"
  22724. // placeholder the HTTP client uses is expected.
  22725. EXPECT_EQ("localhost", received_host);
  22726. }
  22727. }
  22728. // Two threads must never parse WebSocket frames from the same stream.
  22729. // close() used to read the peer's Close reply with its own frame read, so it
  22730. // raced a reader thread that was in the middle of a payload: the payload loop
  22731. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22732. // so bytes taken by close() were replaced with bytes from further along the
  22733. // stream. The message kept its length and silently changed content.
  22734. //
  22735. // The raw peer below sends a frame header plus part of the payload, waits for
  22736. // the handler to call close(), and only then sends the rest. Whichever thread
  22737. // would win the race for those bytes, the message must arrive intact, because
  22738. // close() must not touch the stream while read() owns it.
  22739. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22740. #ifndef _WIN32
  22741. signal(SIGPIPE, SIG_IGN);
  22742. #endif
  22743. const size_t payload_len = 120; // fits the 7-bit length field
  22744. const size_t prefix_len = 8;
  22745. const int attempts = 8;
  22746. std::string expected(payload_len, '\0');
  22747. for (size_t i = 0; i < payload_len; i++) {
  22748. expected[i] = static_cast<char>('a' + i % 26);
  22749. }
  22750. std::atomic<bool> peer_stalled{false};
  22751. std::atomic<bool> handler_done{false};
  22752. std::mutex received_mutex;
  22753. std::vector<std::string> received;
  22754. // Bound every wait, so a regression fails the test instead of hanging the
  22755. // suite.
  22756. auto wait_for = [](const std::atomic<bool> &flag) {
  22757. for (int i = 0; i < 500 && !flag; i++) {
  22758. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22759. }
  22760. };
  22761. Server svr;
  22762. svr.set_websocket_ping_interval(0);
  22763. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22764. std::thread reader([&]() {
  22765. std::string msg;
  22766. while (ws.read(msg)) {
  22767. std::lock_guard<std::mutex> guard(received_mutex);
  22768. received.push_back(msg);
  22769. }
  22770. });
  22771. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22772. // inside read_websocket_frame() when close() runs.
  22773. wait_for(peer_stalled);
  22774. ws.close();
  22775. reader.join();
  22776. handler_done = true;
  22777. });
  22778. auto port = svr.bind_to_any_port("127.0.0.1");
  22779. std::thread t([&]() { svr.listen_after_bind(); });
  22780. auto se = detail::scope_exit([&] {
  22781. svr.stop();
  22782. t.join();
  22783. });
  22784. svr.wait_until_ready();
  22785. auto send_bytes = [](socket_t s, const std::string &data) {
  22786. #ifdef _WIN32
  22787. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22788. #else
  22789. auto n = ::send(s, data.data(), data.size(), 0);
  22790. #endif
  22791. return n == static_cast<decltype(n)>(data.size());
  22792. };
  22793. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22794. // Every length used here fits the 7-bit length field.
  22795. auto masked_header = [](uint8_t first_byte, size_t len) {
  22796. std::string h;
  22797. h += static_cast<char>(first_byte);
  22798. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22799. h.append(4, '\0'); // mask key
  22800. return h;
  22801. };
  22802. for (int attempt = 0; attempt < attempts; attempt++) {
  22803. peer_stalled = false;
  22804. handler_done = false;
  22805. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22806. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22807. auto se_sock = detail::scope_exit([&] {
  22808. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22809. });
  22810. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22811. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22812. sockaddr_in addr{};
  22813. addr.sin_family = AF_INET;
  22814. addr.sin_port = htons(static_cast<uint16_t>(port));
  22815. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22816. ASSERT_EQ(
  22817. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22818. << "attempt " << attempt;
  22819. ASSERT_TRUE(send_bytes(sock,
  22820. "GET /ws HTTP/1.1\r\n"
  22821. "Host: 127.0.0.1\r\n"
  22822. "Upgrade: websocket\r\n"
  22823. "Connection: Upgrade\r\n"
  22824. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22825. "Sec-WebSocket-Version: 13\r\n"
  22826. "\r\n"))
  22827. << "attempt " << attempt;
  22828. std::string response;
  22829. while (response.find("\r\n\r\n") == std::string::npos) {
  22830. char buf[512];
  22831. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22832. if (n <= 0) { break; }
  22833. response.append(buf, static_cast<size_t>(n));
  22834. }
  22835. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22836. << "attempt " << attempt;
  22837. // Send the header of a Binary message but only the first prefix_len bytes
  22838. // of its payload, leaving the reader thread stalled inside the payload.
  22839. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22840. expected.substr(0, prefix_len)))
  22841. << "attempt " << attempt;
  22842. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22843. peer_stalled = true;
  22844. // Let close() send its Close frame and park in its own read before the
  22845. // rest of the payload arrives, so both threads are waiting for it.
  22846. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22847. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22848. close_frame += static_cast<char>(0x03); // status 1000
  22849. close_frame += static_cast<char>(0xE8);
  22850. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22851. << "attempt " << attempt;
  22852. // Closing the peer releases the reader thread even on the buggy path,
  22853. // where it waits for bytes another thread already consumed.
  22854. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22855. detail::close_socket(sock);
  22856. sock = INVALID_SOCKET;
  22857. wait_for(handler_done);
  22858. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22859. }
  22860. std::lock_guard<std::mutex> guard(received_mutex);
  22861. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22862. << "a message in flight when close() ran was dropped";
  22863. for (size_t i = 0; i < received.size(); i++) {
  22864. EXPECT_EQ(expected, received[i]) << "message " << i;
  22865. }
  22866. }
  22867. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  22868. // returning the socket, or INVALID_SOCKET.
  22869. static socket_t connect_raw_websocket(int port, const std::string &path) {
  22870. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22871. if (sock == INVALID_SOCKET) { return sock; }
  22872. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22873. sockaddr_in addr{};
  22874. addr.sin_family = AF_INET;
  22875. addr.sin_port = htons(static_cast<uint16_t>(port));
  22876. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22877. std::string req = "GET " + path +
  22878. " HTTP/1.1\r\n"
  22879. "Host: 127.0.0.1\r\n"
  22880. "Upgrade: websocket\r\n"
  22881. "Connection: Upgrade\r\n"
  22882. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22883. "Sec-WebSocket-Version: 13\r\n"
  22884. "\r\n";
  22885. std::string res;
  22886. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  22887. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  22888. static_cast<int>(req.size())) {
  22889. char c;
  22890. while (res.find("\r\n\r\n") == std::string::npos &&
  22891. ::recv(sock, &c, 1, 0) == 1) {
  22892. res += c;
  22893. }
  22894. }
  22895. if (res.find(" 101 ") == std::string::npos) {
  22896. detail::close_socket(sock);
  22897. return INVALID_SOCKET;
  22898. }
  22899. return sock;
  22900. }
  22901. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  22902. // The payload must fit the 7-bit length field.
  22903. static std::string masked_frame(uint8_t first_byte,
  22904. const std::string &payload) {
  22905. std::string f;
  22906. f += static_cast<char>(first_byte);
  22907. f += static_cast<char>(0x80 | payload.size());
  22908. f.append(4, '\0');
  22909. return f + payload;
  22910. }
  22911. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22912. std::atomic<bool> done{false};
  22913. std::string received;
  22914. Server svr;
  22915. svr.set_websocket_ping_interval(0);
  22916. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22917. std::string msg;
  22918. if (ws.read(msg) == ws::Binary) { received = msg; }
  22919. done = true;
  22920. });
  22921. auto port = svr.bind_to_any_port("127.0.0.1");
  22922. std::thread t([&]() { svr.listen_after_bind(); });
  22923. auto se = detail::scope_exit([&] {
  22924. svr.stop();
  22925. t.join();
  22926. });
  22927. svr.wait_until_ready();
  22928. auto sock = connect_raw_websocket(port, "/ws");
  22929. ASSERT_NE(INVALID_SOCKET, sock);
  22930. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22931. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  22932. masked_frame(0x89, "p") + // FIN + Ping
  22933. masked_frame(0x80, "lo"); // FIN + Continuation
  22934. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  22935. for (int i = 0; i < 500 && !done; i++) {
  22936. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22937. }
  22938. ASSERT_TRUE(done);
  22939. EXPECT_EQ("Hello", received);
  22940. }
  22941. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  22942. Server svr;
  22943. svr.set_websocket_ping_interval(0);
  22944. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22945. std::string msg;
  22946. while (ws.read(msg)) {}
  22947. });
  22948. auto port = svr.bind_to_any_port("127.0.0.1");
  22949. std::thread t([&]() { svr.listen_after_bind(); });
  22950. auto se = detail::scope_exit([&] {
  22951. svr.stop();
  22952. t.join();
  22953. });
  22954. svr.wait_until_ready();
  22955. // Each Close payload and the reply it should get: an echo when valid, 1002
  22956. // otherwise.
  22957. std::vector<std::pair<std::string, std::string>> cases = {
  22958. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  22959. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  22960. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  22961. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  22962. };
  22963. for (const auto &c : cases) {
  22964. auto sock = connect_raw_websocket(port, "/ws");
  22965. ASSERT_NE(INVALID_SOCKET, sock);
  22966. auto close_frame = masked_frame(0x88, c.first);
  22967. ::send(sock, close_frame.data(), static_cast<int>(close_frame.size()), 0);
  22968. std::string reply;
  22969. char buf[256];
  22970. while (reply.size() < 2 + c.second.size()) {
  22971. auto n = ::recv(sock, buf, sizeof(buf), 0);
  22972. if (n <= 0) { break; }
  22973. reply.append(buf, static_cast<size_t>(n));
  22974. }
  22975. detail::close_socket(sock);
  22976. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  22977. c.second,
  22978. reply);
  22979. }
  22980. }
  22981. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22982. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22983. protected:
  22984. void SetUp() override {
  22985. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22986. SERVER_PRIVATE_KEY_FILE);
  22987. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22988. std::string msg;
  22989. ws::ReadResult ret;
  22990. while ((ret = ws.read(msg))) {
  22991. if (ret == ws::Binary) {
  22992. ws.send(msg.data(), msg.size());
  22993. } else {
  22994. ws.send(msg);
  22995. }
  22996. }
  22997. });
  22998. port_ = server_->bind_to_any_port(HOST);
  22999. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23000. server_->wait_until_ready();
  23001. }
  23002. void TearDown() override {
  23003. server_->stop();
  23004. if (server_thread_.joinable()) { server_thread_.join(); }
  23005. }
  23006. std::unique_ptr<SSLServer> server_;
  23007. std::thread server_thread_;
  23008. int port_ = 0;
  23009. };
  23010. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23011. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23012. {
  23013. ws::WebSocketClient client(url);
  23014. client.enable_server_certificate_verification(false);
  23015. auto calls = 0;
  23016. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23017. calls++;
  23018. return false;
  23019. });
  23020. EXPECT_FALSE(client.connect());
  23021. EXPECT_GT(calls, 0);
  23022. }
  23023. {
  23024. ws::WebSocketClient client(url);
  23025. client.enable_server_certificate_verification(false);
  23026. client.set_session_verifier([](tls::session_t) {
  23027. return SSLVerifierResponse::CertificateRejected;
  23028. });
  23029. EXPECT_FALSE(client.connect());
  23030. }
  23031. {
  23032. ws::WebSocketClient client(url);
  23033. client.enable_server_certificate_verification(false);
  23034. client.set_session_verifier([](tls::session_t) {
  23035. return SSLVerifierResponse::CertificateAccepted;
  23036. });
  23037. EXPECT_TRUE(client.connect());
  23038. }
  23039. }
  23040. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23041. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23042. "/ws-echo");
  23043. client.enable_server_certificate_verification(false);
  23044. ASSERT_TRUE(client.connect());
  23045. ASSERT_TRUE(client.is_open());
  23046. ASSERT_TRUE(client.send("Hello WSS"));
  23047. std::string msg;
  23048. EXPECT_EQ(ws::Text, client.read(msg));
  23049. EXPECT_EQ("Hello WSS", msg);
  23050. client.close();
  23051. }
  23052. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23053. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23054. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23055. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23056. // client (without calling close() first) is the only path that runs
  23057. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23058. // bug exactly.
  23059. //
  23060. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23061. // when linked against an instrumented libssl; run under Valgrind to catch it
  23062. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23063. // suite (the freed session otherwise stalls on the close handshake) — this test
  23064. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23065. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23066. {
  23067. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23068. "/ws-echo");
  23069. client.enable_server_certificate_verification(false);
  23070. client.set_read_timeout(2, 0);
  23071. client.set_write_timeout(2, 0);
  23072. ASSERT_TRUE(client.connect());
  23073. ASSERT_TRUE(client.is_open());
  23074. ASSERT_TRUE(client.send("still open"));
  23075. // Intentionally do NOT call client.close(): leaving scope runs
  23076. // shutdown_and_close() with the WebSocket still open, which must send the
  23077. // close frame while the TLS session is still alive.
  23078. }
  23079. }
  23080. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23081. // shutdown_and_close() at the start of connect(), reproducing the same
  23082. // use-after-free within the test body rather than at scope exit. The second
  23083. // connect must succeed and echo, proving the close handshake ran over a live
  23084. // session. See the note above about memory-tool requirements.
  23085. TEST_F(WebSocketSSLIntegrationTest,
  23086. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23087. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23088. "/ws-echo");
  23089. client.enable_server_certificate_verification(false);
  23090. client.set_read_timeout(2, 0);
  23091. client.set_write_timeout(2, 0);
  23092. ASSERT_TRUE(client.connect());
  23093. ASSERT_TRUE(client.is_open());
  23094. ASSERT_TRUE(client.send("still open"));
  23095. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23096. // the still-open connection, which must not touch a freed TLS session.
  23097. ASSERT_TRUE(client.connect());
  23098. ASSERT_TRUE(client.is_open());
  23099. ASSERT_TRUE(client.send("after reconnect"));
  23100. std::string msg;
  23101. EXPECT_EQ(ws::Text, client.read(msg));
  23102. EXPECT_EQ("after reconnect", msg);
  23103. client.close();
  23104. }
  23105. #endif
  23106. #ifdef CPPHTTPLIB_SSL_ENABLED
  23107. class WebSocketSSLCATest : public ::testing::Test {
  23108. protected:
  23109. void SetUp() override {
  23110. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23111. SERVER_PRIVATE_KEY_FILE);
  23112. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23113. std::string msg;
  23114. while (ws.read(msg)) {
  23115. ws.send(msg);
  23116. }
  23117. });
  23118. port_ = server_->bind_to_any_port("127.0.0.1");
  23119. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23120. server_->wait_until_ready();
  23121. }
  23122. void TearDown() override {
  23123. server_->stop();
  23124. if (server_thread_.joinable()) { server_thread_.join(); }
  23125. }
  23126. std::string url() const {
  23127. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23128. }
  23129. std::unique_ptr<SSLServer> server_;
  23130. std::thread server_thread_;
  23131. int port_ = 0;
  23132. };
  23133. // A custom CA loaded as PEM verifies the server with full certificate
  23134. // verification enabled
  23135. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23136. ws::WebSocketClient client(url());
  23137. std::string cert;
  23138. read_file(SERVER_CERT2_FILE, cert);
  23139. client.load_ca_cert_store(cert.c_str(), cert.size());
  23140. ASSERT_TRUE(client.connect());
  23141. ASSERT_TRUE(client.send("hello"));
  23142. std::string msg;
  23143. EXPECT_EQ(ws::Text, client.read(msg));
  23144. EXPECT_EQ("hello", msg);
  23145. client.close();
  23146. }
  23147. // A custom CA that does not cover the server must fail verification (the
  23148. // custom CA is exclusive; system certs are not loaded alongside it)
  23149. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23150. ws::WebSocketClient client(url());
  23151. std::string cert;
  23152. read_file(CLIENT_CA_CERT_FILE, cert);
  23153. client.load_ca_cert_store(cert.c_str(), cert.size());
  23154. auto res = client.connect();
  23155. ASSERT_FALSE(res);
  23156. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23157. EXPECT_EQ(-1, res.status());
  23158. EXPECT_NE(0u, res.ssl_backend_error());
  23159. }
  23160. // The same CA as a file path rather than PEM in memory
  23161. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23162. ws::WebSocketClient client(url());
  23163. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23164. ASSERT_TRUE(client.connect());
  23165. ASSERT_TRUE(client.send("hello"));
  23166. std::string msg;
  23167. EXPECT_EQ(ws::Text, client.read(msg));
  23168. EXPECT_EQ("hello", msg);
  23169. client.close();
  23170. }
  23171. // ...and a CA file that does not cover the server still fails, so it is the
  23172. // path above that decides the outcome
  23173. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23174. ws::WebSocketClient client(url());
  23175. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23176. ASSERT_FALSE(client.connect());
  23177. }
  23178. // Regression test: reconnecting with a native custom CA store used to reuse
  23179. // a store handle the previous TLS context had already freed (use-after-free
  23180. // under the OpenSSL backend). The context now lives as long as the client.
  23181. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23182. ws::WebSocketClient client(url());
  23183. std::string cert;
  23184. read_file(SERVER_CERT2_FILE, cert);
  23185. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23186. ASSERT_TRUE(client.connect());
  23187. client.close();
  23188. ASSERT_TRUE(client.connect());
  23189. ASSERT_TRUE(client.send("again"));
  23190. std::string msg;
  23191. EXPECT_EQ(ws::Text, client.read(msg));
  23192. EXPECT_EQ("again", msg);
  23193. client.close();
  23194. }
  23195. // Regression test: a certificate with a trusted chain but no identity match
  23196. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23197. // verification entirely for IP hosts, so this connection succeeded there.
  23198. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23199. // chain verification while the identity check must still fail.
  23200. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23202. ASSERT_TRUE(svr.is_valid());
  23203. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23204. std::string msg;
  23205. while (ws.read(msg)) {
  23206. ws.send(msg);
  23207. }
  23208. });
  23209. auto port = svr.bind_to_any_port("127.0.0.1");
  23210. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23211. auto se = detail::scope_exit([&] {
  23212. svr.stop();
  23213. t.join();
  23214. });
  23215. svr.wait_until_ready();
  23216. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23217. "/echo");
  23218. std::string cert;
  23219. read_file(SERVER_CERT_FILE, cert);
  23220. client.load_ca_cert_store(cert.c_str(), cert.size());
  23221. ASSERT_FALSE(client.connect());
  23222. }
  23223. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23224. // SNI, so nothing binds the host name to the TLS session. These bind the
  23225. // server to "localhost" instead, the only shape that exercises the SNI and
  23226. // hostname-verification path with certificate verification left enabled.
  23227. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23228. protected:
  23229. void Start(const char *cert_file) {
  23230. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23231. SERVER_PRIVATE_KEY_FILE);
  23232. ASSERT_TRUE(server_->is_valid());
  23233. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23234. std::string msg;
  23235. while (ws.read(msg)) {
  23236. ws.send(msg);
  23237. }
  23238. });
  23239. port_ = server_->bind_to_any_port("localhost");
  23240. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23241. server_->wait_until_ready();
  23242. }
  23243. void TearDown() override {
  23244. if (server_) { server_->stop(); }
  23245. if (server_thread_.joinable()) { server_thread_.join(); }
  23246. }
  23247. std::string url() const {
  23248. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23249. }
  23250. std::unique_ptr<SSLServer> server_;
  23251. std::thread server_thread_;
  23252. int port_ = 0;
  23253. };
  23254. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23255. // out and the connection is usable
  23256. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23257. Start(SERVER_CERT2_FILE);
  23258. ws::WebSocketClient client(url());
  23259. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23260. ASSERT_TRUE(client.connect());
  23261. ASSERT_TRUE(client.send("hello"));
  23262. std::string msg;
  23263. EXPECT_EQ(ws::Text, client.read(msg));
  23264. EXPECT_EQ("hello", msg);
  23265. client.close();
  23266. }
  23267. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23268. // while the identity check must still reject "localhost"
  23269. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23270. Start(SERVER_CERT_FILE);
  23271. ws::WebSocketClient client(url());
  23272. client.set_ca_cert_path(SERVER_CERT_FILE);
  23273. auto res = client.connect();
  23274. ASSERT_FALSE(res);
  23275. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23276. EXPECT_EQ(-1, res.status());
  23277. }
  23278. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23279. // disabled: the chain is still checked, only the identity check is skipped
  23280. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23281. Start(SERVER_CERT_FILE);
  23282. ws::WebSocketClient client(url());
  23283. client.set_ca_cert_path(SERVER_CERT_FILE);
  23284. client.enable_server_hostname_verification(false);
  23285. ASSERT_TRUE(client.connect());
  23286. ASSERT_TRUE(client.send("hello"));
  23287. std::string msg;
  23288. EXPECT_EQ(ws::Text, client.read(msg));
  23289. EXPECT_EQ("hello", msg);
  23290. client.close();
  23291. }
  23292. // A CA that did not sign the server certificate fails the chain, even though
  23293. // the name would match
  23294. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23295. Start(SERVER_CERT2_FILE);
  23296. ws::WebSocketClient client(url());
  23297. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23298. ASSERT_FALSE(client.connect());
  23299. }
  23300. // With verification disabled, neither the chain nor the name is checked
  23301. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23302. Start(SERVER_CERT_FILE);
  23303. ws::WebSocketClient client(url());
  23304. client.enable_server_certificate_verification(false);
  23305. ASSERT_TRUE(client.connect());
  23306. ASSERT_TRUE(client.send("hello"));
  23307. std::string msg;
  23308. EXPECT_EQ(ws::Text, client.read(msg));
  23309. EXPECT_EQ("hello", msg);
  23310. client.close();
  23311. }
  23312. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23313. protected:
  23314. void SetUp() override {
  23315. server_ = httplib::detail::make_unique<SSLServer>(
  23316. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23317. ASSERT_TRUE(server_->is_valid());
  23318. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23319. std::string msg;
  23320. while (ws.read(msg)) {
  23321. ws.send(msg);
  23322. }
  23323. });
  23324. port_ = server_->bind_to_any_port("localhost");
  23325. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23326. server_->wait_until_ready();
  23327. }
  23328. void TearDown() override {
  23329. server_->stop();
  23330. if (server_thread_.joinable()) { server_thread_.join(); }
  23331. }
  23332. std::string url() const {
  23333. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23334. }
  23335. void ConnectWithClientCert(const std::string &client_cert_file,
  23336. const std::string &client_private_key_file,
  23337. const char *private_key_password) {
  23338. std::string cert_pem, key_pem;
  23339. read_file(client_cert_file, cert_pem);
  23340. read_file(client_private_key_file, key_pem);
  23341. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23342. key_pem.c_str(), key_pem.size(),
  23343. private_key_password};
  23344. ws::WebSocketClient client(url(), pem);
  23345. ASSERT_TRUE(client.is_valid());
  23346. client.enable_server_certificate_verification(false);
  23347. ASSERT_TRUE(client.connect());
  23348. ASSERT_TRUE(client.send("hello"));
  23349. std::string msg;
  23350. EXPECT_EQ(ws::Text, client.read(msg));
  23351. EXPECT_EQ("hello", msg);
  23352. client.close();
  23353. }
  23354. std::unique_ptr<SSLServer> server_;
  23355. std::thread server_thread_;
  23356. int port_ = 0;
  23357. };
  23358. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23359. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23360. }
  23361. // Control for the tests above: the fixture's server really does require a
  23362. // client certificate, so it is the PEM the constructor installed that decides
  23363. // the outcome.
  23364. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23365. ws::WebSocketClient client(url());
  23366. ASSERT_TRUE(client.is_valid());
  23367. client.enable_server_certificate_verification(false);
  23368. EXPECT_FALSE(client.connect());
  23369. }
  23370. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23371. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23372. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23373. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23374. }
  23375. #endif
  23376. #if !defined(_WIN32)
  23377. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23378. auto secret_dir = std::string("./symlink_test_secret");
  23379. auto served_dir = std::string("./symlink_test_served");
  23380. auto secret_file = secret_dir + "/secret.txt";
  23381. auto symlink_path = served_dir + "/escape";
  23382. // Setup: create directories and files
  23383. mkdir(secret_dir.c_str(), 0755);
  23384. mkdir(served_dir.c_str(), 0755);
  23385. {
  23386. std::ofstream ofs(secret_file);
  23387. ofs << "SECRET_DATA";
  23388. }
  23389. // Create symlink using absolute path so it resolves correctly
  23390. #ifdef PATH_MAX
  23391. char abs_secret[PATH_MAX];
  23392. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23393. #else
  23394. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23395. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23396. ASSERT_NE(nullptr, abs_secret);
  23397. #endif
  23398. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23399. auto se = detail::scope_exit([&] {
  23400. unlink(symlink_path.c_str());
  23401. unlink(secret_file.c_str());
  23402. rmdir(served_dir.c_str());
  23403. rmdir(secret_dir.c_str());
  23404. });
  23405. Server svr;
  23406. svr.set_mount_point("/", served_dir);
  23407. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23408. auto se2 = detail::scope_exit([&] {
  23409. svr.stop();
  23410. listen_thread.join();
  23411. });
  23412. svr.wait_until_ready();
  23413. Client cli("localhost", PORT);
  23414. // Symlink pointing outside base dir should be blocked
  23415. auto res = cli.Get("/escape/secret.txt");
  23416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23417. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23418. }
  23419. #endif
  23420. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23421. // "GET /smuggled" request), reads the first response, and only then sends the
  23422. // embedded request as the body. Returns how many times /smuggled ran.
  23423. //
  23424. // The body is sent AFTER receiving the first response (as in the original
  23425. // PoC) so that the stream_line_reader cannot buffer it together with the
  23426. // headers of the first request.
  23427. static int count_smuggled_requests(const std::string &outer_head,
  23428. std::string &first_response) {
  23429. Server svr;
  23430. svr.set_mount_point("/", "./www");
  23431. std::atomic<int> smuggled_count(0);
  23432. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23433. smuggled_count++;
  23434. res.set_content("oops", "text/plain");
  23435. });
  23436. svr.Post("/post", [&](const Request &req, Response &res) {
  23437. res.set_content(req.body, "text/plain");
  23438. });
  23439. auto port = svr.bind_to_any_port("localhost");
  23440. thread t = thread([&] { svr.listen_after_bind(); });
  23441. auto se = detail::scope_exit([&] {
  23442. svr.stop();
  23443. t.join();
  23444. });
  23445. svr.wait_until_ready();
  23446. auto error = Error::Success;
  23447. auto sock = detail::create_client_socket(
  23448. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23449. /*connection_timeout_sec=*/2, 0,
  23450. /*read_timeout_sec=*/2, 0,
  23451. /*write_timeout_sec=*/2, 0, std::string(), error);
  23452. EXPECT_NE(INVALID_SOCKET, sock);
  23453. if (sock == INVALID_SOCKET) { return -1; }
  23454. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23455. // The "smuggled" request will be sent as the body of the outer request
  23456. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23457. "Host: localhost\r\n"
  23458. "Connection: close\r\n"
  23459. "\r\n";
  23460. auto head = outer_head;
  23461. auto len = std::to_string(smuggled.size());
  23462. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23463. pos = head.find("{len}", pos + len.size())) {
  23464. head.replace(pos, 5, len);
  23465. }
  23466. // Step 1: Send only the outer request headers (no body yet)
  23467. auto sent = send(sock, head.data(), head.size(), 0);
  23468. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23469. // Step 2: Read the first response
  23470. char buf[4096];
  23471. for (;;) {
  23472. auto n = recv(sock, buf, sizeof(buf), 0);
  23473. if (n <= 0) break;
  23474. first_response.append(buf, static_cast<size_t>(n));
  23475. // Stop once we have a complete response (headers + body)
  23476. auto hdr_end = first_response.find("\r\n\r\n");
  23477. if (hdr_end != std::string::npos) {
  23478. // Check for Content-Length to know when the body is complete
  23479. auto cl_pos = first_response.find("Content-Length:");
  23480. if (cl_pos != std::string::npos) {
  23481. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23482. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23483. auto cl = std::stoul(
  23484. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23485. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23486. } else {
  23487. break; // No Content-Length, assume headers-only response
  23488. }
  23489. }
  23490. }
  23491. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23492. // vulnerable server the keep-alive loop reads this as a second request. The
  23493. // server may already have closed the connection, so the result is ignored.
  23494. send(sock, smuggled.data(), smuggled.size(), 0);
  23495. // Half-close so that a server which drained the body sees EOF and closes,
  23496. // instead of the read below waiting for the read timeout.
  23497. #ifdef _WIN32
  23498. ::shutdown(sock, SD_SEND);
  23499. #else
  23500. ::shutdown(sock, SHUT_WR);
  23501. #endif
  23502. // Step 4: Read until the server closes the connection
  23503. for (;;) {
  23504. auto n = recv(sock, buf, sizeof(buf), 0);
  23505. if (n <= 0) break;
  23506. }
  23507. return smuggled_count.load();
  23508. }
  23509. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23510. // A GET request with Content-Length to a static file handler must have its
  23511. // body drained before the keep-alive connection is reused. Otherwise the
  23512. // unread body bytes are interpreted as the next HTTP request.
  23513. std::string first_response;
  23514. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23515. "Host: localhost\r\n"
  23516. "Content-Length: {len}\r\n"
  23517. "\r\n",
  23518. first_response));
  23519. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23520. }
  23521. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23522. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23523. // be answered with 400 and the connection closed. Treating it as "no body"
  23524. // leaves the body to be parsed as the next request.
  23525. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23526. const char *targets[] = {
  23527. "GET /file", // handler that never reads the body
  23528. "GET /not-found", // no handler matches (404)
  23529. "POST /post", // handler that reads the body
  23530. };
  23531. for (auto target : targets) {
  23532. for (auto value : values) {
  23533. std::string first_response;
  23534. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23535. " HTTP/1.1\r\n"
  23536. "Host: localhost\r\n"
  23537. "Content-Length: " +
  23538. value + "\r\n\r\n",
  23539. first_response))
  23540. << target << " with Content-Length: " << value;
  23541. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23542. << target << " with Content-Length: " << value;
  23543. }
  23544. }
  23545. }
  23546. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23547. // A 400 for an unparseable request line leaves the rest of the message
  23548. // unread, so the connection must be closed rather than reused.
  23549. std::string first_response;
  23550. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23551. "Host: localhost\r\n"
  23552. "Content-Length: {len}\r\n"
  23553. "\r\n",
  23554. first_response));
  23555. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23556. }
  23557. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23558. // Same as above for a header block that fails to parse.
  23559. std::string first_response;
  23560. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23561. "Host: localhost\r\n"
  23562. "Bad Header\r\n"
  23563. "Content-Length: {len}\r\n"
  23564. "\r\n",
  23565. first_response));
  23566. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23567. }
  23568. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23569. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23570. // server must not read another request on that connection, even when the
  23571. // request had no body to drain.
  23572. std::string first_response;
  23573. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23574. "Host: localhost\r\n"
  23575. "\r\n",
  23576. first_response));
  23577. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23578. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23579. }
  23580. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23581. // A content reader that stops early leaves the stream inside the body.
  23582. // Draining the whole Content-Length from there, or reading the body again,
  23583. // reads into the next request, and whatever follows is parsed as a request
  23584. // of its own.
  23585. Server svr;
  23586. std::atomic<int> smuggled_count(0);
  23587. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23588. svr.Post("/upload", [](const Request &req, Response &res,
  23589. const ContentReader &content_reader) {
  23590. // Stop at the last chunk, so the whole body has been read however it
  23591. // arrives.
  23592. auto length = req.get_header_value_u64("Content-Length");
  23593. size_t total = 0;
  23594. auto consumed = content_reader([&](const char *, size_t n) {
  23595. total += n;
  23596. return total < length;
  23597. });
  23598. EXPECT_FALSE(consumed);
  23599. if (req.has_param("retry")) {
  23600. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23601. }
  23602. // Replace the 400 the aborted read set, which would close the connection.
  23603. res.set_redirect("/done");
  23604. });
  23605. auto port = svr.bind_to_any_port(HOST);
  23606. thread t = thread([&] { svr.listen_after_bind(); });
  23607. auto se = detail::scope_exit([&] {
  23608. svr.stop();
  23609. t.join();
  23610. });
  23611. svr.wait_until_ready();
  23612. // A front end sees the second request as a POST whose body is the GET. The
  23613. // first body is as long as the POST's headers, so draining it again reads
  23614. // exactly those and leaves the GET to be parsed next.
  23615. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23616. "Host: localhost\r\n"
  23617. "\r\n";
  23618. std::string second_head = "POST /post HTTP/1.1\r\n"
  23619. "Host: localhost\r\n"
  23620. "Content-Length: " +
  23621. std::to_string(inner.size()) +
  23622. "\r\n"
  23623. "\r\n";
  23624. for (auto target : {"/upload", "/upload?retry"}) {
  23625. smuggled_count = 0;
  23626. std::string request = "POST " + std::string(target) +
  23627. " HTTP/1.1\r\n"
  23628. "Host: localhost\r\n"
  23629. "Content-Length: " +
  23630. std::to_string(second_head.size()) +
  23631. "\r\n"
  23632. "\r\n" +
  23633. std::string(second_head.size(), 'A') + second_head +
  23634. inner;
  23635. std::string response;
  23636. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23637. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23638. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23639. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23640. EXPECT_EQ(0, smuggled_count.load()) << target;
  23641. }
  23642. }
  23643. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23644. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23645. // must be rejected with 400 Bad Request.
  23646. Server svr;
  23647. svr.Post("/test", [&](const Request &, Response &res) {
  23648. res.set_content("ok", "text/plain");
  23649. });
  23650. thread t = thread([&] { svr.listen(HOST, PORT); });
  23651. auto se = detail::scope_exit([&] {
  23652. svr.stop();
  23653. t.join();
  23654. ASSERT_FALSE(svr.is_running());
  23655. });
  23656. svr.wait_until_ready();
  23657. // Exact "chunked"
  23658. {
  23659. auto req = "POST /test HTTP/1.1\r\n"
  23660. "Host: localhost\r\n"
  23661. "Content-Length: 5\r\n"
  23662. "Transfer-Encoding: chunked\r\n"
  23663. "Connection: close\r\n"
  23664. "\r\n"
  23665. "hello";
  23666. std::string response;
  23667. ASSERT_TRUE(send_request(1, req, &response));
  23668. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23669. response.substr(0, response.find("\r\n")));
  23670. }
  23671. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23672. {
  23673. auto req = "POST /test HTTP/1.1\r\n"
  23674. "Host: localhost\r\n"
  23675. "Content-Length: 5\r\n"
  23676. "Transfer-Encoding: gzip, chunked\r\n"
  23677. "Connection: close\r\n"
  23678. "\r\n"
  23679. "hello";
  23680. std::string response;
  23681. ASSERT_TRUE(send_request(1, req, &response));
  23682. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23683. response.substr(0, response.find("\r\n")));
  23684. }
  23685. }
  23686. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23687. Server svr;
  23688. svr.Post("/test", [&](const Request &, Response &res) {
  23689. res.set_content("ok", "text/plain");
  23690. });
  23691. thread t = thread([&] { svr.listen(HOST, PORT); });
  23692. auto se = detail::scope_exit([&] {
  23693. svr.stop();
  23694. t.join();
  23695. ASSERT_FALSE(svr.is_running());
  23696. });
  23697. svr.wait_until_ready();
  23698. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23699. // length cannot be determined, so the server must answer 400 and close
  23700. // rather than treat the request as bodyless and leave the body in the
  23701. // socket for the next request to pick up.
  23702. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23703. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23704. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23705. std::string response;
  23706. ASSERT_TRUE(send_request(1, req, &response));
  23707. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23708. response.substr(0, response.find("\r\n")))
  23709. << transfer_encoding;
  23710. }
  23711. // RFC 9110 5.3: the codings may also be split across several
  23712. // Transfer-Encoding lines, which combine in the order they were received.
  23713. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23714. // just like the single-line "chunked, gzip" above.
  23715. {
  23716. auto req = "POST /test HTTP/1.1\r\n"
  23717. "Host: localhost\r\n"
  23718. "Transfer-Encoding: chunked\r\n"
  23719. "Transfer-Encoding: gzip\r\n"
  23720. "\r\n"
  23721. "0\r\n\r\n";
  23722. std::string response;
  23723. ASSERT_TRUE(send_request(1, req, &response));
  23724. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23725. response.substr(0, response.find("\r\n")));
  23726. }
  23727. // A sequence ending in chunked stays valid.
  23728. auto req = "POST /test HTTP/1.1\r\n"
  23729. "Host: localhost\r\n"
  23730. "Transfer-Encoding: gzip, chunked\r\n"
  23731. "Connection: close\r\n"
  23732. "\r\n"
  23733. "0\r\n\r\n";
  23734. std::string response;
  23735. ASSERT_TRUE(send_request(1, req, &response));
  23736. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23737. // ...including when it is spread over several lines.
  23738. auto split_req = "POST /test HTTP/1.1\r\n"
  23739. "Host: localhost\r\n"
  23740. "Transfer-Encoding: gzip\r\n"
  23741. "Transfer-Encoding: chunked\r\n"
  23742. "Connection: close\r\n"
  23743. "\r\n"
  23744. "0\r\n\r\n";
  23745. std::string split_response;
  23746. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23747. EXPECT_EQ("HTTP/1.1 200 OK",
  23748. split_response.substr(0, split_response.find("\r\n")));
  23749. }
  23750. // Regression for issue #2450: a DELETE without Content-Length on a
  23751. // keep-alive connection must not let the post-response drain consume the
  23752. // next request's bytes.
  23753. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23754. Server svr;
  23755. std::atomic<int> delete_count(0);
  23756. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23757. delete_count++;
  23758. res.status = StatusCode::NoContent_204;
  23759. });
  23760. auto port = svr.bind_to_any_port(HOST);
  23761. thread t = thread([&] { svr.listen_after_bind(); });
  23762. auto se = detail::scope_exit([&] {
  23763. svr.stop();
  23764. t.join();
  23765. });
  23766. svr.wait_until_ready();
  23767. auto error = Error::Success;
  23768. auto sock = detail::create_client_socket(
  23769. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23770. /*connection_timeout_sec=*/2, 0,
  23771. /*read_timeout_sec=*/2, 0,
  23772. /*write_timeout_sec=*/2, 0, std::string(), error);
  23773. ASSERT_NE(INVALID_SOCKET, sock);
  23774. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23775. auto send_request_and_read_response = [&](const std::string &req,
  23776. std::string &out) -> bool {
  23777. auto sent = send(sock, req.data(), req.size(), 0);
  23778. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23779. char buf[4096];
  23780. for (;;) {
  23781. auto n = recv(sock, buf, sizeof(buf), 0);
  23782. if (n <= 0) { return !out.empty(); }
  23783. out.append(buf, static_cast<size_t>(n));
  23784. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23785. }
  23786. };
  23787. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23788. "Host: localhost\r\n"
  23789. "\r\n";
  23790. std::string resp1;
  23791. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23792. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23793. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23794. "Host: localhost\r\n"
  23795. "Connection: close\r\n"
  23796. "\r\n";
  23797. std::string resp2;
  23798. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23799. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23800. EXPECT_EQ(2, delete_count.load());
  23801. }
  23802. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23803. Server svr;
  23804. svr.Post("/ingest", [&](const Request &, Response &res,
  23805. const ContentReader &content_reader) {
  23806. auto consumed = content_reader([](const char *, size_t) { return false; });
  23807. EXPECT_FALSE(consumed);
  23808. res.status = StatusCode::Conflict_409;
  23809. res.set_header("Connection", "close");
  23810. });
  23811. auto port = svr.bind_to_any_port(HOST);
  23812. thread t = thread([&] { svr.listen_after_bind(); });
  23813. auto se = detail::scope_exit([&] {
  23814. svr.stop();
  23815. t.join();
  23816. });
  23817. svr.wait_until_ready();
  23818. auto error = Error::Success;
  23819. auto sock = detail::create_client_socket(
  23820. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23821. /*connection_timeout_sec=*/2, 0,
  23822. /*read_timeout_sec=*/1, 0,
  23823. /*write_timeout_sec=*/2, 0, std::string(), error);
  23824. ASSERT_NE(INVALID_SOCKET, sock);
  23825. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23826. std::string request = "POST /ingest HTTP/1.1\r\n"
  23827. "Host: localhost\r\n"
  23828. "Transfer-Encoding: chunked\r\n"
  23829. "\r\n"
  23830. "4\r\n"
  23831. "data\r\n";
  23832. auto sent = send(sock, request.data(), request.size(), 0);
  23833. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23834. std::string response;
  23835. ssize_t received = 0;
  23836. do {
  23837. char buf[4096];
  23838. received = recv(sock, buf, sizeof(buf), 0);
  23839. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23840. } while (received > 0);
  23841. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23842. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23843. EXPECT_EQ(0, received);
  23844. }
  23845. namespace no_proxy_test {
  23846. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23847. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23848. // calling listen().
  23849. class ScopedServer {
  23850. public:
  23851. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23852. ~ScopedServer() {
  23853. svr_.stop();
  23854. if (th_.joinable()) { th_.join(); }
  23855. }
  23856. Server &svr() { return svr_; }
  23857. int port() const { return port_; }
  23858. void listen() {
  23859. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23860. svr_.wait_until_ready();
  23861. }
  23862. private:
  23863. Server svr_;
  23864. std::thread th_;
  23865. int port_ = 0;
  23866. };
  23867. class ProxyAndTargetServers {
  23868. public:
  23869. ProxyAndTargetServers() {
  23870. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23871. proxy_hits_++;
  23872. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23873. res.set_content("via-proxy", "text/plain");
  23874. });
  23875. target_.Get(".*", [this](const Request &req, Response &res) {
  23876. target_hits_++;
  23877. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23878. res.set_content("direct", "text/plain");
  23879. });
  23880. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23881. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23882. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23883. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23884. proxy_mock_.wait_until_ready();
  23885. target_.wait_until_ready();
  23886. }
  23887. ~ProxyAndTargetServers() {
  23888. proxy_mock_.stop();
  23889. target_.stop();
  23890. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23891. if (target_thread_.joinable()) { target_thread_.join(); }
  23892. }
  23893. Server &proxy_mock() { return proxy_mock_; }
  23894. Server &target() { return target_; }
  23895. int proxy_port() const { return proxy_port_; }
  23896. int target_port() const { return target_port_; }
  23897. int proxy_hits() const { return proxy_hits_.load(); }
  23898. int target_hits() const { return target_hits_.load(); }
  23899. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23900. void reset_counters() {
  23901. proxy_hits_ = 0;
  23902. target_hits_ = 0;
  23903. last_had_proxy_authz_ = false;
  23904. }
  23905. private:
  23906. Server proxy_mock_;
  23907. Server target_;
  23908. std::thread proxy_thread_;
  23909. std::thread target_thread_;
  23910. int proxy_port_ = 0;
  23911. int target_port_ = 0;
  23912. std::atomic<int> proxy_hits_{0};
  23913. std::atomic<int> target_hits_{0};
  23914. std::atomic<bool> last_had_proxy_authz_{false};
  23915. };
  23916. inline std::unique_ptr<Client> make_client(const std::string &host,
  23917. ProxyAndTargetServers &s) {
  23918. auto cli = detail::make_unique<Client>(host, s.target_port());
  23919. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23920. cli->set_proxy("127.0.0.1", s.proxy_port());
  23921. return cli;
  23922. }
  23923. } // namespace no_proxy_test
  23924. using no_proxy_test::make_client;
  23925. using no_proxy_test::ProxyAndTargetServers;
  23926. TEST(NoProxyTest, ExactHostnameBypasses) {
  23927. ProxyAndTargetServers s;
  23928. auto cli = make_client("example.com", s);
  23929. cli->set_no_proxy({"example.com"});
  23930. auto res = cli->Get("/");
  23931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23932. EXPECT_EQ(0, s.proxy_hits());
  23933. EXPECT_EQ(1, s.target_hits());
  23934. }
  23935. TEST(NoProxyTest, SubdomainBypasses) {
  23936. ProxyAndTargetServers s;
  23937. auto cli = make_client("foo.example.com", s);
  23938. cli->set_no_proxy({"example.com"});
  23939. auto res = cli->Get("/");
  23940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23941. EXPECT_EQ(0, s.proxy_hits());
  23942. EXPECT_EQ(1, s.target_hits());
  23943. }
  23944. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23945. // Regression guard: "evilexample.com" must not be considered a subdomain
  23946. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23947. // check would let traffic bypass the proxy and leak credentials direct
  23948. // to the attacker host.
  23949. ProxyAndTargetServers s;
  23950. auto cli = make_client("evilexample.com", s);
  23951. cli->set_no_proxy({"example.com"});
  23952. auto res = cli->Get("/");
  23953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23954. EXPECT_GE(s.proxy_hits(), 1);
  23955. EXPECT_EQ(0, s.target_hits());
  23956. }
  23957. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23958. ProxyAndTargetServers s;
  23959. auto cli = make_client("example.com.evil.com", s);
  23960. cli->set_no_proxy({"example.com"});
  23961. auto res = cli->Get("/");
  23962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23963. EXPECT_GE(s.proxy_hits(), 1);
  23964. EXPECT_EQ(0, s.target_hits());
  23965. }
  23966. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23967. ProxyAndTargetServers s;
  23968. auto cli = make_client("example.com", s);
  23969. cli->set_no_proxy({".example.com"});
  23970. auto res = cli->Get("/");
  23971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23972. EXPECT_EQ(0, s.proxy_hits());
  23973. EXPECT_EQ(1, s.target_hits());
  23974. }
  23975. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23976. ProxyAndTargetServers s;
  23977. auto cli = make_client("Example.COM", s);
  23978. cli->set_no_proxy({"EXAMPLE.com"});
  23979. auto res = cli->Get("/");
  23980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23981. EXPECT_EQ(0, s.proxy_hits());
  23982. EXPECT_EQ(1, s.target_hits());
  23983. }
  23984. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23985. ProxyAndTargetServers s;
  23986. auto cli = make_client("example.com.", s);
  23987. cli->set_no_proxy({"example.com"});
  23988. auto res = cli->Get("/");
  23989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23990. EXPECT_EQ(0, s.proxy_hits());
  23991. EXPECT_EQ(1, s.target_hits());
  23992. }
  23993. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23994. // Trailing dots must be normalized on BOTH sides — host and entry.
  23995. // An implementation that only strips the host-side trailing dot would
  23996. // fail to match host "example.com" against entry "example.com." because
  23997. // a literal substring search would compare 11 chars against 12.
  23998. ProxyAndTargetServers s;
  23999. auto cli = make_client("example.com", s);
  24000. cli->set_no_proxy({"example.com."});
  24001. auto res = cli->Get("/");
  24002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24003. EXPECT_EQ(0, s.proxy_hits());
  24004. EXPECT_EQ(1, s.target_hits());
  24005. }
  24006. TEST(NoProxyTest, WildcardBypassesEverything) {
  24007. ProxyAndTargetServers s;
  24008. auto cli = make_client("anything.invalid.test", s);
  24009. cli->set_no_proxy({"*"});
  24010. auto res = cli->Get("/");
  24011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24012. EXPECT_EQ(0, s.proxy_hits());
  24013. EXPECT_EQ(1, s.target_hits());
  24014. }
  24015. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24016. ProxyAndTargetServers s;
  24017. Client cli("127.0.0.1", s.target_port());
  24018. cli.set_proxy("127.0.0.1", s.proxy_port());
  24019. cli.set_no_proxy({"127.0.0.1"});
  24020. auto res = cli.Get("/");
  24021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24022. EXPECT_EQ(0, s.proxy_hits());
  24023. EXPECT_EQ(1, s.target_hits());
  24024. }
  24025. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24026. ProxyAndTargetServers s;
  24027. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24028. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24029. cli.set_proxy("127.0.0.1", s.proxy_port());
  24030. cli.set_no_proxy({"::1"});
  24031. auto res = cli.Get("/");
  24032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24033. EXPECT_EQ(0, s.proxy_hits());
  24034. EXPECT_EQ(1, s.target_hits());
  24035. }
  24036. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24037. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24038. // must still be recognized as IPv6 for CIDR matching. Implementations
  24039. // that detect IPv6 only when the host begins with '[' would parse the
  24040. // host as a hostname and miss the match.
  24041. ProxyAndTargetServers s;
  24042. Client cli("fe80::1", s.target_port());
  24043. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24044. cli.set_proxy("127.0.0.1", s.proxy_port());
  24045. cli.set_no_proxy({"fe80::/10"});
  24046. auto res = cli.Get("/");
  24047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24048. EXPECT_EQ(0, s.proxy_hits());
  24049. EXPECT_EQ(1, s.target_hits());
  24050. }
  24051. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24052. ProxyAndTargetServers s;
  24053. Client cli("::1", s.target_port());
  24054. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24055. cli.set_proxy("127.0.0.1", s.proxy_port());
  24056. cli.set_no_proxy({"[::1]"});
  24057. auto res = cli.Get("/");
  24058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24059. EXPECT_EQ(0, s.proxy_hits());
  24060. EXPECT_EQ(1, s.target_hits());
  24061. }
  24062. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24063. ProxyAndTargetServers s;
  24064. Client cli("fe80::1", s.target_port());
  24065. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24066. cli.set_proxy("127.0.0.1", s.proxy_port());
  24067. cli.set_no_proxy({"[fe80::]/10"});
  24068. auto res = cli.Get("/");
  24069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24070. EXPECT_EQ(0, s.proxy_hits());
  24071. EXPECT_EQ(1, s.target_hits());
  24072. }
  24073. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24074. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24075. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24076. // tricks via address-family conversion.
  24077. ProxyAndTargetServers s;
  24078. Client cli("::ffff:127.0.0.1", s.target_port());
  24079. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24080. cli.set_proxy("127.0.0.1", s.proxy_port());
  24081. cli.set_no_proxy({"127.0.0.1"});
  24082. auto res = cli.Get("/");
  24083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24084. EXPECT_GE(s.proxy_hits(), 1);
  24085. EXPECT_EQ(0, s.target_hits());
  24086. }
  24087. TEST(NoProxyTest, IPv4CidrMatch) {
  24088. ProxyAndTargetServers s;
  24089. Client cli("127.0.0.1", s.target_port());
  24090. cli.set_proxy("127.0.0.1", s.proxy_port());
  24091. cli.set_no_proxy({"127.0.0.0/8"});
  24092. auto res = cli.Get("/");
  24093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24094. EXPECT_EQ(0, s.proxy_hits());
  24095. EXPECT_EQ(1, s.target_hits());
  24096. }
  24097. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24098. ProxyAndTargetServers s;
  24099. Client cli("127.0.0.1", s.target_port());
  24100. cli.set_proxy("127.0.0.1", s.proxy_port());
  24101. cli.set_no_proxy({"10.0.0.0/8"});
  24102. auto res = cli.Get("/");
  24103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24104. EXPECT_GE(s.proxy_hits(), 1);
  24105. EXPECT_EQ(0, s.target_hits());
  24106. }
  24107. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24108. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24109. // IPv4 target matches.
  24110. ProxyAndTargetServers s;
  24111. Client cli("127.0.0.1", s.target_port());
  24112. cli.set_proxy("127.0.0.1", s.proxy_port());
  24113. cli.set_no_proxy({"0.0.0.0/0"});
  24114. auto res = cli.Get("/");
  24115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24116. EXPECT_EQ(0, s.proxy_hits());
  24117. EXPECT_EQ(1, s.target_hits());
  24118. }
  24119. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24120. ProxyAndTargetServers s;
  24121. Client cli("127.0.0.1", s.target_port());
  24122. cli.set_proxy("127.0.0.1", s.proxy_port());
  24123. cli.set_no_proxy({"127.0.0.1"});
  24124. auto res = cli.Get("/");
  24125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24126. EXPECT_EQ(0, s.proxy_hits());
  24127. EXPECT_EQ(1, s.target_hits());
  24128. }
  24129. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24130. ProxyAndTargetServers s;
  24131. Client cli("127.0.0.1", s.target_port());
  24132. cli.set_proxy("127.0.0.1", s.proxy_port());
  24133. cli.set_no_proxy({"127.0.0.0/33"});
  24134. auto res = cli.Get("/");
  24135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24136. EXPECT_GE(s.proxy_hits(), 1);
  24137. EXPECT_EQ(0, s.target_hits());
  24138. }
  24139. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24140. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24141. ProxyAndTargetServers s;
  24142. Client cli("127.0.0.1", s.target_port());
  24143. cli.set_proxy("127.0.0.1", s.proxy_port());
  24144. cli.set_no_proxy({"127.0.0.1/"});
  24145. auto res = cli.Get("/");
  24146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24147. EXPECT_GE(s.proxy_hits(), 1);
  24148. EXPECT_EQ(0, s.target_hits());
  24149. }
  24150. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24151. ProxyAndTargetServers s;
  24152. auto cli = make_client("internal.corp", s);
  24153. cli->set_proxy_basic_auth("u", "p");
  24154. cli->set_no_proxy({"internal.corp"});
  24155. auto res = cli->Get("/");
  24156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24157. EXPECT_EQ(1, s.target_hits());
  24158. EXPECT_EQ(0, s.proxy_hits());
  24159. EXPECT_FALSE(s.last_had_proxy_authz())
  24160. << "Proxy-Authorization must not be sent direct to the target";
  24161. }
  24162. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24163. ProxyAndTargetServers s;
  24164. auto cli = make_client("public.example", s);
  24165. cli->set_proxy_basic_auth("u", "p");
  24166. cli->set_no_proxy({"internal.corp"}); // does not match
  24167. auto res = cli->Get("/");
  24168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24169. EXPECT_GE(s.proxy_hits(), 1);
  24170. EXPECT_TRUE(s.last_had_proxy_authz());
  24171. }
  24172. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24173. std::atomic<int> hits{0};
  24174. std::atomic<int> hits_with_authz{0};
  24175. no_proxy_test::ScopedServer proxy_mock;
  24176. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24177. hits++;
  24178. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24179. if (req.target.find("/redir") != std::string::npos) {
  24180. res.set_redirect("http://other.example/landed");
  24181. } else {
  24182. res.set_content("via-proxy", "text/plain");
  24183. }
  24184. });
  24185. proxy_mock.listen();
  24186. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24187. hits = 0;
  24188. hits_with_authz = 0;
  24189. Client cli("public.example", 80);
  24190. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24191. cli.set_proxy_basic_auth(c.first, c.second);
  24192. cli.set_follow_location(true);
  24193. // The redirect to another host goes through the proxy as well
  24194. auto res = cli.Get("/redir");
  24195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24196. EXPECT_EQ(2, hits.load());
  24197. EXPECT_EQ(2, hits_with_authz.load());
  24198. }
  24199. }
  24200. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24201. ProxyAndTargetServers s;
  24202. auto cli = make_client("anything.test", s);
  24203. auto res = cli->Get("/");
  24204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24205. EXPECT_GE(s.proxy_hits(), 1);
  24206. EXPECT_EQ(0, s.target_hits());
  24207. }
  24208. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24209. ProxyAndTargetServers s;
  24210. auto cli = make_client("example.com", s);
  24211. cli->set_no_proxy({"example.com:8080"});
  24212. auto res = cli->Get("/");
  24213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24214. EXPECT_GE(s.proxy_hits(), 1);
  24215. EXPECT_EQ(0, s.target_hits());
  24216. }
  24217. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24218. ProxyAndTargetServers s;
  24219. auto cli = make_client("anything.test", s);
  24220. cli->set_no_proxy({"", " ", "\t"});
  24221. auto res = cli->Get("/");
  24222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24223. EXPECT_GE(s.proxy_hits(), 1);
  24224. EXPECT_EQ(0, s.target_hits());
  24225. }
  24226. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24227. // An entry with leading/trailing whitespace must still match — env-style
  24228. // values are commonly pasted with stray spaces and an implementation
  24229. // that feeds the raw token directly to inet_pton would fail to match
  24230. // valid CIDRs because of the spaces.
  24231. ProxyAndTargetServers s;
  24232. Client cli("127.0.0.1", s.target_port());
  24233. cli.set_proxy("127.0.0.1", s.proxy_port());
  24234. cli.set_no_proxy({" 127.0.0.0/8 "});
  24235. auto res = cli.Get("/");
  24236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24237. EXPECT_EQ(0, s.proxy_hits());
  24238. EXPECT_EQ(1, s.target_hits());
  24239. }
  24240. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24241. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24242. // go direct and must NOT carry Proxy-Authorization.
  24243. std::atomic<int> proxy_hits{0};
  24244. std::atomic<int> target_hits{0};
  24245. std::atomic<bool> target_saw_authz{false};
  24246. no_proxy_test::ScopedServer proxy_mock, target;
  24247. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24248. proxy_hits++;
  24249. res.status = 302;
  24250. res.set_header("Location", "http://127.0.0.1:" +
  24251. std::to_string(target.port()) + "/landed");
  24252. });
  24253. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24254. target_hits++;
  24255. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24256. res.set_content("direct", "text/plain");
  24257. });
  24258. proxy_mock.listen();
  24259. target.listen();
  24260. Client cli("public.example", target.port());
  24261. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24262. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24263. cli.set_proxy_basic_auth("u", "p");
  24264. cli.set_no_proxy({"127.0.0.1"});
  24265. cli.set_follow_location(true);
  24266. auto res = cli.Get("/redir");
  24267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24268. EXPECT_GE(proxy_hits.load(), 1);
  24269. EXPECT_GE(target_hits.load(), 1);
  24270. EXPECT_FALSE(target_saw_authz.load());
  24271. }
  24272. #ifdef CPPHTTPLIB_SSL_ENABLED
  24273. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24274. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24275. // proxy creds would be sent to the (possibly hostile) origin.
  24276. std::atomic<int> target_hits{0};
  24277. std::atomic<bool> target_saw_proxy_authz{false};
  24278. no_proxy_test::ScopedServer target;
  24279. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24280. target_hits++;
  24281. if (req.has_header("Proxy-Authorization")) {
  24282. target_saw_proxy_authz = true;
  24283. }
  24284. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24285. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24286. "nonce=\"abc\", algorithm=MD5");
  24287. });
  24288. target.listen();
  24289. // The proxy address is set to the target's port: the bypass MUST kick in;
  24290. // if it doesn't, the test still routes "via proxy" to the same server and
  24291. // the Proxy-Authorization assertion below catches the leak.
  24292. Client cli("evil.example", target.port());
  24293. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24294. cli.set_proxy("127.0.0.1", target.port());
  24295. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24296. cli.set_no_proxy({"evil.example"});
  24297. auto res = cli.Get("/x");
  24298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24299. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24300. EXPECT_EQ(1, target_hits.load());
  24301. EXPECT_FALSE(target_saw_proxy_authz.load());
  24302. }
  24303. #endif
  24304. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24305. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24306. std::atomic<int> proxy_hits{0};
  24307. std::atomic<int> bypass_hits{0};
  24308. std::atomic<bool> proxy_saw_c_url{false};
  24309. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24310. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24311. proxy_hits++;
  24312. if (req.path.find("/start") != std::string::npos) {
  24313. res.status = 302;
  24314. res.set_header("Location", "http://127.0.0.1:" +
  24315. std::to_string(bypass_server.port()) +
  24316. "/middle");
  24317. return;
  24318. }
  24319. if (req.path.find("/end") != std::string::npos) {
  24320. proxy_saw_c_url = true;
  24321. res.set_content("c-via-proxy", "text/plain");
  24322. return;
  24323. }
  24324. res.set_content("unexpected", "text/plain");
  24325. });
  24326. // public.example's "advertised" port is arbitrary (the request never lands
  24327. // there — it goes through the proxy), but use a dynamic value to stay
  24328. // friendly with sharded parallel runs.
  24329. int public_port = bypass_server.port();
  24330. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24331. bypass_hits++;
  24332. res.status = 302;
  24333. res.set_header("Location", "http://public.example:" +
  24334. std::to_string(public_port) + "/end");
  24335. });
  24336. proxy_mock.listen();
  24337. bypass_server.listen();
  24338. Client cli("public.example", public_port);
  24339. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24340. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24341. cli.set_no_proxy({"127.0.0.1"});
  24342. cli.set_follow_location(true);
  24343. auto res = cli.Get("/start");
  24344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24345. EXPECT_EQ(StatusCode::OK_200, res->status);
  24346. EXPECT_EQ("c-via-proxy", res->body);
  24347. EXPECT_GE(proxy_hits.load(), 2);
  24348. EXPECT_GE(bypass_hits.load(), 1);
  24349. EXPECT_TRUE(proxy_saw_c_url.load());
  24350. }
  24351. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24352. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24353. // request reconnects to the correct endpoint.
  24354. std::atomic<int> proxy_hits{0};
  24355. std::atomic<int> target_hits{0};
  24356. no_proxy_test::ScopedServer proxy_mock, target;
  24357. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24358. proxy_hits++;
  24359. res.set_content("via-proxy", "text/plain");
  24360. });
  24361. target.svr().Get(".*", [&](const Request &, Response &res) {
  24362. target_hits++;
  24363. res.set_content("direct", "text/plain");
  24364. });
  24365. proxy_mock.listen();
  24366. target.listen();
  24367. Client cli("public.example", target.port());
  24368. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24369. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24370. cli.set_keep_alive(true);
  24371. auto res1 = cli.Get("/a");
  24372. ASSERT_TRUE(res1);
  24373. EXPECT_EQ("via-proxy", res1->body);
  24374. EXPECT_EQ(1, proxy_hits.load());
  24375. EXPECT_EQ(0, target_hits.load());
  24376. cli.set_no_proxy({"public.example"});
  24377. auto res2 = cli.Get("/b");
  24378. ASSERT_TRUE(res2);
  24379. EXPECT_EQ("direct", res2->body);
  24380. EXPECT_EQ(1, proxy_hits.load());
  24381. EXPECT_EQ(1, target_hits.load());
  24382. }
  24383. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24384. namespace proxy_tunnel_test {
  24385. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24386. class ScopedSSLServer {
  24387. public:
  24388. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24389. port_ = svr_.bind_to_any_port("127.0.0.1");
  24390. }
  24391. ~ScopedSSLServer() {
  24392. svr_.stop();
  24393. if (th_.joinable()) { th_.join(); }
  24394. }
  24395. SSLServer &svr() { return svr_; }
  24396. int port() const { return port_; }
  24397. void listen() {
  24398. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24399. svr_.wait_until_ready();
  24400. }
  24401. private:
  24402. SSLServer svr_;
  24403. std::thread th_;
  24404. int port_ = 0;
  24405. };
  24406. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24407. class ScopedConnectProxy {
  24408. public:
  24409. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24410. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24411. if (listen_fd_ < 0) { return; }
  24412. int yes = 1;
  24413. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24414. sockaddr_in a{};
  24415. a.sin_family = AF_INET;
  24416. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24417. a.sin_port = 0;
  24418. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24419. return;
  24420. }
  24421. socklen_t alen = sizeof(a);
  24422. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24423. 0) {
  24424. return;
  24425. }
  24426. port_ = ntohs(a.sin_port);
  24427. if (::listen(listen_fd_, 1) != 0) { return; }
  24428. th_ = std::thread([this] { run(); });
  24429. }
  24430. ~ScopedConnectProxy() {
  24431. stop_ = true;
  24432. if (listen_fd_ >= 0) {
  24433. ::shutdown(listen_fd_, SHUT_RDWR);
  24434. ::close(listen_fd_);
  24435. }
  24436. if (th_.joinable()) { th_.join(); }
  24437. }
  24438. int port() const { return port_; }
  24439. int connect_hits() const { return connect_hits_.load(); }
  24440. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24441. std::string connect_request() const {
  24442. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24443. return connect_request_;
  24444. }
  24445. private:
  24446. void run() {
  24447. while (!stop_.load()) {
  24448. fd_set rfds;
  24449. FD_ZERO(&rfds);
  24450. FD_SET(listen_fd_, &rfds);
  24451. timeval tv{0, 100 * 1000};
  24452. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24453. if (sel <= 0) { continue; }
  24454. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24455. if (client_fd < 0) { continue; }
  24456. std::string req;
  24457. char buf[2048];
  24458. while (req.find("\r\n\r\n") == std::string::npos) {
  24459. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24460. if (n <= 0) { break; }
  24461. req.append(buf, static_cast<size_t>(n));
  24462. }
  24463. if (req.compare(0, 7, "CONNECT") != 0) {
  24464. ::close(client_fd);
  24465. continue;
  24466. }
  24467. connect_hits_++;
  24468. {
  24469. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24470. connect_request_ = req;
  24471. }
  24472. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24473. ::send(client_fd, ok, std::strlen(ok), 0);
  24474. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24475. sockaddr_in o{};
  24476. o.sin_family = AF_INET;
  24477. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24478. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24479. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24480. 0) {
  24481. ::close(client_fd);
  24482. ::close(origin_fd);
  24483. continue;
  24484. }
  24485. auto forward = [](int from, int to) {
  24486. char b[8192];
  24487. for (;;) {
  24488. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24489. if (n <= 0) { break; }
  24490. ssize_t off = 0;
  24491. while (off < n) {
  24492. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24493. if (s <= 0) {
  24494. off = n;
  24495. break;
  24496. }
  24497. off += s;
  24498. }
  24499. }
  24500. ::shutdown(to, SHUT_WR);
  24501. };
  24502. std::thread t1([&] { forward(client_fd, origin_fd); });
  24503. std::thread t2([&] { forward(origin_fd, client_fd); });
  24504. t1.join();
  24505. t2.join();
  24506. ::close(client_fd);
  24507. ::close(origin_fd);
  24508. }
  24509. }
  24510. int forward_port_ = -1;
  24511. int listen_fd_ = -1;
  24512. int port_ = 0;
  24513. std::thread th_;
  24514. std::atomic<bool> stop_{false};
  24515. std::atomic<int> connect_hits_{0};
  24516. mutable std::mutex connect_request_mutex_;
  24517. std::string connect_request_;
  24518. };
  24519. // Sends one request through the CONNECT proxy to the TLS origin with a
  24520. // credential configured for each hop, and checks that each credential reaches
  24521. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24522. // origin's (every header in origin_headers) on the tunnelled request.
  24523. void CredentialsStayWithTheirHop(
  24524. const std::function<void(SSLClient &)> &set_credentials,
  24525. const std::string &scheme,
  24526. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24527. std::atomic<int> origin_hits{0};
  24528. std::atomic<bool> origin_saw_proxy_authz{false};
  24529. std::atomic<bool> origin_saw_headers{false};
  24530. ScopedSSLServer origin;
  24531. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24532. origin_hits++;
  24533. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24534. origin_saw_headers =
  24535. std::all_of(origin_headers.begin(), origin_headers.end(),
  24536. [&](const std::string &h) { return req.has_header(h); });
  24537. res.set_content("ok", "text/plain");
  24538. });
  24539. origin.listen();
  24540. ScopedConnectProxy proxy(origin.port());
  24541. ASSERT_NE(0, proxy.port());
  24542. // Pinned to 127.0.0.1 for the same reason as the test below.
  24543. SSLClient cli("127.0.0.1", origin.port());
  24544. cli.enable_server_certificate_verification(false);
  24545. cli.set_proxy("127.0.0.1", proxy.port());
  24546. set_credentials(cli);
  24547. auto res = cli.Get("/x");
  24548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24549. EXPECT_EQ(StatusCode::OK_200, res->status);
  24550. EXPECT_EQ(1, origin_hits.load());
  24551. EXPECT_EQ(1, proxy.connect_hits());
  24552. EXPECT_TRUE(origin_saw_headers.load());
  24553. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24554. << "Proxy-Authorization must not be sent inside the tunnel";
  24555. auto connect_req = proxy.connect_request();
  24556. EXPECT_NE(std::string::npos,
  24557. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24558. for (const auto &h : origin_headers) {
  24559. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24560. << h << " must not be sent to the proxy on CONNECT";
  24561. }
  24562. }
  24563. } // namespace proxy_tunnel_test
  24564. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24565. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24566. [](SSLClient &cli) {
  24567. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24568. cli.set_basic_auth("origin-user", "origin-pass");
  24569. },
  24570. "Basic");
  24571. }
  24572. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24573. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24574. [](SSLClient &cli) {
  24575. cli.set_proxy_bearer_token_auth("proxy-token");
  24576. cli.set_bearer_token_auth("origin-token");
  24577. },
  24578. "Bearer");
  24579. }
  24580. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24581. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24582. [](SSLClient &cli) {
  24583. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24584. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24585. {"Cookie", "sid=origin-session"},
  24586. {"X-Api-Key", "origin-key"}});
  24587. },
  24588. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24589. }
  24590. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24591. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24592. // retry; otherwise proxy creds would be sent to the origin.
  24593. std::atomic<int> origin_hits{0};
  24594. std::atomic<bool> origin_saw_proxy_authz{false};
  24595. proxy_tunnel_test::ScopedSSLServer origin;
  24596. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24597. origin_hits++;
  24598. if (req.has_header("Proxy-Authorization")) {
  24599. origin_saw_proxy_authz = true;
  24600. }
  24601. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24602. res.set_header("Proxy-Authenticate",
  24603. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24604. "algorithm=MD5");
  24605. });
  24606. origin.listen();
  24607. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24608. ASSERT_NE(0, proxy.port());
  24609. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24610. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24611. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24612. // and answer with its own status, making this test flaky.
  24613. SSLClient cli("127.0.0.1", origin.port());
  24614. cli.enable_server_certificate_verification(false);
  24615. cli.set_proxy("127.0.0.1", proxy.port());
  24616. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24617. auto res = cli.Get("/x");
  24618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24619. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24620. EXPECT_EQ(1, origin_hits.load());
  24621. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24622. EXPECT_EQ(1, proxy.connect_hits());
  24623. }
  24624. #endif