1
0

test.cc 930 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666
  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. } // namespace detail
  488. } // namespace httplib
  489. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  490. struct {
  491. const char *line;
  492. const char *version;
  493. int status;
  494. const char *reason;
  495. } cases[] = {
  496. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  497. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  498. // The reason phrase may be empty, or left out along with its space.
  499. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  500. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  501. };
  502. for (const auto &c : cases) {
  503. std::string version;
  504. int status = 0;
  505. std::string reason = "unset";
  506. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  507. << c.line;
  508. EXPECT_EQ(c.version, version);
  509. EXPECT_EQ(c.status, status);
  510. EXPECT_EQ(c.reason, reason);
  511. }
  512. }
  513. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  514. const char *lines[] = {
  515. "HTTP/2 200 OK\r\n",
  516. "HTTP/1.2 200 OK\r\n",
  517. "HTTP/1.1 20 OK\r\n",
  518. "HTTP/1.1 2000 OK\r\n",
  519. "HTTP/1.1 2x0 OK\r\n",
  520. "HTTP/1.1 200 OK\r\n",
  521. "HTTP/1.1 200OK\r\n",
  522. "HTTP/1.1 200 O\rK\r\n",
  523. "HTTP/1.1 200 OK",
  524. "HTTP/1.1 200 OK\r\nX",
  525. "",
  526. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  527. "HTTP/1.1 200 OK\n",
  528. #endif
  529. };
  530. for (auto line : lines) {
  531. std::string version;
  532. int status = 0;
  533. std::string reason;
  534. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  535. << line;
  536. }
  537. }
  538. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  539. // Long enough to overflow the stack when matched with std::regex.
  540. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  541. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  542. std::string version;
  543. int status = 0;
  544. std::string reason;
  545. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  546. EXPECT_EQ(200, status);
  547. EXPECT_EQ(long_reason, reason);
  548. }
  549. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  550. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  551. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  552. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  553. EXPECT_EQ("", detail::file_extension("noext"));
  554. EXPECT_EQ("", detail::file_extension("a."));
  555. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  556. EXPECT_EQ("", detail::file_extension("a.b-c"));
  557. // Long enough to overflow the stack when matched with std::regex.
  558. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  559. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  560. }
  561. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  562. detail::case_ignore::hash hash;
  563. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  564. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  565. // Long enough to overflow the stack if hashed one call per character.
  566. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  567. }
  568. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  569. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  570. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  571. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  572. // Same 26-bit hash as html, svg and js.
  573. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  574. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  575. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  576. }
  577. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  578. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  579. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  580. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  581. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  582. // Same 26-bit hash as application/json.
  583. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  584. }
  585. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  586. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  587. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  588. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  589. // Same 26-bit hash as REMOTE_ADDR.
  590. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  591. }
  592. // Forward declaration: in split builds split.py strips `inline` and moves the
  593. // definition into httplib.cc, so detail::base64_encode is not visible from the
  594. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  595. // in both header-only and split builds.
  596. namespace httplib {
  597. namespace detail {
  598. std::string base64_encode(const std::string &in);
  599. } // namespace detail
  600. } // namespace httplib
  601. TEST(Base64EncodeTest, KnownAnswers) {
  602. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  603. // where the accumulator's top bit is already set before the next shift.
  604. EXPECT_EQ("", detail::base64_encode(""));
  605. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  606. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  607. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  608. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  609. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  610. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  611. // High bytes keep the top bit set across several rounds.
  612. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  613. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  614. }
  615. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  616. string unescapedCharacters = "-_.!~*'()";
  617. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  618. }
  619. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  620. string reservedCharacters = ";,/?:@&=+$";
  621. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  622. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  623. }
  624. TEST(ClientQueryOrder, PreserveOrder) {
  625. // This test reproduces Issue #2259: client may reorder query parameters
  626. // when sending a GET request. The expected behavior is that the client
  627. // preserves the original query string order when the caller supplied it
  628. // as part of the path.
  629. Server svr;
  630. svr.Get("/", [&](const Request &req, Response &res) {
  631. // Echo back the raw target so the test can assert ordering
  632. res.set_content(req.target, "text/plain");
  633. });
  634. std::thread t{[&] { svr.listen(HOST, PORT); }};
  635. auto se = detail::scope_exit([&] {
  636. svr.stop();
  637. t.join();
  638. ASSERT_FALSE(svr.is_running());
  639. });
  640. svr.wait_until_ready();
  641. Client cli(HOST, PORT);
  642. ASSERT_TRUE(cli.is_valid());
  643. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  644. auto res = cli.Get(original);
  645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  646. // Expect the echoed target to exactly match the original path (order
  647. // preserved)
  648. EXPECT_EQ(res->body, original);
  649. }
  650. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  651. string chineseCharacters = U8("中国語");
  652. string russianCharacters = U8("дом");
  653. string brazilianCharacters = U8("óculos");
  654. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  655. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  656. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  657. "%D0%B4%D0%BE%D0%BC");
  658. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  659. }
  660. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  661. string unescapedCharacters = "-_.!~*'()";
  662. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  663. }
  664. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  665. string reservedCharacters = ";,/?:@&=+$";
  666. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  667. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  668. }
  669. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  670. string chineseCharacters = U8("中国語");
  671. string russianCharacters = U8("дом");
  672. string brazilianCharacters = U8("óculos");
  673. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  674. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  675. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  676. "%D0%B4%D0%BE%D0%BC");
  677. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  678. }
  679. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  680. // Issue #2082 use case: encoding path component with ampersand
  681. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  682. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  683. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  684. }
  685. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  686. string unescapedCharacters = "-_.!~*'()";
  687. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  688. }
  689. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  690. string reservedCharacters = ";,/?:@&=+$#";
  691. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  692. }
  693. TEST(EncodeUriTest, TestUTF8Characters) {
  694. string chineseCharacters = U8("中国語");
  695. string russianCharacters = U8("дом");
  696. string brazilianCharacters = U8("óculos");
  697. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  698. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  699. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  700. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  701. }
  702. TEST(EncodeUriTest, TestCompleteUri) {
  703. string uri =
  704. "https://example.com/path/to/resource?query=value&param=test#fragment";
  705. EXPECT_EQ(
  706. httplib::encode_uri(uri),
  707. "https://example.com/path/to/resource?query=value&param=test#fragment");
  708. }
  709. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  710. string uri =
  711. "https://example.com/path with spaces/file name.html?q=hello world";
  712. EXPECT_EQ(httplib::encode_uri(uri),
  713. "https://example.com/path%20with%20spaces/"
  714. "file%20name.html?q=hello%20world");
  715. }
  716. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  717. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  718. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  719. }
  720. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  721. string unescapedCharacters = "-_.!~*'()";
  722. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  723. }
  724. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  725. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  726. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  727. string encodedBrazilian = "%C3%B3culos";
  728. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  729. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  730. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  731. }
  732. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  733. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  734. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  735. "Piri Tommy Villiers - on & on");
  736. }
  737. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  738. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  739. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  740. }
  741. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  742. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  743. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  744. }
  745. TEST(DecodeUriTest, TestUTF8Characters) {
  746. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  747. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  748. string encodedBrazilian = "%C3%B3culos";
  749. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  750. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  751. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  752. }
  753. TEST(DecodeUriTest, TestCompleteUri) {
  754. string encodedUri = "https://example.com/path%20with%20spaces/"
  755. "file%20name.html?q=hello%20world";
  756. EXPECT_EQ(
  757. httplib::decode_uri(encodedUri),
  758. "https://example.com/path with spaces/file name.html?q=hello world");
  759. }
  760. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  761. string original =
  762. "https://example.com/path with spaces/file name.html?q=hello world";
  763. string encoded = httplib::encode_uri(original);
  764. string decoded = httplib::decode_uri(encoded);
  765. EXPECT_EQ(decoded, original);
  766. }
  767. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  768. // decode_uri is the inverse of encode_uri: an escaped reserved character
  769. // stays encoded so it is not promoted into a real delimiter, while
  770. // non-reserved escapes still decode (like JS decodeURI).
  771. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  772. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  773. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  774. "%3F%3A%40%26%3D%2B%24%2C%3B");
  775. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  776. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  777. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  778. "http://example.com/a%2Fb");
  779. // decode_uri_component still decodes the reserved character.
  780. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  781. }
  782. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  783. string original = "Piri Tommy Villiers - on & on";
  784. string encoded = httplib::encode_uri_component(original);
  785. string decoded = httplib::decode_uri_component(encoded);
  786. EXPECT_EQ(decoded, original);
  787. }
  788. TEST(TrimTests, TrimStringTests) {
  789. EXPECT_EQ("abc", detail::trim_copy("abc"));
  790. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  791. EXPECT_TRUE(detail::trim_copy("").empty());
  792. }
  793. TEST(AsciiTest, LocaleIndependentClassification) {
  794. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  795. // which consult the global C locale: std::isalnum(0xC5) can return true
  796. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  797. // helpers must classify every byte by the ASCII grammar alone.
  798. for (int i = 0; i < 256; i++) {
  799. auto c = static_cast<char>(i);
  800. auto is_digit = i >= '0' && i <= '9';
  801. auto is_upper = i >= 'A' && i <= 'Z';
  802. auto is_lower = i >= 'a' && i <= 'z';
  803. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  804. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  805. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  806. << "byte " << i;
  807. }
  808. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  809. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  810. // Non-ASCII bytes must be percent-encoded, never passed through as
  811. // alphanumeric.
  812. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  813. }
  814. TEST(FromCharsTest, Double) {
  815. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  816. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  817. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  818. auto parse = [](const std::string &s, double &v) {
  819. return detail::from_chars(s.data(), s.data() + s.size(), v);
  820. };
  821. double v = -1.0;
  822. // Representative quality values.
  823. EXPECT_EQ(parse("0", v).ec, std::errc{});
  824. EXPECT_DOUBLE_EQ(v, 0.0);
  825. EXPECT_EQ(parse("1", v).ec, std::errc{});
  826. EXPECT_DOUBLE_EQ(v, 1.0);
  827. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  828. EXPECT_DOUBLE_EQ(v, 0.8);
  829. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  830. EXPECT_DOUBLE_EQ(v, 0.001);
  831. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  832. EXPECT_DOUBLE_EQ(v, 1.0);
  833. // A missing integer or fractional part is tolerated.
  834. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  835. EXPECT_DOUBLE_EQ(v, 0.5);
  836. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  837. EXPECT_DOUBLE_EQ(v, 5.0);
  838. // Values outside [0, 1] still parse; the caller range-checks them.
  839. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  840. EXPECT_DOUBLE_EQ(v, 123.456);
  841. // Stops at the first byte that is not part of the number and reports where.
  842. std::string trailing = "0.9, text/html";
  843. auto r = parse(trailing, v);
  844. EXPECT_EQ(r.ec, std::errc{});
  845. EXPECT_DOUBLE_EQ(v, 0.9);
  846. EXPECT_EQ(*r.ptr, ',');
  847. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  848. // outright, and an 'e'/'E' simply ends the number.
  849. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  850. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  851. std::string exp_input = "1.5e3";
  852. r = parse(exp_input, v);
  853. EXPECT_EQ(r.ec, std::errc{});
  854. EXPECT_DOUBLE_EQ(v, 1.5);
  855. EXPECT_EQ(*r.ptr, 'e');
  856. // Invalid inputs.
  857. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  858. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  859. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  860. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  861. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  862. // Pathological but well-formed inputs must stay bounded (no overflow, no
  863. // out-of-bounds table access) and stay within [0, 1] for the caller.
  864. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  865. std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 0.0);
  867. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  868. std::errc{});
  869. EXPECT_GE(v, 0.0);
  870. EXPECT_LE(v, 1.0);
  871. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  872. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  873. }
  874. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  875. // Simple case without quality values
  876. std::vector<std::string> result1;
  877. EXPECT_TRUE(detail::parse_accept_header(
  878. "text/html,application/json,text/plain", result1));
  879. EXPECT_EQ(result1.size(), 3U);
  880. EXPECT_EQ(result1[0], "text/html");
  881. EXPECT_EQ(result1[1], "application/json");
  882. EXPECT_EQ(result1[2], "text/plain");
  883. // With quality values
  884. std::vector<std::string> result2;
  885. EXPECT_TRUE(detail::parse_accept_header(
  886. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  887. EXPECT_EQ(result2.size(), 3U);
  888. EXPECT_EQ(result2[0], "application/json"); // highest q value
  889. EXPECT_EQ(result2[1], "text/html");
  890. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  891. }
  892. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  893. // Mixed with and without quality values
  894. std::vector<std::string> result;
  895. EXPECT_TRUE(detail::parse_accept_header(
  896. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  897. EXPECT_EQ(result.size(), 3U);
  898. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  899. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  900. EXPECT_EQ(result[2], "application/json"); // q=0.5
  901. }
  902. TEST(ParseAcceptHeaderTest, EdgeCases) {
  903. // Empty header
  904. std::vector<std::string> empty_result;
  905. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  906. EXPECT_TRUE(empty_result.empty());
  907. // Single type
  908. std::vector<std::string> single_result;
  909. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  910. EXPECT_EQ(single_result.size(), 1U);
  911. EXPECT_EQ(single_result[0], "application/json");
  912. // Wildcard types
  913. std::vector<std::string> wildcard_result;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  916. EXPECT_EQ(wildcard_result.size(), 3U);
  917. EXPECT_EQ(wildcard_result[0], "application/json");
  918. EXPECT_EQ(wildcard_result[1], "text/*");
  919. EXPECT_EQ(wildcard_result[2], "*/*");
  920. }
  921. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  922. // Common browser Accept header
  923. std::vector<std::string> browser_result;
  924. EXPECT_TRUE(
  925. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  926. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  927. browser_result));
  928. EXPECT_EQ(browser_result.size(), 6U);
  929. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  930. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  931. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  932. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  933. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  934. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  935. // API client header
  936. std::vector<std::string> api_result;
  937. EXPECT_TRUE(detail::parse_accept_header(
  938. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  939. api_result));
  940. EXPECT_EQ(api_result.size(), 3U);
  941. EXPECT_EQ(api_result[0], "application/json");
  942. EXPECT_EQ(api_result[1], "application/xml");
  943. EXPECT_EQ(api_result[2], "text/plain");
  944. }
  945. TEST(ParseAcceptHeaderTest, SpecialCases) {
  946. // Quality value with 3 decimal places
  947. std::vector<std::string> decimal_result;
  948. EXPECT_TRUE(detail::parse_accept_header(
  949. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  950. EXPECT_EQ(decimal_result.size(), 2U);
  951. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  952. EXPECT_EQ(decimal_result[1], "text/html");
  953. // Zero quality (should still be included but with lowest priority)
  954. std::vector<std::string> zero_q_result;
  955. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  956. zero_q_result));
  957. EXPECT_EQ(zero_q_result.size(), 2U);
  958. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  959. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  960. // No spaces around commas
  961. std::vector<std::string> no_space_result;
  962. EXPECT_TRUE(detail::parse_accept_header(
  963. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  964. no_space_result));
  965. EXPECT_EQ(no_space_result.size(), 3U);
  966. EXPECT_EQ(no_space_result[0], "text/html");
  967. EXPECT_EQ(no_space_result[1], "application/json");
  968. EXPECT_EQ(no_space_result[2], "text/plain");
  969. }
  970. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  971. // Quality values always use '.' as the decimal separator, so parsing must
  972. // not depend on the process locale. An embedding application may have
  973. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  974. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  975. std::string saved = cur ? cur : "C";
  976. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  977. "fr_FR.UTF-8"};
  978. bool switched = false;
  979. for (const auto loc : comma_locales) {
  980. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  981. std::localeconv()->decimal_point[0] == ',') {
  982. switched = true;
  983. break;
  984. }
  985. }
  986. if (!switched) {
  987. std::setlocale(LC_NUMERIC, saved.c_str());
  988. GTEST_SKIP() << "no comma-decimal locale available on this host";
  989. }
  990. // The higher-weighted type appears later in the list, so a correct parse
  991. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  992. // sensitive parse reads both weights as 0 and leaves the original order.
  993. std::vector<std::string> result;
  994. EXPECT_TRUE(detail::parse_accept_header(
  995. "application/json;q=0.1,text/html;q=0.9", result));
  996. ASSERT_EQ(result.size(), 2U);
  997. EXPECT_EQ(result[0], "text/html");
  998. EXPECT_EQ(result[1], "application/json");
  999. std::setlocale(LC_NUMERIC, saved.c_str());
  1000. }
  1001. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1002. std::vector<std::string> result;
  1003. // Invalid quality value (> 1.0)
  1004. EXPECT_FALSE(
  1005. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1006. // Invalid quality value (< 0.0)
  1007. EXPECT_FALSE(
  1008. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1009. // Invalid quality value (not a number)
  1010. EXPECT_FALSE(detail::parse_accept_header(
  1011. "text/html;q=invalid,application/json", result));
  1012. // A valid numeric prefix does not make the entire quality value valid.
  1013. EXPECT_FALSE(detail::parse_accept_header(
  1014. "text/html;q=0.5junk,application/json", result));
  1015. // Empty quality value
  1016. EXPECT_FALSE(
  1017. detail::parse_accept_header("text/html;q=,application/json", result));
  1018. // Invalid media type format (no slash and not wildcard)
  1019. EXPECT_FALSE(
  1020. detail::parse_accept_header("invalidtype,application/json", result));
  1021. // Valid cases should still work
  1022. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1023. EXPECT_EQ(result.size(), 1U);
  1024. EXPECT_EQ(result[0], "*/*");
  1025. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1026. EXPECT_EQ(result.size(), 1U);
  1027. EXPECT_EQ(result[0], "*");
  1028. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1029. EXPECT_EQ(result.size(), 1U);
  1030. EXPECT_EQ(result[0], "text/*");
  1031. }
  1032. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1033. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1034. // and must not be answered with 400 Bad Request.
  1035. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1036. struct {
  1037. const char *value;
  1038. std::vector<std::string> expected;
  1039. } cases[] = {
  1040. {",application/json", {"application/json"}},
  1041. {"text/html,", {"text/html"}},
  1042. {"text/html,,*/*", {"text/html", "*/*"}},
  1043. // An empty element may be spelled with whitespace in it
  1044. {"text/html, , application/json", {"text/html", "application/json"}},
  1045. // Nothing but empty elements is an empty list, which means the same
  1046. // thing as no Accept header at all
  1047. {",,,", {}},
  1048. // Quality values still apply across ignored empty elements
  1049. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1050. };
  1051. for (const auto &c : cases) {
  1052. std::vector<std::string> result;
  1053. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1054. << "value: " << c.value;
  1055. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1056. }
  1057. // An invalid entry is still rejected when empty elements surround it
  1058. std::vector<std::string> result;
  1059. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1060. }
  1061. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1062. // or ';' inside one does not end the list element or the parameter. Section
  1063. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1064. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1065. struct {
  1066. const char *value;
  1067. std::vector<std::string> expected;
  1068. } cases[] = {
  1069. {"text/html;profile=\"a,b\",application/json",
  1070. {"text/html", "application/json"}},
  1071. // A "q=" inside a quoted value is not the weight
  1072. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1073. {"text/html", "application/json"}},
  1074. // The weight after a quoted value still applies
  1075. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1076. {"application/json", "text/html"}},
  1077. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1078. {"application/json", "text/html"}},
  1079. {"text/html;profile=\"a\\\"b\",application/json",
  1080. {"text/html", "application/json"}},
  1081. // An escaped backslash does not escape the '"' after it
  1082. {"text/html;profile=\"a\\\\\",application/json",
  1083. {"text/html", "application/json"}},
  1084. };
  1085. for (const auto &c : cases) {
  1086. std::vector<std::string> result;
  1087. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1088. << "value: " << c.value;
  1089. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1090. }
  1091. }
  1092. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1093. Server svr;
  1094. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1095. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1096. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1097. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1098. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1099. res.set_content("ok", "text/plain");
  1100. });
  1101. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1102. EXPECT_TRUE(false);
  1103. res.set_content("bad request", "text/plain");
  1104. });
  1105. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1106. auto se = detail::scope_exit([&] {
  1107. svr.stop();
  1108. listen_thread.join();
  1109. ASSERT_FALSE(svr.is_running());
  1110. });
  1111. svr.wait_until_ready();
  1112. Client cli("localhost", PORT);
  1113. {
  1114. auto res = cli.Get(
  1115. "/accept_ok",
  1116. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1118. EXPECT_EQ(StatusCode::OK_200, res->status);
  1119. }
  1120. {
  1121. auto res = cli.Get("/accept_bad_request",
  1122. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1124. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1125. }
  1126. }
  1127. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1128. Server svr;
  1129. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1130. res.set_content("ok", "text/plain");
  1131. });
  1132. std::atomic<int> start_count{0};
  1133. std::atomic<bool> running_when_called{false};
  1134. svr.set_start_handler([&]() {
  1135. running_when_called = svr.is_running();
  1136. start_count++;
  1137. });
  1138. auto port = svr.bind_to_any_port(HOST);
  1139. std::thread t([&]() { svr.listen_after_bind(); });
  1140. auto se = detail::scope_exit([&] {
  1141. svr.stop();
  1142. t.join();
  1143. ASSERT_FALSE(svr.is_running());
  1144. });
  1145. svr.wait_until_ready();
  1146. // A successful request proves the accept loop is running, which the start
  1147. // handler precedes; so by now the handler must have run exactly once.
  1148. Client cli(HOST, port);
  1149. cli.set_connection_timeout(std::chrono::seconds(5));
  1150. auto res = cli.Get("/");
  1151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1152. EXPECT_EQ(StatusCode::OK_200, res->status);
  1153. EXPECT_EQ(1, start_count.load());
  1154. EXPECT_TRUE(running_when_called.load());
  1155. }
  1156. TEST(DivideTest, DivideStringTests) {
  1157. auto divide = [](const std::string &str, char d) {
  1158. std::string lhs;
  1159. std::string rhs;
  1160. detail::divide(str, d,
  1161. [&](const char *lhs_data, std::size_t lhs_size,
  1162. const char *rhs_data, std::size_t rhs_size) {
  1163. lhs.assign(lhs_data, lhs_size);
  1164. rhs.assign(rhs_data, rhs_size);
  1165. });
  1166. return std::make_pair(std::move(lhs), std::move(rhs));
  1167. };
  1168. {
  1169. const auto res = divide("", '=');
  1170. EXPECT_EQ(res.first, "");
  1171. EXPECT_EQ(res.second, "");
  1172. }
  1173. {
  1174. const auto res = divide("=", '=');
  1175. EXPECT_EQ(res.first, "");
  1176. EXPECT_EQ(res.second, "");
  1177. }
  1178. {
  1179. const auto res = divide(" ", '=');
  1180. EXPECT_EQ(res.first, " ");
  1181. EXPECT_EQ(res.second, "");
  1182. }
  1183. {
  1184. const auto res = divide("a", '=');
  1185. EXPECT_EQ(res.first, "a");
  1186. EXPECT_EQ(res.second, "");
  1187. }
  1188. {
  1189. const auto res = divide("a=", '=');
  1190. EXPECT_EQ(res.first, "a");
  1191. EXPECT_EQ(res.second, "");
  1192. }
  1193. {
  1194. const auto res = divide("=b", '=');
  1195. EXPECT_EQ(res.first, "");
  1196. EXPECT_EQ(res.second, "b");
  1197. }
  1198. {
  1199. const auto res = divide("a=b", '=');
  1200. EXPECT_EQ(res.first, "a");
  1201. EXPECT_EQ(res.second, "b");
  1202. }
  1203. {
  1204. const auto res = divide("a=b=", '=');
  1205. EXPECT_EQ(res.first, "a");
  1206. EXPECT_EQ(res.second, "b=");
  1207. }
  1208. {
  1209. const auto res = divide("a=b=c", '=');
  1210. EXPECT_EQ(res.first, "a");
  1211. EXPECT_EQ(res.second, "b=c");
  1212. }
  1213. }
  1214. TEST(SplitTest, ParseQueryString) {
  1215. string s = "key1=val1&key2=val2&key3=val3";
  1216. Params dic;
  1217. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1218. [&](const char *b, const char *e) {
  1219. string key, val;
  1220. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1221. if (key.empty()) {
  1222. key.assign(b2, e2);
  1223. } else {
  1224. val.assign(b2, e2);
  1225. }
  1226. });
  1227. dic.emplace(key, val);
  1228. });
  1229. EXPECT_EQ("val1", dic.find("key1")->second);
  1230. EXPECT_EQ("val2", dic.find("key2")->second);
  1231. EXPECT_EQ("val3", dic.find("key3")->second);
  1232. }
  1233. TEST(SplitTest, ParseInvalidQueryTests) {
  1234. {
  1235. string s = " ";
  1236. Params dict;
  1237. detail::parse_query_text(s, dict);
  1238. EXPECT_TRUE(dict.empty());
  1239. }
  1240. {
  1241. string s = " = =";
  1242. Params dict;
  1243. detail::parse_query_text(s, dict);
  1244. EXPECT_TRUE(dict.empty());
  1245. }
  1246. }
  1247. TEST(ParseQueryTest, ParseQueryString) {
  1248. {
  1249. std::string s = "key1=val1&key2=val2&key3=val3";
  1250. Params dic;
  1251. detail::parse_query_text(s, dic);
  1252. EXPECT_EQ("val1", dic.find("key1")->second);
  1253. EXPECT_EQ("val2", dic.find("key2")->second);
  1254. EXPECT_EQ("val3", dic.find("key3")->second);
  1255. }
  1256. {
  1257. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1258. Params dic;
  1259. detail::parse_query_text(s, dic);
  1260. EXPECT_EQ("", dic.find("key1")->second);
  1261. EXPECT_EQ("val1", dic.find("key2")->second);
  1262. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1263. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1264. }
  1265. }
  1266. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1267. Params dic;
  1268. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1269. dic.emplace("key1", "val1");
  1270. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1271. dic.emplace("key2", "val2");
  1272. dic.emplace("key3", "val3");
  1273. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1274. }
  1275. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1276. Params params;
  1277. params.emplace("a", "1");
  1278. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1279. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1280. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1281. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1282. // Long enough to overflow the stack when matched with std::regex.
  1283. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1284. EXPECT_EQ("/p?" + long_query + "&a=1",
  1285. append_query_params("/p?" + long_query, params));
  1286. }
  1287. // Joins every entry of a Headers or Params into "key=value " so a whole
  1288. // traversal can be compared in one assertion. Both are instantiations of the
  1289. // same insertion-ordered container, so one helper serves both.
  1290. template <typename Map> static std::string entries_to_string(const Map &m) {
  1291. std::string s;
  1292. for (const auto &entry : m) {
  1293. s += entry.first + "=" + entry.second + " ";
  1294. }
  1295. return s;
  1296. }
  1297. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1298. // Params used to be a std::multimap, which sorted by name and handed the
  1299. // caller's query back alphabetised. A client signing its query string could
  1300. // not reproduce the order it asked for.
  1301. Params dic;
  1302. dic.emplace("zulu", "1");
  1303. dic.emplace("alpha", "2");
  1304. dic.emplace("mike", "3");
  1305. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1306. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1307. }
  1308. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1309. Params dic;
  1310. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1311. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1312. }
  1313. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1314. Request req;
  1315. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1316. req.params);
  1317. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1318. EXPECT_EQ("first", req.get_param_value("tag"));
  1319. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1320. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1321. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1322. EXPECT_EQ("", req.get_param_value("tag", 3));
  1323. }
  1324. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1325. // Params shares its container with Headers, which matches field names
  1326. // case-insensitively. Parameter names must not pick that up.
  1327. Params dic;
  1328. dic.emplace("Key", "upper");
  1329. dic.emplace("key", "lower");
  1330. EXPECT_EQ(2U, dic.size());
  1331. EXPECT_EQ(1U, dic.count("Key"));
  1332. EXPECT_EQ(1U, dic.count("key"));
  1333. EXPECT_EQ("upper", dic.find("Key")->second);
  1334. EXPECT_EQ("lower", dic.find("key")->second);
  1335. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1336. }
  1337. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1338. Server svr;
  1339. std::string order;
  1340. svr.Get("/order", [&](const Request &req, Response &res) {
  1341. order = entries_to_string(req.params);
  1342. res.set_content("ok", "text/plain");
  1343. });
  1344. auto port = svr.bind_to_any_port(HOST);
  1345. thread t = thread([&] { svr.listen_after_bind(); });
  1346. auto se = detail::scope_exit([&] {
  1347. svr.stop();
  1348. t.join();
  1349. ASSERT_FALSE(svr.is_running());
  1350. });
  1351. svr.wait_until_ready();
  1352. Client cli(HOST, port);
  1353. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1354. ASSERT_TRUE(res);
  1355. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1356. }
  1357. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1358. Server svr;
  1359. std::string field_order, file_order;
  1360. svr.Post("/order", [&](const Request &req, Response &res) {
  1361. for (const auto &field : req.form.fields) {
  1362. field_order += field.first + "=" + field.second.content + " ";
  1363. }
  1364. for (const auto &file : req.form.files) {
  1365. file_order += file.first + "=" + file.second.filename + " ";
  1366. }
  1367. res.set_content("ok", "text/plain");
  1368. });
  1369. auto port = svr.bind_to_any_port(HOST);
  1370. thread t = thread([&] { svr.listen_after_bind(); });
  1371. auto se = detail::scope_exit([&] {
  1372. svr.stop();
  1373. t.join();
  1374. ASSERT_FALSE(svr.is_running());
  1375. });
  1376. svr.wait_until_ready();
  1377. UploadFormDataItems items = {
  1378. {"zulu", "1", "", ""},
  1379. {"alpha", "2", "", ""},
  1380. {"mike", "3", "", ""},
  1381. {"zebra", "z", "z.txt", "text/plain"},
  1382. {"apple", "a", "a.txt", "text/plain"},
  1383. };
  1384. Client cli(HOST, port);
  1385. auto res = cli.Post("/order", items);
  1386. ASSERT_TRUE(res);
  1387. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1388. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1389. }
  1390. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1391. Server svr;
  1392. std::vector<std::string> values;
  1393. std::string first, second, out_of_range, order;
  1394. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1395. values = req.form.get_fields("tag");
  1396. first = req.form.get_field("tag", 0);
  1397. second = req.form.get_field("tag", 1);
  1398. out_of_range = req.form.get_field("tag", 2);
  1399. for (const auto &field : req.form.fields) {
  1400. order += field.first + "=" + field.second.content + " ";
  1401. }
  1402. res.set_content("ok", "text/plain");
  1403. });
  1404. auto port = svr.bind_to_any_port(HOST);
  1405. thread t = thread([&] { svr.listen_after_bind(); });
  1406. auto se = detail::scope_exit([&] {
  1407. svr.stop();
  1408. t.join();
  1409. ASSERT_FALSE(svr.is_running());
  1410. });
  1411. svr.wait_until_ready();
  1412. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1413. // not adjacent in the container.
  1414. UploadFormDataItems items = {
  1415. {"tag", "first", "", ""},
  1416. {"other", "x", "", ""},
  1417. {"tag", "second", "", ""},
  1418. };
  1419. Client cli(HOST, port);
  1420. auto res = cli.Post("/repeated", items);
  1421. ASSERT_TRUE(res);
  1422. ASSERT_EQ(2U, values.size());
  1423. EXPECT_EQ("first", values[0]);
  1424. EXPECT_EQ("second", values[1]);
  1425. EXPECT_EQ("first", first);
  1426. EXPECT_EQ("second", second);
  1427. // std::multimap already kept entries sharing a name in insertion order, so
  1428. // everything above passes without this change too. The whole traversal is
  1429. // what tells the two apart: sorting by name would hoist "other" to the front
  1430. // and the two "tag" parts would end up adjacent.
  1431. EXPECT_EQ("tag=first other=x tag=second ", order);
  1432. // Advancing past the last entry of a name used to run off the container;
  1433. // the container's saturating increment makes it return the default instead.
  1434. EXPECT_EQ("", out_of_range);
  1435. }
  1436. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1437. // Server::read_content() keeps a FormFields::iterator alive across the
  1438. // content callbacks that fill the part it points at. The container is
  1439. // vector-backed, so a later emplace can reallocate and invalidate an older
  1440. // iterator; 64 parts grow the vector through seven reallocations, which
  1441. // checks that every part's content still lands in its own entry.
  1442. const size_t part_count = 64;
  1443. // One formula for both the parts sent and the values expected back, so the
  1444. // two cannot drift apart.
  1445. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1446. auto content_of = [](size_t i) {
  1447. return std::string(64, static_cast<char>('a' + (i % 26)));
  1448. };
  1449. Server svr;
  1450. std::vector<std::pair<std::string, std::string>> received;
  1451. svr.Post("/many", [&](const Request &req, Response &res) {
  1452. for (const auto &field : req.form.fields) {
  1453. received.emplace_back(field.first, field.second.content);
  1454. }
  1455. res.set_content("ok", "text/plain");
  1456. });
  1457. auto port = svr.bind_to_any_port(HOST);
  1458. thread t = thread([&] { svr.listen_after_bind(); });
  1459. auto se = detail::scope_exit([&] {
  1460. svr.stop();
  1461. t.join();
  1462. ASSERT_FALSE(svr.is_running());
  1463. });
  1464. svr.wait_until_ready();
  1465. UploadFormDataItems items;
  1466. for (size_t i = 0; i < part_count; i++) {
  1467. items.push_back({name_of(i), content_of(i), "", ""});
  1468. }
  1469. Client cli(HOST, port);
  1470. auto res = cli.Post("/many", items);
  1471. ASSERT_TRUE(res);
  1472. ASSERT_EQ(part_count, received.size());
  1473. for (size_t i = 0; i < part_count; i++) {
  1474. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1475. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1476. }
  1477. }
  1478. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1479. string content_type = "multipart/form-data; boundary=something";
  1480. string boundary;
  1481. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1482. EXPECT_TRUE(ret);
  1483. EXPECT_EQ(boundary, "something");
  1484. }
  1485. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1486. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1487. string boundary;
  1488. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1489. EXPECT_TRUE(ret);
  1490. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1491. }
  1492. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1493. string content_type =
  1494. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1495. string boundary;
  1496. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1497. EXPECT_TRUE(ret);
  1498. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1499. }
  1500. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1501. string content_type =
  1502. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1503. string boundary;
  1504. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1505. EXPECT_TRUE(ret);
  1506. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1507. }
  1508. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1509. const string boundary(70, 'a');
  1510. string content_type = "multipart/form-data; boundary=" + boundary;
  1511. string parsed;
  1512. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1513. EXPECT_TRUE(ret);
  1514. EXPECT_EQ(parsed, boundary);
  1515. }
  1516. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1517. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1518. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1519. string parsed;
  1520. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1521. EXPECT_FALSE(ret);
  1522. }
  1523. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1524. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1525. // is 72 characters on the wire and still valid.
  1526. const string boundary(70, 'a');
  1527. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1528. string parsed;
  1529. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1530. EXPECT_EQ(parsed, boundary);
  1531. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1532. parsed.clear();
  1533. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1534. }
  1535. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1536. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1537. // The parameter parser must not treat that '=' as the key/value separator.
  1538. string content_type =
  1539. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1540. "charset=UTF-8";
  1541. string parsed;
  1542. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1543. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1544. }
  1545. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1546. // A ';' inside the quoted-string is part of the value, not a parameter
  1547. // separator, so it must not truncate the boundary.
  1548. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1549. string parsed;
  1550. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1551. EXPECT_EQ(parsed, "a;b");
  1552. }
  1553. TEST(ParseDispositionParamsTest, QuotedValues) {
  1554. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1555. // ';' and '=' are ordinary characters inside one.
  1556. struct {
  1557. const char *value;
  1558. std::vector<std::pair<const char *, const char *>> expected;
  1559. } cases[] = {
  1560. {"name=\"file1\"; filename=\"a.txt\"",
  1561. {{"name", "file1"}, {"filename", "a.txt"}}},
  1562. // Whitespace around '=' and ';' is still trimmed
  1563. {"name=\"file2\" ;filename = \"a.html\"",
  1564. {{"name", "file2"}, {"filename", "a.html"}}},
  1565. // '=' inside the value used to leave only the text after the last one
  1566. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1567. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1568. {"name=\"x=y\"", {{"name", "x=y"}}},
  1569. // ';' inside the value used to truncate the pair and leave a bogus one
  1570. {"name=\"file3\"; filename=\"a;b.txt\"",
  1571. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1572. // An unquoted value keeps working, and so does filename*
  1573. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1574. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1575. // A parameter with no key is dropped rather than turned into one whose
  1576. // key is the value
  1577. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1578. // An escaped quote does not end the value
  1579. {"name=\"a\\\"; filename=evil.php\"",
  1580. {{"name", "a\"; filename=evil.php"}}},
  1581. // Other backslashes, as in a Windows path, are kept
  1582. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1583. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1584. };
  1585. for (const auto &c : cases) {
  1586. Params params;
  1587. detail::parse_disposition_params(c.value, params);
  1588. for (const auto &kv : c.expected) {
  1589. auto it = params.find(kv.first);
  1590. ASSERT_NE(it, params.end())
  1591. << "value: " << c.value << ", key: " << kv.first;
  1592. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1593. }
  1594. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1595. }
  1596. }
  1597. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1598. Server svr;
  1599. std::string filename;
  1600. std::string content;
  1601. svr.Post("/upload", [&](const Request &req, Response &) {
  1602. const auto &file = req.form.get_file("file");
  1603. filename = file.filename;
  1604. content = file.content;
  1605. });
  1606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1607. auto se = detail::scope_exit([&] {
  1608. svr.stop();
  1609. thread.join();
  1610. ASSERT_FALSE(svr.is_running());
  1611. });
  1612. svr.wait_until_ready();
  1613. std::string body = "--B\r\n"
  1614. "Content-Disposition: form-data; name=\"file\"; "
  1615. "filename=\"a.txt\"\r\n"
  1616. "Content-Type: text/plain\r\n"
  1617. "\r\n"
  1618. "hello\r\n"
  1619. "--B--\r\n";
  1620. Client cli(HOST, PORT);
  1621. auto res = cli.Post(
  1622. "/upload",
  1623. [&](size_t offset, DataSink &sink) {
  1624. if (offset < body.size()) {
  1625. sink.write(&body[offset], 1);
  1626. } else {
  1627. sink.done();
  1628. }
  1629. return true;
  1630. },
  1631. "multipart/form-data; boundary=B");
  1632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1633. EXPECT_EQ(StatusCode::OK_200, res->status);
  1634. EXPECT_EQ("a.txt", filename);
  1635. EXPECT_EQ("hello", content);
  1636. }
  1637. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1638. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1639. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1640. Server svr;
  1641. std::string field_value, file_name, file_filename;
  1642. bool has_field = false, has_file = false;
  1643. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1644. has_field = req.form.has_field("x=y");
  1645. field_value = req.form.get_field("x=y");
  1646. has_file = req.form.has_file("file1");
  1647. const auto &file = req.form.get_file("file1");
  1648. file_name = file.name;
  1649. file_filename = file.filename;
  1650. res.set_content("ok", "text/plain");
  1651. });
  1652. auto port = svr.bind_to_any_port(HOST);
  1653. thread t = thread([&] { svr.listen_after_bind(); });
  1654. auto se = detail::scope_exit([&] {
  1655. svr.stop();
  1656. t.join();
  1657. ASSERT_FALSE(svr.is_running());
  1658. });
  1659. svr.wait_until_ready();
  1660. UploadFormDataItems items = {
  1661. {"x=y", "field-value", "", ""},
  1662. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1663. };
  1664. Client cli(HOST, port);
  1665. auto res = cli.Post("/quoted", items);
  1666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1667. ASSERT_EQ(StatusCode::OK_200, res->status);
  1668. EXPECT_TRUE(has_field);
  1669. EXPECT_EQ("field-value", field_value);
  1670. EXPECT_TRUE(has_file);
  1671. EXPECT_EQ("file1", file_name);
  1672. EXPECT_EQ("a;b=report.pdf", file_filename);
  1673. }
  1674. TEST(GetHeaderValueTest, DefaultValue) {
  1675. Headers headers = {{"Dummy", "Dummy"}};
  1676. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1677. EXPECT_STREQ("text/plain", val);
  1678. }
  1679. TEST(GetHeaderValueTest, DefaultValueInt) {
  1680. Headers headers = {{"Dummy", "Dummy"}};
  1681. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1682. EXPECT_EQ(100ull, val);
  1683. }
  1684. TEST(GetHeaderValueTest, RegularValue) {
  1685. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1686. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1687. EXPECT_STREQ("text/html", val);
  1688. }
  1689. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1690. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1691. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1692. EXPECT_STREQ("text/html", val);
  1693. }
  1694. TEST(GetHeaderValueTest, SetContent) {
  1695. Response res;
  1696. res.set_content("html", "text/html");
  1697. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1698. res.set_content("text", "text/plain");
  1699. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1700. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1701. }
  1702. TEST(GetHeaderValueTest, RegularValueInt) {
  1703. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1704. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1705. EXPECT_EQ(100ull, val);
  1706. }
  1707. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1708. Headers headers = {{"Content-Length", "x"}};
  1709. auto is_invalid_value = false;
  1710. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1711. is_invalid_value);
  1712. EXPECT_EQ(0ull, val);
  1713. EXPECT_TRUE(is_invalid_value);
  1714. }
  1715. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1716. // An all-digit value that overflows size_t must be reported as invalid, not
  1717. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1718. // a large length to a small one on 32-bit builds, leaving the framing length
  1719. // wrong while is_invalid_value stayed false.
  1720. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1721. auto is_invalid_value = false;
  1722. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1723. is_invalid_value);
  1724. EXPECT_TRUE(is_invalid_value);
  1725. // A well-formed length is unaffected.
  1726. Headers ok = {{"Content-Length", "1234"}};
  1727. is_invalid_value = false;
  1728. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1729. is_invalid_value);
  1730. EXPECT_EQ(1234ull, val);
  1731. EXPECT_FALSE(is_invalid_value);
  1732. }
  1733. TEST(GetHeaderValueTest, Range) {
  1734. {
  1735. Headers headers = {make_range_header({{1, -1}})};
  1736. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1737. EXPECT_STREQ("bytes=1-", val);
  1738. }
  1739. {
  1740. Headers headers = {make_range_header({{-1, 1}})};
  1741. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1742. EXPECT_STREQ("bytes=-1", val);
  1743. }
  1744. {
  1745. Headers headers = {make_range_header({{1, 10}})};
  1746. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1747. EXPECT_STREQ("bytes=1-10", val);
  1748. }
  1749. {
  1750. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1751. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1752. EXPECT_STREQ("bytes=1-10, 100-", val);
  1753. }
  1754. {
  1755. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1756. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1757. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1758. }
  1759. {
  1760. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1761. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1762. EXPECT_STREQ("bytes=0-0, -1", val);
  1763. }
  1764. }
  1765. TEST(BearerTokenAuthTest, SchemeValidation) {
  1766. // A value shorter than "Bearer " must not throw from the fixed-length
  1767. // substr, and a non-Bearer scheme must not be reported as a token.
  1768. struct {
  1769. const char *value;
  1770. const char *expected;
  1771. } cases[] = {
  1772. {"x", ""},
  1773. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1774. {"Bearer abc123", "abc123"},
  1775. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1776. };
  1777. for (const auto &c : cases) {
  1778. Request req;
  1779. req.set_header("Authorization", c.value);
  1780. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1781. }
  1782. }
  1783. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1784. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1785. // to depend on the standard library (libstdc++ handed back duplicates in
  1786. // reverse insertion order, libc++ in insertion order).
  1787. Request req;
  1788. req.set_header("Accept-Encoding", "gzip");
  1789. req.set_header("Accept-Encoding", "deflate");
  1790. req.set_header("Accept-Encoding", "br");
  1791. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1792. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1793. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1794. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1795. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1796. }
  1797. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1798. Request req;
  1799. req.set_header("X-Test", "only");
  1800. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1801. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1802. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1803. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1804. }
  1805. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1806. Request req;
  1807. req.set_header("X-First", "1");
  1808. req.set_header("X-Test", "2");
  1809. req.params.emplace("first", "1");
  1810. req.params.emplace("test", "2");
  1811. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1812. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1813. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1814. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1815. // The second one is negative when read as a signed value
  1816. const auto max_id = (std::numeric_limits<size_t>::max)();
  1817. for (auto id : {max_id / 2, max_id}) {
  1818. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1819. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1820. EXPECT_EQ("", req.get_param_value("test", id));
  1821. EXPECT_EQ("", req.form.get_field("test", id));
  1822. EXPECT_EQ("", req.form.get_file("test", id).content);
  1823. }
  1824. }
  1825. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1826. Headers headers;
  1827. headers.emplace("Host", "example.com");
  1828. headers.emplace("Accept-Encoding", "gzip");
  1829. headers.emplace("User-Agent", "test");
  1830. headers.emplace("Accept-Encoding", "deflate");
  1831. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1832. "Accept-Encoding=deflate ",
  1833. entries_to_string(headers));
  1834. }
  1835. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1836. Headers headers = {{"Content-Type", "text/html"},
  1837. {"CONTENT-TYPE", "text/xml"}};
  1838. EXPECT_EQ(2U, headers.count("content-type"));
  1839. auto it = headers.find("content-type");
  1840. ASSERT_TRUE(it != headers.end());
  1841. EXPECT_EQ("text/html", it->second);
  1842. }
  1843. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1844. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1845. // drop only those fields and leave everything positioned between them.
  1846. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1847. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1848. auto rng = headers.equal_range("a");
  1849. headers.erase(rng.first, rng.second);
  1850. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1851. }
  1852. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1853. Headers headers = {
  1854. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1855. EXPECT_EQ(3U, headers.erase("A"));
  1856. EXPECT_EQ(0U, headers.count("A"));
  1857. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1858. }
  1859. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1860. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1861. headers.emplace_front("Host", "example.com");
  1862. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1863. entries_to_string(headers));
  1864. }
  1865. TEST(ParseHeaderValueTest, Range) {
  1866. {
  1867. Ranges ranges;
  1868. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1869. EXPECT_TRUE(ret);
  1870. EXPECT_EQ(1u, ranges.size());
  1871. EXPECT_EQ(1u, ranges[0].first);
  1872. EXPECT_EQ(-1, ranges[0].second);
  1873. }
  1874. {
  1875. Ranges ranges;
  1876. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1877. EXPECT_TRUE(ret);
  1878. EXPECT_EQ(1u, ranges.size());
  1879. EXPECT_EQ(-1, ranges[0].first);
  1880. EXPECT_EQ(1u, ranges[0].second);
  1881. }
  1882. {
  1883. Ranges ranges;
  1884. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1885. EXPECT_TRUE(ret);
  1886. EXPECT_EQ(1u, ranges.size());
  1887. EXPECT_EQ(1u, ranges[0].first);
  1888. EXPECT_EQ(10u, ranges[0].second);
  1889. }
  1890. {
  1891. Ranges ranges;
  1892. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1893. EXPECT_FALSE(ret);
  1894. }
  1895. {
  1896. Ranges ranges;
  1897. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1898. EXPECT_TRUE(ret);
  1899. EXPECT_EQ(2u, ranges.size());
  1900. EXPECT_EQ(1u, ranges[0].first);
  1901. EXPECT_EQ(10u, ranges[0].second);
  1902. EXPECT_EQ(100u, ranges[1].first);
  1903. EXPECT_EQ(-1, ranges[1].second);
  1904. }
  1905. {
  1906. Ranges ranges;
  1907. auto ret =
  1908. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1909. EXPECT_TRUE(ret);
  1910. EXPECT_EQ(3u, ranges.size());
  1911. EXPECT_EQ(1u, ranges[0].first);
  1912. EXPECT_EQ(10u, ranges[0].second);
  1913. EXPECT_EQ(100u, ranges[1].first);
  1914. EXPECT_EQ(200u, ranges[1].second);
  1915. EXPECT_EQ(300u, ranges[2].first);
  1916. EXPECT_EQ(400u, ranges[2].second);
  1917. }
  1918. {
  1919. Ranges ranges;
  1920. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1921. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1922. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1923. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1924. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1925. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1926. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1927. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1928. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1929. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1930. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1931. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1932. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1933. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1934. EXPECT_FALSE(
  1935. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1936. EXPECT_TRUE(ranges.empty());
  1937. }
  1938. {
  1939. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1940. // remainder of the representation, so it stays accepted.
  1941. Ranges ranges;
  1942. auto ret =
  1943. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1944. EXPECT_TRUE(ret);
  1945. ASSERT_EQ(1u, ranges.size());
  1946. EXPECT_EQ(0, ranges[0].first);
  1947. EXPECT_EQ(-1, ranges[0].second);
  1948. }
  1949. // RFC 9110 14.1: range unit names are case-insensitive.
  1950. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1951. Ranges ranges;
  1952. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1953. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1954. }
  1955. }
  1956. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1957. Request req;
  1958. req.set_header("Accept-Encoding", "gzip");
  1959. Response res;
  1960. res.set_header("Content-Type", "text/plain");
  1961. auto ret = detail::encoding_type(req, res);
  1962. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1963. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1964. #else
  1965. EXPECT_TRUE(ret == detail::EncodingType::None);
  1966. #endif
  1967. }
  1968. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1969. Request req;
  1970. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1971. Response res;
  1972. res.set_header("Content-Type", "text/plain");
  1973. auto ret = detail::encoding_type(req, res);
  1974. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1975. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1976. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1977. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1978. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1979. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1980. #else
  1981. EXPECT_TRUE(ret == detail::EncodingType::None);
  1982. #endif
  1983. }
  1984. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1985. Request req;
  1986. req.set_header("Accept-Encoding",
  1987. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1988. Response res;
  1989. res.set_header("Content-Type", "text/plain");
  1990. auto ret = detail::encoding_type(req, res);
  1991. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1992. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1993. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1994. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1995. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1996. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1997. #else
  1998. EXPECT_TRUE(ret == detail::EncodingType::None);
  1999. #endif
  2000. }
  2001. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2002. // All supported encodings rejected with q=0 should return None
  2003. Request req;
  2004. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2005. Response res;
  2006. res.set_header("Content-Type", "text/plain");
  2007. auto ret = detail::encoding_type(req, res);
  2008. EXPECT_TRUE(ret == detail::EncodingType::None);
  2009. }
  2010. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2011. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2012. Request req;
  2013. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2014. Response res;
  2015. res.set_header("Content-Type", "text/plain");
  2016. auto ret = detail::encoding_type(req, res);
  2017. EXPECT_TRUE(ret == detail::EncodingType::None);
  2018. }
  2019. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2020. Request req;
  2021. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2022. Response res;
  2023. res.set_header("Content-Type", "text/plain");
  2024. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2025. }
  2026. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2027. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2028. Request req;
  2029. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2030. Response res;
  2031. res.set_header("Content-Type", "text/plain");
  2032. auto ret = detail::encoding_type(req, res);
  2033. EXPECT_TRUE(ret == detail::EncodingType::None);
  2034. }
  2035. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2036. // RFC 7231: Accept-Encoding values are case-insensitive
  2037. Request req;
  2038. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2039. Response res;
  2040. res.set_header("Content-Type", "text/plain");
  2041. auto ret = detail::encoding_type(req, res);
  2042. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2043. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2044. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2045. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2046. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2047. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2048. #else
  2049. EXPECT_TRUE(ret == detail::EncodingType::None);
  2050. #endif
  2051. }
  2052. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2053. // q value should determine priority, not hardcoded order
  2054. Request req;
  2055. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2056. Response res;
  2057. res.set_header("Content-Type", "text/plain");
  2058. auto ret = detail::encoding_type(req, res);
  2059. // gzip has highest q=1.0, so it should be selected even though
  2060. // br and zstd are also supported
  2061. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2062. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2063. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2065. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2066. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2067. #else
  2068. EXPECT_TRUE(ret == detail::EncodingType::None);
  2069. #endif
  2070. }
  2071. TEST(BufferStreamTest, read) {
  2072. detail::BufferStream strm1;
  2073. Stream &strm = strm1;
  2074. EXPECT_EQ(5, strm.write("hello"));
  2075. char buf[512];
  2076. EXPECT_EQ(2, strm.read(buf, 2));
  2077. EXPECT_EQ('h', buf[0]);
  2078. EXPECT_EQ('e', buf[1]);
  2079. EXPECT_EQ(2, strm.read(buf, 2));
  2080. EXPECT_EQ('l', buf[0]);
  2081. EXPECT_EQ('l', buf[1]);
  2082. EXPECT_EQ(1, strm.read(buf, 1));
  2083. EXPECT_EQ('o', buf[0]);
  2084. EXPECT_EQ(0, strm.read(buf, 1));
  2085. }
  2086. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2087. auto host = "www.httpwatch.com";
  2088. auto ip = hosted_at(host);
  2089. EXPECT_EQ("23.96.13.243", ip);
  2090. std::vector<std::string> addrs;
  2091. hosted_at(host, addrs);
  2092. EXPECT_EQ(1u, addrs.size());
  2093. }
  2094. #if 0 // It depends on each test environment...
  2095. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2096. auto host = "www.youtube.com";
  2097. std::vector<std::string> addrs;
  2098. hosted_at(host, addrs);
  2099. EXPECT_EQ(20u, addrs.size());
  2100. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2101. EXPECT_TRUE(it != addrs.end());
  2102. }
  2103. #endif
  2104. class ChunkedEncodingTest : public ::testing::Test {
  2105. protected:
  2106. ChunkedEncodingTest()
  2107. : cli_(HOST, PORT)
  2108. #ifdef CPPHTTPLIB_SSL_ENABLED
  2109. ,
  2110. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2111. #endif
  2112. {
  2113. cli_.set_connection_timeout(2);
  2114. #ifdef CPPHTTPLIB_SSL_ENABLED
  2115. cli_.enable_server_certificate_verification(false);
  2116. #endif
  2117. }
  2118. virtual void SetUp() {
  2119. read_file("./image.jpg", image_data_);
  2120. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2121. res.set_content("Hello World!", "text/plain");
  2122. });
  2123. svr_.Get(
  2124. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2125. res.set_chunked_content_provider(
  2126. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2127. size_t remaining = image_data_.size() - offset;
  2128. if (remaining == 0) {
  2129. sink.done();
  2130. } else {
  2131. constexpr size_t CHUNK_SIZE = 1024;
  2132. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2133. sink.write(&image_data_[offset], send_size);
  2134. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2135. }
  2136. return true;
  2137. });
  2138. });
  2139. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2140. svr_.wait_until_ready();
  2141. }
  2142. virtual void TearDown() {
  2143. svr_.stop();
  2144. if (!request_threads_.empty()) {
  2145. std::this_thread::sleep_for(std::chrono::seconds(1));
  2146. for (auto &t : request_threads_) {
  2147. t.join();
  2148. }
  2149. }
  2150. t_.join();
  2151. }
  2152. #ifdef CPPHTTPLIB_SSL_ENABLED
  2153. SSLClient cli_;
  2154. SSLServer svr_;
  2155. #else
  2156. Client cli_;
  2157. Server svr_;
  2158. #endif
  2159. thread t_;
  2160. std::vector<thread> request_threads_;
  2161. std::string image_data_;
  2162. };
  2163. TEST_F(ChunkedEncodingTest, NormalGet) {
  2164. auto res = cli_.Get("/chunked");
  2165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2166. std::string out;
  2167. read_file("./image.jpg", out);
  2168. EXPECT_EQ(StatusCode::OK_200, res->status);
  2169. EXPECT_EQ(out, res->body);
  2170. }
  2171. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2172. std::string body;
  2173. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2174. body.append(data, data_length);
  2175. return true;
  2176. });
  2177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2178. std::string out;
  2179. read_file("./image.jpg", out);
  2180. EXPECT_EQ(StatusCode::OK_200, res->status);
  2181. EXPECT_EQ(out, body);
  2182. }
  2183. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2184. std::string body;
  2185. auto res = cli_.Get(
  2186. "/chunked",
  2187. [&](const Response &response) {
  2188. EXPECT_EQ(StatusCode::OK_200, response.status);
  2189. return true;
  2190. },
  2191. [&](const char *data, size_t data_length) {
  2192. body.append(data, data_length);
  2193. return true;
  2194. });
  2195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2196. std::string out;
  2197. read_file("./image.jpg", out);
  2198. EXPECT_EQ(StatusCode::OK_200, res->status);
  2199. EXPECT_EQ(out, body);
  2200. }
  2201. TEST(RangeTest, FromHTTPBin_Online) {
  2202. auto host = "httpbingo.org";
  2203. auto path = std::string{"/range/32"};
  2204. #ifdef CPPHTTPLIB_SSL_ENABLED
  2205. auto port = 443;
  2206. SSLClient cli(host, port);
  2207. #else
  2208. auto port = 80;
  2209. Client cli(host, port);
  2210. #endif
  2211. cli.set_connection_timeout(5);
  2212. {
  2213. auto res = cli.Get(path);
  2214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2215. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2216. EXPECT_EQ(StatusCode::OK_200, res->status);
  2217. }
  2218. {
  2219. Headers headers = {make_range_header({{1, -1}})};
  2220. auto res = cli.Get(path, headers);
  2221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2222. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2223. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2224. }
  2225. {
  2226. Headers headers = {make_range_header({{1, 10}})};
  2227. auto res = cli.Get(path, headers);
  2228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2229. EXPECT_EQ("bcdefghijk", res->body);
  2230. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2231. }
  2232. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2233. // entire resource, while the original httpbin returned 200. Both are
  2234. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2235. {
  2236. Headers headers = {make_range_header({{0, 31}})};
  2237. auto res = cli.Get(path, headers);
  2238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2239. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2240. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2241. res->status == StatusCode::PartialContent_206);
  2242. }
  2243. {
  2244. Headers headers = {make_range_header({{0, -1}})};
  2245. auto res = cli.Get(path, headers);
  2246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2247. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2248. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2249. res->status == StatusCode::PartialContent_206);
  2250. }
  2251. // go-httpbin returns 206 with clamped range for over-range requests,
  2252. // while the original httpbin returned 416. Both behaviors are observed
  2253. // in real servers, so we only verify the request succeeds.
  2254. {
  2255. Headers headers = {make_range_header({{0, 32}})};
  2256. auto res = cli.Get(path, headers);
  2257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2258. }
  2259. }
  2260. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2261. auto host = "unresolvableaddress.local";
  2262. auto path = std::string{"/"};
  2263. #ifdef CPPHTTPLIB_SSL_ENABLED
  2264. auto port = 443;
  2265. SSLClient cli(host, port);
  2266. #else
  2267. auto port = 80;
  2268. Client cli(host, port);
  2269. #endif
  2270. cli.set_connection_timeout(1);
  2271. {
  2272. auto res = cli.Get(path);
  2273. ASSERT_FALSE(res);
  2274. }
  2275. std::this_thread::sleep_for(std::chrono::seconds(8));
  2276. }
  2277. #if defined(__linux__) && defined(__GLIBC__) && \
  2278. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2279. // Forward declaration: in split builds split.py strips `inline` and moves the
  2280. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2281. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2282. // against the symbol in both header-only and split builds.
  2283. namespace httplib {
  2284. namespace detail {
  2285. int getaddrinfo_with_timeout(const char *node, const char *service,
  2286. const struct addrinfo *hints,
  2287. struct addrinfo **res, time_t timeout_sec);
  2288. } // namespace detail
  2289. } // namespace httplib
  2290. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2291. //
  2292. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2293. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2294. // gai_suspend() call hits the connection timeout the function calls
  2295. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2296. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2297. // still alive and still references the now-destroyed stack frame.
  2298. //
  2299. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2300. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2301. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2302. // and runs them in a container.
  2303. namespace {
  2304. bool should_run_issue_2431_tests() {
  2305. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2306. return v && *v && std::string(v) != "0";
  2307. }
  2308. std::string unique_unresolvable_host(int n) {
  2309. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2310. // glibc still asks the configured nameserver — which is exactly the path
  2311. // we want to exercise. A unique label per call avoids the resolver cache.
  2312. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2313. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2314. std::to_string(n) + ".invalid";
  2315. }
  2316. } // namespace
  2317. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2318. if (!should_run_issue_2431_tests()) {
  2319. GTEST_SKIP()
  2320. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2321. }
  2322. for (int i = 0; i < 8; ++i) {
  2323. struct addrinfo hints;
  2324. memset(&hints, 0, sizeof(hints));
  2325. hints.ai_family = AF_UNSPEC;
  2326. hints.ai_socktype = SOCK_STREAM;
  2327. auto host = unique_unresolvable_host(i);
  2328. struct addrinfo *result = nullptr;
  2329. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2330. &result, /*timeout_sec=*/1);
  2331. if (rc == 0 && result) { freeaddrinfo(result); }
  2332. }
  2333. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2334. // stack region they still believe holds their gaicb.
  2335. std::this_thread::sleep_for(std::chrono::seconds(3));
  2336. }
  2337. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2338. if (!should_run_issue_2431_tests()) {
  2339. GTEST_SKIP()
  2340. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2341. }
  2342. std::atomic<bool> stop{false};
  2343. std::vector<std::thread> threads;
  2344. for (int t = 0; t < 8; ++t) {
  2345. threads.emplace_back([t, &stop] {
  2346. int i = 0;
  2347. while (!stop.load(std::memory_order_relaxed)) {
  2348. struct addrinfo hints;
  2349. memset(&hints, 0, sizeof(hints));
  2350. hints.ai_family = AF_UNSPEC;
  2351. hints.ai_socktype = SOCK_STREAM;
  2352. auto host = unique_unresolvable_host(t * 100000 + i++);
  2353. struct addrinfo *result = nullptr;
  2354. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2355. &result, /*timeout_sec=*/1);
  2356. if (rc == 0 && result) { freeaddrinfo(result); }
  2357. }
  2358. });
  2359. }
  2360. std::this_thread::sleep_for(std::chrono::seconds(8));
  2361. stop.store(true, std::memory_order_relaxed);
  2362. for (auto &th : threads) {
  2363. th.join();
  2364. }
  2365. std::this_thread::sleep_for(std::chrono::seconds(3));
  2366. }
  2367. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2368. if (!should_run_issue_2431_tests()) {
  2369. GTEST_SKIP()
  2370. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2371. }
  2372. std::atomic<bool> stop{false};
  2373. std::vector<std::thread> threads;
  2374. for (int t = 0; t < 8; ++t) {
  2375. threads.emplace_back([t, &stop] {
  2376. int i = 0;
  2377. while (!stop.load(std::memory_order_relaxed)) {
  2378. auto host = unique_unresolvable_host(t * 100000 + i++);
  2379. Client cli(host, 80);
  2380. cli.set_connection_timeout(1, 0);
  2381. cli.set_read_timeout(1, 0);
  2382. cli.set_write_timeout(1, 0);
  2383. (void)cli.Get("/");
  2384. }
  2385. });
  2386. }
  2387. std::this_thread::sleep_for(std::chrono::seconds(8));
  2388. stop.store(true, std::memory_order_relaxed);
  2389. for (auto &th : threads) {
  2390. th.join();
  2391. }
  2392. std::this_thread::sleep_for(std::chrono::seconds(3));
  2393. }
  2394. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2395. TEST(ConnectionErrorTest, InvalidHost) {
  2396. auto host = "-abcde.com";
  2397. #ifdef CPPHTTPLIB_SSL_ENABLED
  2398. auto port = 443;
  2399. SSLClient cli(host, port);
  2400. #else
  2401. auto port = 80;
  2402. Client cli(host, port);
  2403. #endif
  2404. cli.set_connection_timeout(std::chrono::seconds(2));
  2405. auto res = cli.Get("/");
  2406. ASSERT_TRUE(!res);
  2407. EXPECT_EQ(Error::Connection, res.error());
  2408. }
  2409. TEST(ConnectionErrorTest, InvalidHost2) {
  2410. auto host = "httpcan.org/";
  2411. #ifdef CPPHTTPLIB_SSL_ENABLED
  2412. SSLClient cli(host);
  2413. #else
  2414. Client cli(host);
  2415. #endif
  2416. cli.set_connection_timeout(std::chrono::seconds(2));
  2417. auto res = cli.Get("/");
  2418. ASSERT_TRUE(!res);
  2419. EXPECT_EQ(Error::Connection, res.error());
  2420. }
  2421. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2422. auto host = "httpcan.org/";
  2423. #ifdef CPPHTTPLIB_SSL_ENABLED
  2424. SSLClient cli(host);
  2425. #else
  2426. Client cli(host);
  2427. #endif
  2428. cli.set_connection_timeout(std::chrono::seconds(2));
  2429. auto res = cli.Get("/");
  2430. ASSERT_TRUE(!res);
  2431. stringstream s;
  2432. s << "error code: " << res.error();
  2433. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2434. }
  2435. TEST(ConnectionErrorTest, InvalidPort) {
  2436. auto host = "localhost";
  2437. auto port = 44380;
  2438. #ifdef CPPHTTPLIB_SSL_ENABLED
  2439. SSLClient cli(host, port);
  2440. #else
  2441. Client cli(host, port);
  2442. #endif
  2443. cli.set_connection_timeout(std::chrono::seconds(2));
  2444. auto res = cli.Get("/");
  2445. ASSERT_TRUE(!res);
  2446. EXPECT_TRUE(Error::Connection == res.error() ||
  2447. Error::ConnectionTimeout == res.error());
  2448. }
  2449. TEST(ConnectionErrorTest, Timeout_Online) {
  2450. auto host = "google.com";
  2451. #ifdef CPPHTTPLIB_SSL_ENABLED
  2452. auto port = 44380;
  2453. SSLClient cli(host, port);
  2454. #else
  2455. auto port = 8080;
  2456. Client cli(host, port);
  2457. #endif
  2458. cli.set_connection_timeout(std::chrono::seconds(2));
  2459. // only probe one address type so that the error reason
  2460. // correlates to the timed-out IPv4, not the unsupported
  2461. // IPv6 connection attempt
  2462. cli.set_address_family(AF_INET);
  2463. auto res = cli.Get("/");
  2464. ASSERT_TRUE(!res);
  2465. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2466. }
  2467. TEST(CancelTest, NoCancel_Online) {
  2468. auto host = "httpbingo.org";
  2469. auto path = std::string{"/range/32"};
  2470. #ifdef CPPHTTPLIB_SSL_ENABLED
  2471. auto port = 443;
  2472. SSLClient cli(host, port);
  2473. #else
  2474. auto port = 80;
  2475. Client cli(host, port);
  2476. #endif
  2477. cli.set_connection_timeout(std::chrono::seconds(5));
  2478. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2480. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2481. EXPECT_EQ(StatusCode::OK_200, res->status);
  2482. }
  2483. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2484. // Use /bytes with a large payload so that the DownloadProgress callback
  2485. // (which only fires for Content-Length responses) is invoked before the
  2486. // entire body is received, giving cancellation a chance to fire.
  2487. auto host = "httpbingo.org";
  2488. auto path = std::string{"/bytes/524288"};
  2489. #ifdef CPPHTTPLIB_SSL_ENABLED
  2490. auto port = 443;
  2491. SSLClient cli(host, port);
  2492. #else
  2493. auto port = 80;
  2494. Client cli(host, port);
  2495. #endif
  2496. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2497. cli.set_connection_timeout(std::chrono::seconds(5));
  2498. ASSERT_TRUE(!res);
  2499. EXPECT_EQ(Error::Canceled, res.error());
  2500. }
  2501. TEST(CancelTest, WithCancelLargePayload_Online) {
  2502. auto host = "httpbingo.org";
  2503. auto path = std::string{"/bytes/524288"};
  2504. #ifdef CPPHTTPLIB_SSL_ENABLED
  2505. auto port = 443;
  2506. SSLClient cli(host, port);
  2507. #else
  2508. auto port = 80;
  2509. Client cli(host, port);
  2510. #endif
  2511. cli.set_connection_timeout(std::chrono::seconds(5));
  2512. uint32_t count = 0;
  2513. auto res =
  2514. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2515. ASSERT_TRUE(!res);
  2516. EXPECT_EQ(Error::Canceled, res.error());
  2517. }
  2518. TEST(CancelTest, NoCancelPost) {
  2519. Server svr;
  2520. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2521. res.set_content("Hello World!", "text/plain");
  2522. });
  2523. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2524. auto se = detail::scope_exit([&] {
  2525. svr.stop();
  2526. thread.join();
  2527. ASSERT_FALSE(svr.is_running());
  2528. });
  2529. svr.wait_until_ready();
  2530. Client cli(HOST, PORT);
  2531. cli.set_connection_timeout(std::chrono::seconds(5));
  2532. auto res =
  2533. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2534. "application/json", [](uint64_t, uint64_t) { return true; });
  2535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2536. EXPECT_EQ("Hello World!", res->body);
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. }
  2539. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2540. Server svr;
  2541. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2542. res.set_content("Hello World!", "text/plain");
  2543. });
  2544. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2545. auto se = detail::scope_exit([&] {
  2546. svr.stop();
  2547. thread.join();
  2548. ASSERT_FALSE(svr.is_running());
  2549. });
  2550. svr.wait_until_ready();
  2551. Client cli(HOST, PORT);
  2552. cli.set_connection_timeout(std::chrono::seconds(5));
  2553. auto res =
  2554. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2555. "application/json", [](uint64_t, uint64_t) { return false; });
  2556. ASSERT_TRUE(!res);
  2557. EXPECT_EQ(Error::Canceled, res.error());
  2558. }
  2559. TEST(CancelTest, WithCancelLargePayloadPost) {
  2560. Server svr;
  2561. svr.set_payload_max_length(200 * 1024 * 1024);
  2562. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2563. res.set_content(LARGE_DATA, "text/plain");
  2564. });
  2565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2566. auto se = detail::scope_exit([&] {
  2567. svr.stop();
  2568. thread.join();
  2569. ASSERT_FALSE(svr.is_running());
  2570. });
  2571. svr.wait_until_ready();
  2572. Client cli(HOST, PORT);
  2573. cli.set_payload_max_length(200 * 1024 * 1024);
  2574. cli.set_connection_timeout(std::chrono::seconds(5));
  2575. auto res =
  2576. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2577. "application/json", [](uint64_t, uint64_t) { return false; });
  2578. ASSERT_TRUE(!res);
  2579. EXPECT_EQ(Error::Canceled, res.error());
  2580. }
  2581. TEST(CancelTest, NoCancelPut) {
  2582. Server svr;
  2583. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2584. res.set_content("Hello World!", "text/plain");
  2585. });
  2586. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2587. auto se = detail::scope_exit([&] {
  2588. svr.stop();
  2589. thread.join();
  2590. ASSERT_FALSE(svr.is_running());
  2591. });
  2592. svr.wait_until_ready();
  2593. Client cli(HOST, PORT);
  2594. cli.set_connection_timeout(std::chrono::seconds(5));
  2595. auto res =
  2596. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2597. "application/json", [](uint64_t, uint64_t) { return true; });
  2598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2599. EXPECT_EQ("Hello World!", res->body);
  2600. EXPECT_EQ(StatusCode::OK_200, res->status);
  2601. }
  2602. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2603. Server svr;
  2604. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2605. res.set_content("Hello World!", "text/plain");
  2606. });
  2607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2608. auto se = detail::scope_exit([&] {
  2609. svr.stop();
  2610. thread.join();
  2611. ASSERT_FALSE(svr.is_running());
  2612. });
  2613. svr.wait_until_ready();
  2614. Client cli(HOST, PORT);
  2615. cli.set_connection_timeout(std::chrono::seconds(5));
  2616. auto res =
  2617. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2618. "application/json", [](uint64_t, uint64_t) { return false; });
  2619. ASSERT_TRUE(!res);
  2620. EXPECT_EQ(Error::Canceled, res.error());
  2621. }
  2622. TEST(CancelTest, WithCancelLargePayloadPut) {
  2623. Server svr;
  2624. svr.set_payload_max_length(200 * 1024 * 1024);
  2625. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2626. res.set_content(LARGE_DATA, "text/plain");
  2627. });
  2628. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2629. auto se = detail::scope_exit([&] {
  2630. svr.stop();
  2631. thread.join();
  2632. ASSERT_FALSE(svr.is_running());
  2633. });
  2634. svr.wait_until_ready();
  2635. Client cli(HOST, PORT);
  2636. cli.set_payload_max_length(200 * 1024 * 1024);
  2637. cli.set_connection_timeout(std::chrono::seconds(5));
  2638. auto res =
  2639. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2640. "application/json", [](uint64_t, uint64_t) { return false; });
  2641. ASSERT_TRUE(!res);
  2642. EXPECT_EQ(Error::Canceled, res.error());
  2643. }
  2644. TEST(CancelTest, NoCancelPatch) {
  2645. Server svr;
  2646. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2647. res.set_content("Hello World!", "text/plain");
  2648. });
  2649. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2650. auto se = detail::scope_exit([&] {
  2651. svr.stop();
  2652. thread.join();
  2653. ASSERT_FALSE(svr.is_running());
  2654. });
  2655. svr.wait_until_ready();
  2656. Client cli(HOST, PORT);
  2657. cli.set_connection_timeout(std::chrono::seconds(5));
  2658. auto res =
  2659. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2660. "application/json", [](uint64_t, uint64_t) { return true; });
  2661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2662. EXPECT_EQ("Hello World!", res->body);
  2663. EXPECT_EQ(StatusCode::OK_200, res->status);
  2664. }
  2665. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2666. Server svr;
  2667. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2668. res.set_content("Hello World!", "text/plain");
  2669. });
  2670. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2671. auto se = detail::scope_exit([&] {
  2672. svr.stop();
  2673. thread.join();
  2674. ASSERT_FALSE(svr.is_running());
  2675. });
  2676. svr.wait_until_ready();
  2677. Client cli(HOST, PORT);
  2678. cli.set_connection_timeout(std::chrono::seconds(5));
  2679. auto res =
  2680. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2681. "application/json", [](uint64_t, uint64_t) { return false; });
  2682. ASSERT_TRUE(!res);
  2683. EXPECT_EQ(Error::Canceled, res.error());
  2684. }
  2685. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2686. Server svr;
  2687. svr.set_payload_max_length(200 * 1024 * 1024);
  2688. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2689. res.set_content(LARGE_DATA, "text/plain");
  2690. });
  2691. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2692. auto se = detail::scope_exit([&] {
  2693. svr.stop();
  2694. thread.join();
  2695. ASSERT_FALSE(svr.is_running());
  2696. });
  2697. svr.wait_until_ready();
  2698. Client cli(HOST, PORT);
  2699. cli.set_payload_max_length(200 * 1024 * 1024);
  2700. cli.set_connection_timeout(std::chrono::seconds(5));
  2701. auto res =
  2702. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2703. "application/json", [](uint64_t, uint64_t) { return false; });
  2704. ASSERT_TRUE(!res);
  2705. EXPECT_EQ(Error::Canceled, res.error());
  2706. }
  2707. TEST(CancelTest, NoCancelDelete) {
  2708. Server svr;
  2709. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2710. res.set_content("Hello World!", "text/plain");
  2711. });
  2712. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2713. auto se = detail::scope_exit([&] {
  2714. svr.stop();
  2715. thread.join();
  2716. ASSERT_FALSE(svr.is_running());
  2717. });
  2718. svr.wait_until_ready();
  2719. Client cli(HOST, PORT);
  2720. cli.set_connection_timeout(std::chrono::seconds(5));
  2721. auto res =
  2722. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2723. "application/json", [](uint64_t, uint64_t) { return true; });
  2724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2725. EXPECT_EQ("Hello World!", res->body);
  2726. EXPECT_EQ(StatusCode::OK_200, res->status);
  2727. }
  2728. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2729. Server svr;
  2730. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2731. res.set_content("Hello World!", "text/plain");
  2732. });
  2733. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2734. auto se = detail::scope_exit([&] {
  2735. svr.stop();
  2736. thread.join();
  2737. ASSERT_FALSE(svr.is_running());
  2738. });
  2739. svr.wait_until_ready();
  2740. Client cli(HOST, PORT);
  2741. cli.set_connection_timeout(std::chrono::seconds(5));
  2742. auto res =
  2743. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2744. "application/json", [](uint64_t, uint64_t) { return false; });
  2745. ASSERT_TRUE(!res);
  2746. EXPECT_EQ(Error::Canceled, res.error());
  2747. }
  2748. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2749. Server svr;
  2750. svr.set_payload_max_length(200 * 1024 * 1024);
  2751. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2752. res.set_content(LARGE_DATA, "text/plain");
  2753. });
  2754. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2755. auto se = detail::scope_exit([&] {
  2756. svr.stop();
  2757. thread.join();
  2758. ASSERT_FALSE(svr.is_running());
  2759. });
  2760. svr.wait_until_ready();
  2761. Client cli(HOST, PORT);
  2762. cli.set_payload_max_length(200 * 1024 * 1024);
  2763. cli.set_connection_timeout(std::chrono::seconds(5));
  2764. auto res =
  2765. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2766. "application/json", [](uint64_t, uint64_t) { return false; });
  2767. ASSERT_TRUE(!res);
  2768. EXPECT_EQ(Error::Canceled, res.error());
  2769. }
  2770. static std::string remove_whitespace(const std::string &input) {
  2771. std::string output;
  2772. output.reserve(input.size());
  2773. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2774. [](unsigned char c) { return !std::isspace(c); });
  2775. return output;
  2776. }
  2777. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2778. auto host = "httpbingo.org";
  2779. auto path = std::string{"/basic-auth/hello/world"};
  2780. #ifdef CPPHTTPLIB_SSL_ENABLED
  2781. auto port = 443;
  2782. SSLClient cli(host, port);
  2783. #else
  2784. auto port = 80;
  2785. Client cli(host, port);
  2786. #endif
  2787. {
  2788. auto res = cli.Get(path);
  2789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2790. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2791. }
  2792. {
  2793. auto res = cli.Get(
  2794. path, Headers{make_basic_authentication_header("hello", "world")});
  2795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2796. auto body = remove_whitespace(res->body);
  2797. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2798. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2799. EXPECT_EQ(StatusCode::OK_200, res->status);
  2800. }
  2801. {
  2802. cli.set_basic_auth("hello", "world");
  2803. auto res = cli.Get(path);
  2804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2805. auto body = remove_whitespace(res->body);
  2806. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2807. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2808. EXPECT_EQ(StatusCode::OK_200, res->status);
  2809. }
  2810. {
  2811. cli.set_basic_auth("hello", "bad");
  2812. auto res = cli.Get(path);
  2813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2814. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2815. }
  2816. {
  2817. cli.set_basic_auth("bad", "world");
  2818. auto res = cli.Get(path);
  2819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2820. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2821. }
  2822. }
  2823. #ifdef CPPHTTPLIB_SSL_ENABLED
  2824. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2825. auto host = "httpbingo.org";
  2826. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2827. auto paths = std::vector<std::string>{
  2828. "/digest-auth/auth/hello/world/MD5",
  2829. "/digest-auth/auth/hello/world/SHA-256",
  2830. };
  2831. auto port = 443;
  2832. SSLClient cli(host, port);
  2833. {
  2834. auto res = cli.Get(unauth_path);
  2835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2836. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2837. }
  2838. {
  2839. cli.set_digest_auth("hello", "world");
  2840. for (const auto &path : paths) {
  2841. auto res = cli.Get(path.c_str());
  2842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2843. auto body = remove_whitespace(res->body);
  2844. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2845. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2846. EXPECT_EQ(StatusCode::OK_200, res->status);
  2847. }
  2848. cli.set_digest_auth("hello", "bad");
  2849. for (const auto &path : paths) {
  2850. auto res = cli.Get(path.c_str());
  2851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2852. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2853. }
  2854. }
  2855. }
  2856. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2857. // comma-separated list of challenges, and each challenge may itself carry a
  2858. // comma-separated auth-param list, so a server can legally offer Basic
  2859. // before Digest, either as two field lines or packed into one. Runs one 401
  2860. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2861. // value() joins them in receipt order) and checks that the retry carries a
  2862. // well-formed Digest Authorization header naming expected_realm.
  2863. static void
  2864. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2865. const std::string &expected_realm) {
  2866. std::atomic<int> hits{0};
  2867. Server svr;
  2868. svr.Get("/x", [&](const Request &req, Response &res) {
  2869. if (++hits == 1) {
  2870. res.status = StatusCode::Unauthorized_401;
  2871. for (const auto &challenge : challenges) {
  2872. res.set_header("WWW-Authenticate", challenge);
  2873. }
  2874. } else {
  2875. auto authorization = req.get_header_value("Authorization");
  2876. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2877. EXPECT_NE(std::string::npos,
  2878. authorization.find("realm=\"" + expected_realm + "\""));
  2879. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2880. res.set_content("ok", "text/plain");
  2881. }
  2882. });
  2883. auto port = svr.bind_to_any_port(HOST);
  2884. std::thread t([&]() { svr.listen_after_bind(); });
  2885. auto se = detail::scope_exit([&] {
  2886. svr.stop();
  2887. t.join();
  2888. });
  2889. svr.wait_until_ready();
  2890. Client cli(HOST, port);
  2891. cli.set_digest_auth("hello", "world");
  2892. auto res = cli.Get("/x");
  2893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2894. EXPECT_EQ(2, hits.load());
  2895. }
  2896. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2897. static const char *kDigestChallenge =
  2898. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2899. "algorithm=MD5";
  2900. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2901. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2902. "testrealm");
  2903. }
  2904. // Same challenge list with the schemes in the opposite order, to make sure
  2905. // the fix above didn't just special-case "Basic first".
  2906. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2907. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2908. "testrealm");
  2909. }
  2910. // A comma inside a quoted auth-param value must not be mistaken for the
  2911. // separator between two challenges (or two auth-params).
  2912. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2913. run_digest_challenge_list_test(
  2914. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2915. "algorithm=MD5"},
  2916. "test,realm");
  2917. }
  2918. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2919. // make_digest_authentication_header() dereferences both unconditionally, so
  2920. // a server sending a challenge missing either one must not be treated as
  2921. // usable -- doing so used to crash the client with std::out_of_range.
  2922. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2923. Server svr;
  2924. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2925. res.status = StatusCode::Unauthorized_401;
  2926. res.set_header("WWW-Authenticate", challenge);
  2927. });
  2928. auto port = svr.bind_to_any_port(HOST);
  2929. std::thread t([&]() { svr.listen_after_bind(); });
  2930. auto se = detail::scope_exit([&] {
  2931. svr.stop();
  2932. t.join();
  2933. });
  2934. svr.wait_until_ready();
  2935. Client cli(HOST, port);
  2936. cli.set_digest_auth("hello", "world");
  2937. auto res = cli.Get("/x");
  2938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2939. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2940. }
  2941. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2942. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2943. }
  2944. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2945. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2946. }
  2947. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2948. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2949. }
  2950. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2951. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2952. // when storing the values, so the header builder has to re-escape them (and
  2953. // keep algorithm a bare token); otherwise the value breaks out of its
  2954. // quoted-string and injects extra auth-params into the client's Authorization.
  2955. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2956. std::atomic<int> hits{0};
  2957. std::string authorization;
  2958. Server svr;
  2959. svr.Get("/x", [&](const Request &req, Response &res) {
  2960. if (++hits == 1) {
  2961. res.status = StatusCode::Unauthorized_401;
  2962. // On the wire the quotes embedded in the values are backslash-escaped.
  2963. res.set_header("WWW-Authenticate",
  2964. "Digest realm=\"testrealm\", "
  2965. "nonce=\"n\\\"; injected=\\\"x\", "
  2966. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2967. } else {
  2968. authorization = req.get_header_value("Authorization");
  2969. res.set_content("ok", "text/plain");
  2970. }
  2971. });
  2972. auto port = svr.bind_to_any_port(HOST);
  2973. std::thread t([&]() { svr.listen_after_bind(); });
  2974. auto se = detail::scope_exit([&] {
  2975. svr.stop();
  2976. t.join();
  2977. });
  2978. svr.wait_until_ready();
  2979. Client cli(HOST, port);
  2980. cli.set_digest_auth("hello", "world");
  2981. auto res = cli.Get("/x");
  2982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2983. EXPECT_EQ(2, hits.load());
  2984. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2985. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2986. // inside its quoted-string rather than starting an "injected" auth-param.
  2987. EXPECT_NE(std::string::npos,
  2988. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2989. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2990. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2991. }
  2992. #endif
  2993. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2994. auto host = "google.com";
  2995. auto another_host = "example.com";
  2996. auto wrong_ip = "0.0.0.0";
  2997. #ifdef CPPHTTPLIB_SSL_ENABLED
  2998. SSLClient cli(host);
  2999. #else
  3000. Client cli(host);
  3001. #endif
  3002. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3003. auto res = cli.Get("/");
  3004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3005. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3006. }
  3007. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3008. auto host = "google.com";
  3009. auto wrong_ip = "0.0.0.0";
  3010. #ifdef CPPHTTPLIB_SSL_ENABLED
  3011. SSLClient cli(host);
  3012. #else
  3013. Client cli(host);
  3014. #endif
  3015. cli.set_hostname_addr_map({{host, wrong_ip}});
  3016. auto res = cli.Get("/");
  3017. ASSERT_TRUE(!res);
  3018. EXPECT_EQ(Error::Connection, res.error());
  3019. }
  3020. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3021. // A mapped value that is not an IP literal must be resolved. "localhost"
  3022. // resolves from the hosts file, so this test needs no external DNS.
  3023. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3024. auto host = "target.invalid";
  3025. Server svr;
  3026. std::string received_host;
  3027. svr.Get("/hi", [&](const Request &req, Response &res) {
  3028. received_host = req.get_header_value("Host");
  3029. res.set_content("Hello World!", "text/plain");
  3030. });
  3031. auto port = svr.bind_to_any_port(HOST);
  3032. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3033. auto se = detail::scope_exit([&] {
  3034. svr.stop();
  3035. thread.join();
  3036. ASSERT_FALSE(svr.is_running());
  3037. });
  3038. svr.wait_until_ready();
  3039. Client cli(host, port);
  3040. cli.set_hostname_addr_map({{host, HOST}});
  3041. auto res = cli.Get("/hi");
  3042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3043. EXPECT_EQ(StatusCode::OK_200, res->status);
  3044. // The mapping only redirects the connection; the identity stays host_.
  3045. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3046. }
  3047. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3048. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3049. auto host = "target.invalid";
  3050. Server svr;
  3051. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3052. res.set_content("Hello World!", "text/plain");
  3053. });
  3054. auto port = svr.bind_to_any_port("127.0.0.1");
  3055. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3056. auto se = detail::scope_exit([&] {
  3057. svr.stop();
  3058. thread.join();
  3059. ASSERT_FALSE(svr.is_running());
  3060. });
  3061. svr.wait_until_ready();
  3062. Client cli(host, port);
  3063. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3064. auto res = cli.Get("/hi");
  3065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3066. EXPECT_EQ(StatusCode::OK_200, res->status);
  3067. }
  3068. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3069. // An empty mapped value must leave host_ as the connection target. Without
  3070. // that guard the empty value would become the host argument, getaddrinfo
  3071. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3072. // loopback - silently connecting somewhere the caller never asked for.
  3073. // The server listens on loopback, so such a fallback would succeed and is
  3074. // therefore observable as a failure of this test.
  3075. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3076. Server svr;
  3077. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3078. res.set_content("Hello World!", "text/plain");
  3079. });
  3080. auto port = svr.bind_to_any_port(HOST);
  3081. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3082. auto se = detail::scope_exit([&] {
  3083. svr.stop();
  3084. thread.join();
  3085. ASSERT_FALSE(svr.is_running());
  3086. });
  3087. svr.wait_until_ready();
  3088. Client cli(blackhole, port);
  3089. cli.set_hostname_addr_map({{blackhole, ""}});
  3090. cli.set_connection_timeout(1);
  3091. auto res = cli.Get("/hi");
  3092. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3093. }
  3094. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3095. auto host = "httpbingo.org";
  3096. auto path = std::string{"/absolute-redirect/3"};
  3097. #ifdef CPPHTTPLIB_SSL_ENABLED
  3098. SSLClient cli(host);
  3099. #else
  3100. Client cli(host);
  3101. #endif
  3102. cli.set_follow_location(true);
  3103. auto res = cli.Get(path);
  3104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3105. EXPECT_EQ(StatusCode::OK_200, res->status);
  3106. }
  3107. TEST(RedirectTest, Redirect_Online) {
  3108. auto host = "httpbingo.org";
  3109. auto path = std::string{"/redirect/3"};
  3110. #ifdef CPPHTTPLIB_SSL_ENABLED
  3111. SSLClient cli(host);
  3112. #else
  3113. Client cli(host);
  3114. #endif
  3115. cli.set_follow_location(true);
  3116. auto res = cli.Get(path);
  3117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3118. EXPECT_EQ(StatusCode::OK_200, res->status);
  3119. }
  3120. TEST(RelativeRedirectTest, Redirect_Online) {
  3121. auto host = "httpbingo.org";
  3122. auto path = std::string{"/relative-redirect/3"};
  3123. #ifdef CPPHTTPLIB_SSL_ENABLED
  3124. SSLClient cli(host);
  3125. #else
  3126. Client cli(host);
  3127. #endif
  3128. cli.set_follow_location(true);
  3129. auto res = cli.Get(path);
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. }
  3133. TEST(TooManyRedirectTest, Redirect_Online) {
  3134. auto host = "httpbingo.org";
  3135. auto path = std::string{"/redirect/21"};
  3136. #ifdef CPPHTTPLIB_SSL_ENABLED
  3137. SSLClient cli(host);
  3138. #else
  3139. Client cli(host);
  3140. #endif
  3141. cli.set_follow_location(true);
  3142. auto res = cli.Get(path);
  3143. ASSERT_TRUE(!res);
  3144. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3145. }
  3146. #ifdef CPPHTTPLIB_SSL_ENABLED
  3147. TEST(YahooRedirectTest, Redirect_Online) {
  3148. Client cli("yahoo.com");
  3149. auto res = cli.Get("/");
  3150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3151. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3152. cli.set_follow_location(true);
  3153. res = cli.Get("/");
  3154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3155. EXPECT_EQ(StatusCode::OK_200, res->status);
  3156. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3157. }
  3158. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3159. #define REDIR_HOST "httpbingo.org"
  3160. #define REDIR_PATH "/redirect-to"
  3161. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3162. SSLClient cli(REDIR_HOST);
  3163. cli.set_follow_location(true);
  3164. auto res =
  3165. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3167. EXPECT_EQ(StatusCode::OK_200, res->status);
  3168. }
  3169. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3170. SSLClient cli(REDIR_HOST);
  3171. cli.set_follow_location(true);
  3172. Params params;
  3173. params.emplace("url", "http://example.com");
  3174. params.emplace("status_code", "302");
  3175. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3177. EXPECT_EQ(StatusCode::OK_200, res->status);
  3178. }
  3179. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3180. SSLClient cli(REDIR_HOST);
  3181. cli.set_follow_location(true);
  3182. Params params;
  3183. params.emplace("url", "http://example.com");
  3184. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3186. EXPECT_EQ(StatusCode::OK_200, res->status);
  3187. }
  3188. TEST(UrlWithSpace, Redirect_Online) {
  3189. SSLClient cli("edge.forgecdn.net");
  3190. cli.set_follow_location(true);
  3191. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3193. EXPECT_EQ(StatusCode::OK_200, res->status);
  3194. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3195. }
  3196. #endif
  3197. #if !defined(_WIN32) && !defined(_WIN64)
  3198. TEST(ReceiveSignals, Signal) {
  3199. auto setupSignalHandlers = []() {
  3200. struct sigaction act;
  3201. sigemptyset(&act.sa_mask);
  3202. act.sa_flags = SA_SIGINFO;
  3203. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3204. switch (sig) {
  3205. case SIGINT:
  3206. default: break;
  3207. }
  3208. };
  3209. ::sigaction(SIGINT, &act, nullptr);
  3210. };
  3211. Server svr;
  3212. int port = 0;
  3213. auto thread = std::thread([&]() {
  3214. setupSignalHandlers();
  3215. port = svr.bind_to_any_port(HOST);
  3216. svr.listen_after_bind();
  3217. });
  3218. auto se = detail::scope_exit([&] {
  3219. svr.stop();
  3220. thread.join();
  3221. ASSERT_FALSE(svr.is_running());
  3222. });
  3223. svr.wait_until_ready();
  3224. ASSERT_TRUE(svr.is_running());
  3225. pthread_kill(thread.native_handle(), SIGINT);
  3226. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3227. ASSERT_TRUE(svr.is_running());
  3228. }
  3229. #endif
  3230. TEST(RedirectToDifferentPort, Redirect) {
  3231. Server svr1;
  3232. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3233. res.set_content("Hello World!", "text/plain");
  3234. });
  3235. int svr1_port = 0;
  3236. auto thread1 = std::thread([&]() {
  3237. svr1_port = svr1.bind_to_any_port(HOST);
  3238. svr1.listen_after_bind();
  3239. });
  3240. Server svr2;
  3241. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3242. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3243. });
  3244. int svr2_port = 0;
  3245. auto thread2 = std::thread([&]() {
  3246. svr2_port = svr2.bind_to_any_port(HOST);
  3247. svr2.listen_after_bind();
  3248. });
  3249. auto se = detail::scope_exit([&] {
  3250. svr2.stop();
  3251. thread2.join();
  3252. svr1.stop();
  3253. thread1.join();
  3254. ASSERT_FALSE(svr2.is_running());
  3255. ASSERT_FALSE(svr1.is_running());
  3256. });
  3257. svr1.wait_until_ready();
  3258. svr2.wait_until_ready();
  3259. Client cli("localhost", svr2_port);
  3260. cli.set_follow_location(true);
  3261. auto res = cli.Get("/2");
  3262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3263. EXPECT_EQ(StatusCode::OK_200, res->status);
  3264. EXPECT_EQ("Hello World!", res->body);
  3265. }
  3266. // GET /redir on one server redirects to /target on another port, so the
  3267. // client follows it with a new client.
  3268. static Result
  3269. GetThroughRedirectToDifferentPort(Server::Handler target,
  3270. const std::function<void(Client &)> &setup,
  3271. const Headers &headers = Headers()) {
  3272. Server target_svr;
  3273. target_svr.Get("/target", target);
  3274. int target_port = 0;
  3275. auto target_thread = std::thread([&]() {
  3276. target_port = target_svr.bind_to_any_port(HOST);
  3277. target_svr.listen_after_bind();
  3278. });
  3279. Server origin_svr;
  3280. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3281. res.set_redirect(
  3282. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3283. });
  3284. int origin_port = 0;
  3285. auto origin_thread = std::thread([&]() {
  3286. origin_port = origin_svr.bind_to_any_port(HOST);
  3287. origin_svr.listen_after_bind();
  3288. });
  3289. auto se = detail::scope_exit([&] {
  3290. origin_svr.stop();
  3291. origin_thread.join();
  3292. target_svr.stop();
  3293. target_thread.join();
  3294. });
  3295. target_svr.wait_until_ready();
  3296. origin_svr.wait_until_ready();
  3297. Client cli("localhost", origin_port);
  3298. cli.set_follow_location(true);
  3299. setup(cli);
  3300. return cli.Get("/redir", headers);
  3301. }
  3302. static void
  3303. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3304. std::string captured_authorization;
  3305. auto result = GetThroughRedirectToDifferentPort(
  3306. [&](const Request &req, Response &res) {
  3307. captured_authorization = req.get_header_value("Authorization");
  3308. res.set_content("OK", "text/plain");
  3309. },
  3310. set_auth);
  3311. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3312. EXPECT_EQ(StatusCode::OK_200, result->status);
  3313. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3314. EXPECT_TRUE(captured_authorization.empty());
  3315. }
  3316. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3317. TestDoNotForwardCredentialsOnRedirect(
  3318. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3319. }
  3320. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3321. TestDoNotForwardCredentialsOnRedirect(
  3322. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3323. }
  3324. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3325. std::string captured_cookie;
  3326. auto result = GetThroughRedirectToDifferentPort(
  3327. [&](const Request &req, Response &res) {
  3328. captured_cookie = req.get_header_value("Cookie");
  3329. res.set_content("OK", "text/plain");
  3330. },
  3331. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3332. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3333. EXPECT_EQ(StatusCode::OK_200, result->status);
  3334. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3335. EXPECT_TRUE(captured_cookie.empty());
  3336. }
  3337. TEST(RedirectToSamePort, ForwardCookie) {
  3338. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3339. // header so that ordinary session flows keep working.
  3340. Server svr;
  3341. std::string captured_cookie;
  3342. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3343. res.set_redirect("/target", 302);
  3344. });
  3345. svr.Get("/target", [&](const Request &req, Response &res) {
  3346. captured_cookie = req.get_header_value("Cookie");
  3347. res.set_content("OK", "text/plain");
  3348. });
  3349. auto port = svr.bind_to_any_port(HOST);
  3350. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3351. auto se = detail::scope_exit([&] {
  3352. svr.stop();
  3353. thread.join();
  3354. ASSERT_FALSE(svr.is_running());
  3355. });
  3356. svr.wait_until_ready();
  3357. Client cli(HOST, port);
  3358. cli.set_follow_location(true);
  3359. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3360. auto res = cli.Get("/redir", headers);
  3361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3362. EXPECT_EQ(StatusCode::OK_200, res->status);
  3363. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3364. }
  3365. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3366. std::string authorization;
  3367. std::string trace_id;
  3368. auto result = GetThroughRedirectToDifferentPort(
  3369. [&](const Request &req, Response &res) {
  3370. authorization = req.get_header_value("Authorization");
  3371. trace_id = req.get_header_value("X-Trace-Id");
  3372. res.set_content("OK", "text/plain");
  3373. },
  3374. [](Client &cli) {
  3375. cli.set_default_headers(
  3376. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3377. });
  3378. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3379. EXPECT_EQ(StatusCode::OK_200, result->status);
  3380. // Like a header given with the request, a default one goes along unless it
  3381. // carries credentials (RFC 9110 15.4).
  3382. EXPECT_TRUE(authorization.empty());
  3383. EXPECT_EQ("42", trace_id);
  3384. }
  3385. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3386. auto result = GetThroughRedirectToDifferentPort(
  3387. [](const Request &, Response &res) {
  3388. res.set_content(std::string(2048, 'x'), "text/plain");
  3389. },
  3390. [](Client &cli) { cli.set_payload_max_length(1024); });
  3391. EXPECT_FALSE(result);
  3392. }
  3393. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3394. auto result = GetThroughRedirectToDifferentPort(
  3395. [](const Request &req, Response &res) {
  3396. // Answer after a second, or once the client gives up.
  3397. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3398. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3399. }
  3400. res.set_content("late", "text/plain");
  3401. },
  3402. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3403. ASSERT_FALSE(result);
  3404. EXPECT_EQ(Error::Read, result.error());
  3405. }
  3406. #ifdef CPPHTTPLIB_SSL_ENABLED
  3407. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3408. auto result = GetThroughRedirectToDifferentPort(
  3409. [](const Request &, Response &res) {
  3410. res.status = StatusCode::Unauthorized_401;
  3411. res.set_header("WWW-Authenticate",
  3412. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3413. },
  3414. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3415. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3416. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3417. }
  3418. #endif
  3419. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3420. Server svr;
  3421. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3422. // Port number that overflows int — should not crash
  3423. res.set_redirect("http://localhost:99999999999999999999/target");
  3424. });
  3425. auto port = svr.bind_to_any_port(HOST);
  3426. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3427. auto se = detail::scope_exit([&] {
  3428. svr.stop();
  3429. thread.join();
  3430. ASSERT_FALSE(svr.is_running());
  3431. });
  3432. svr.wait_until_ready();
  3433. Client cli(HOST, port);
  3434. cli.set_follow_location(true);
  3435. auto res = cli.Get("/redir");
  3436. // Should fail gracefully, not crash (no valid response due to bad port)
  3437. EXPECT_FALSE(res);
  3438. }
  3439. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3440. Server svr;
  3441. auto port = svr.bind_to_any_port(HOST);
  3442. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3443. // The server's own port followed by junk must not be followed
  3444. res.set_redirect("http://" + std::string(HOST) + ":" +
  3445. std::to_string(port) + "junk/target");
  3446. });
  3447. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3448. res.set_content("target", "text/plain");
  3449. });
  3450. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3451. auto se = detail::scope_exit([&] {
  3452. svr.stop();
  3453. thread.join();
  3454. ASSERT_FALSE(svr.is_running());
  3455. });
  3456. svr.wait_until_ready();
  3457. Client cli(HOST, port);
  3458. cli.set_follow_location(true);
  3459. auto res = cli.Get("/redir");
  3460. EXPECT_FALSE(res);
  3461. }
  3462. TEST(RedirectFromPageWithContent, Redirect) {
  3463. Server svr;
  3464. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3465. res.set_content("___", "text/plain");
  3466. res.set_redirect("/2");
  3467. });
  3468. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3469. res.set_content("Hello World!", "text/plain");
  3470. });
  3471. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3472. auto se = detail::scope_exit([&] {
  3473. svr.stop();
  3474. th.join();
  3475. ASSERT_FALSE(svr.is_running());
  3476. });
  3477. svr.wait_until_ready();
  3478. {
  3479. Client cli("localhost", PORT);
  3480. cli.set_follow_location(true);
  3481. std::string body;
  3482. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3483. body.append(data, data_length);
  3484. return true;
  3485. });
  3486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3487. EXPECT_EQ(StatusCode::OK_200, res->status);
  3488. EXPECT_EQ("Hello World!", body);
  3489. }
  3490. {
  3491. Client cli("localhost", PORT);
  3492. std::string body;
  3493. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3494. body.append(data, data_length);
  3495. return true;
  3496. });
  3497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3498. EXPECT_EQ(StatusCode::Found_302, res->status);
  3499. EXPECT_EQ("___", body);
  3500. }
  3501. }
  3502. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3503. Server svr;
  3504. auto port_str = std::to_string(PORT);
  3505. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3506. auto expected_host = "[::1]:" + port_str;
  3507. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3508. res.set_content("___", "text/plain");
  3509. // res.set_redirect("/2");
  3510. res.set_redirect(redirect_url);
  3511. });
  3512. svr.Get("/2", [&](const Request &req, Response &res) {
  3513. auto host_header = req.headers.find("Host");
  3514. ASSERT_TRUE(host_header != req.headers.end());
  3515. EXPECT_EQ(expected_host, host_header->second);
  3516. res.set_content("Hello World!", "text/plain");
  3517. });
  3518. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3519. auto se = detail::scope_exit([&] {
  3520. svr.stop();
  3521. th.join();
  3522. ASSERT_FALSE(svr.is_running());
  3523. });
  3524. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3525. // actually starts anything, so the condition !svr.is_running() will
  3526. // always remain true, and the loop never stops.
  3527. // This basically counts how many milliseconds have passed since the
  3528. // call to svr.listen(), and if after 5 seconds nothing started yet
  3529. // aborts the test.
  3530. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3531. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3532. ASSERT_LT(milliseconds, 5000U);
  3533. }
  3534. {
  3535. Client cli("::1", PORT);
  3536. cli.set_follow_location(true);
  3537. std::string body;
  3538. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3539. body.append(data, data_length);
  3540. return true;
  3541. });
  3542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3543. EXPECT_EQ(StatusCode::OK_200, res->status);
  3544. EXPECT_EQ("Hello World!", body);
  3545. }
  3546. {
  3547. Client cli("::1", PORT);
  3548. std::string body;
  3549. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3550. body.append(data, data_length);
  3551. return true;
  3552. });
  3553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3554. EXPECT_EQ(StatusCode::Found_302, res->status);
  3555. EXPECT_EQ("___", body);
  3556. }
  3557. }
  3558. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3559. Server svr;
  3560. svr.Get("/foo", [](const Request &req, Response &res) {
  3561. auto a = req.params.find("a");
  3562. if (a != req.params.end()) {
  3563. res.set_content((*a).second, "text/plain");
  3564. res.status = StatusCode::OK_200;
  3565. } else {
  3566. res.status = StatusCode::BadRequest_400;
  3567. }
  3568. });
  3569. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3570. auto se = detail::scope_exit([&] {
  3571. svr.stop();
  3572. thread.join();
  3573. ASSERT_FALSE(svr.is_running());
  3574. });
  3575. svr.wait_until_ready();
  3576. {
  3577. Client cli(HOST, PORT);
  3578. cli.set_path_encode(false);
  3579. auto res = cli.Get("/foo?a=explicitly+encoded");
  3580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3581. EXPECT_EQ(StatusCode::OK_200, res->status);
  3582. // This expects it back with a space, as the `+` won't have been
  3583. // url-encoded, and server-side the params get decoded turning `+`
  3584. // into spaces.
  3585. EXPECT_EQ("explicitly encoded", res->body);
  3586. }
  3587. }
  3588. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3589. // When path encoding is disabled the client must transmit the supplied
  3590. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3591. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3592. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3593. // than a space (0x20). Assert on the raw wire target to catch this.
  3594. Server svr;
  3595. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3596. svr.Get("/foo", [&](const Request &req, Response &res) {
  3597. EXPECT_EQ(expected_target, req.target);
  3598. res.status = StatusCode::OK_200;
  3599. });
  3600. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3601. auto se = detail::scope_exit([&] {
  3602. svr.stop();
  3603. thread.join();
  3604. ASSERT_FALSE(svr.is_running());
  3605. });
  3606. svr.wait_until_ready();
  3607. {
  3608. Client cli(HOST, PORT);
  3609. cli.set_path_encode(false);
  3610. auto res = cli.Get(expected_target.c_str());
  3611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3612. EXPECT_EQ(StatusCode::OK_200, res->status);
  3613. }
  3614. }
  3615. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3616. // `open_stream()` used to skip the path encoding that the buffered send
  3617. // path applies, so the same `path` produced different bytes in the request
  3618. // line depending on which API was used. Assert the two agree.
  3619. Server svr;
  3620. std::string target;
  3621. svr.Get(".*", [&](const Request &req, Response &res) {
  3622. target = req.target;
  3623. res.status = StatusCode::OK_200;
  3624. });
  3625. auto port = svr.bind_to_any_port(HOST);
  3626. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3627. auto se = detail::scope_exit([&] {
  3628. svr.stop();
  3629. thread.join();
  3630. ASSERT_FALSE(svr.is_running());
  3631. });
  3632. svr.wait_until_ready();
  3633. struct {
  3634. const char *path;
  3635. const char *expected;
  3636. } cases[] = {
  3637. {"/a b?x=1", "/a%20b?x=1"},
  3638. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3639. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3640. };
  3641. for (const auto &c : cases) {
  3642. Client cli(HOST, port);
  3643. target.clear();
  3644. auto res = cli.Get(c.path);
  3645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3646. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3647. auto buffered_target = target;
  3648. target.clear();
  3649. auto handle = cli.open_stream("GET", c.path);
  3650. EXPECT_TRUE(handle.is_valid())
  3651. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3652. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3653. }
  3654. }
  3655. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3656. // The `set_path_encode(false)` contract — transmit the supplied target
  3657. // verbatim — must hold for the streaming API too.
  3658. Server svr;
  3659. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3660. std::string target;
  3661. svr.Get("/foo", [&](const Request &req, Response &res) {
  3662. target = req.target;
  3663. res.status = StatusCode::OK_200;
  3664. });
  3665. auto port = svr.bind_to_any_port(HOST);
  3666. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3667. auto se = detail::scope_exit([&] {
  3668. svr.stop();
  3669. thread.join();
  3670. ASSERT_FALSE(svr.is_running());
  3671. });
  3672. svr.wait_until_ready();
  3673. {
  3674. Client cli(HOST, port);
  3675. cli.set_path_encode(false);
  3676. auto handle = cli.open_stream("GET", expected_target);
  3677. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3678. EXPECT_EQ(expected_target, target);
  3679. }
  3680. }
  3681. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3682. // With path encoding enabled a CR/LF in the target is percent-encoded
  3683. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3684. // write_request_line still backstops `set_path_encode(false)`, which is
  3685. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3686. Server svr;
  3687. // Captured before routing: the decoded path contains a newline, which a
  3688. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3689. std::string target;
  3690. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3691. target = req.target;
  3692. res.status = StatusCode::OK_200;
  3693. return Server::HandlerResponse::Handled;
  3694. });
  3695. auto port = svr.bind_to_any_port(HOST);
  3696. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3697. auto se = detail::scope_exit([&] {
  3698. svr.stop();
  3699. thread.join();
  3700. ASSERT_FALSE(svr.is_running());
  3701. });
  3702. svr.wait_until_ready();
  3703. {
  3704. Client cli(HOST, port);
  3705. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3706. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3707. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3708. }
  3709. }
  3710. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3711. // Every control character is percent-encoded, not just CR/LF, so the target
  3712. // passes the request-target check in write_request_line.
  3713. Server svr;
  3714. std::string target;
  3715. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3716. target = req.target;
  3717. res.status = StatusCode::OK_200;
  3718. return Server::HandlerResponse::Handled;
  3719. });
  3720. auto port = svr.bind_to_any_port(HOST);
  3721. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3722. auto se = detail::scope_exit([&] {
  3723. svr.stop();
  3724. thread.join();
  3725. ASSERT_FALSE(svr.is_running());
  3726. });
  3727. svr.wait_until_ready();
  3728. {
  3729. Client cli(HOST, port);
  3730. auto res = cli.Get("/a\tb\x1b\x7f");
  3731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3732. EXPECT_EQ("/a%09b%1B%7F", target);
  3733. }
  3734. }
  3735. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3736. // Nothing may reach the wire: a raw CR/LF target would split the request
  3737. // line and inject headers.
  3738. Server svr;
  3739. // Pre-routing so that "not called" means nothing reached the server at all,
  3740. // rather than merely failing to match a handler pattern.
  3741. auto handler_called = false;
  3742. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3743. handler_called = true;
  3744. res.status = StatusCode::OK_200;
  3745. return Server::HandlerResponse::Handled;
  3746. });
  3747. auto port = svr.bind_to_any_port(HOST);
  3748. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3749. auto se = detail::scope_exit([&] {
  3750. svr.stop();
  3751. thread.join();
  3752. ASSERT_FALSE(svr.is_running());
  3753. });
  3754. svr.wait_until_ready();
  3755. {
  3756. Client cli(HOST, port);
  3757. cli.set_path_encode(false);
  3758. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3759. EXPECT_FALSE(handle.is_valid());
  3760. EXPECT_EQ(Error::Write, handle.error);
  3761. EXPECT_FALSE(handler_called);
  3762. }
  3763. }
  3764. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3765. // Which of the two branches runs is decided by whether the query component
  3766. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3767. // an empty query and must still fall back to building one from
  3768. // `req.params`, while a non-empty query must win over `req.params`.
  3769. Server svr;
  3770. std::string target;
  3771. svr.Get("/foo", [&](const Request &req, Response &res) {
  3772. target = req.target;
  3773. res.status = StatusCode::OK_200;
  3774. });
  3775. auto port = svr.bind_to_any_port(HOST);
  3776. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3777. auto se = detail::scope_exit([&] {
  3778. svr.stop();
  3779. thread.join();
  3780. ASSERT_FALSE(svr.is_running());
  3781. });
  3782. svr.wait_until_ready();
  3783. {
  3784. // Trailing `?` -> empty query component -> `req.params` is used.
  3785. Client cli(HOST, port);
  3786. Request req;
  3787. req.method = "GET";
  3788. req.path = "/foo?";
  3789. req.params.emplace("a", "1");
  3790. target.clear();
  3791. auto res = cli.send(req);
  3792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3793. EXPECT_EQ("/foo?a=1", target);
  3794. }
  3795. {
  3796. // Non-empty query in `req.path` -> `req.params` is not appended.
  3797. Client cli(HOST, port);
  3798. Request req;
  3799. req.method = "GET";
  3800. req.path = "/foo?b=2";
  3801. req.params.emplace("a", "1");
  3802. target.clear();
  3803. auto res = cli.send(req);
  3804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3805. EXPECT_EQ("/foo?b=2", target);
  3806. }
  3807. }
  3808. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3809. Server svr;
  3810. svr.Get("/", [](const Request &req, Response &) {
  3811. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3812. });
  3813. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3814. auto se = detail::scope_exit([&] {
  3815. svr.stop();
  3816. thread.join();
  3817. ASSERT_FALSE(svr.is_running());
  3818. });
  3819. svr.wait_until_ready();
  3820. {
  3821. Client cli(HOST, PORT);
  3822. cli.set_path_encode(false);
  3823. auto res = cli.Get("/?something=%0A");
  3824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3825. EXPECT_EQ(StatusCode::OK_200, res->status);
  3826. }
  3827. }
  3828. TEST(BindServerTest, BindDualStack) {
  3829. Server svr;
  3830. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3831. res.set_content("Hello World!", "text/plain");
  3832. });
  3833. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3834. auto se = detail::scope_exit([&] {
  3835. svr.stop();
  3836. thread.join();
  3837. ASSERT_FALSE(svr.is_running());
  3838. });
  3839. svr.wait_until_ready();
  3840. {
  3841. Client cli("127.0.0.1", PORT);
  3842. auto res = cli.Get("/1");
  3843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3844. EXPECT_EQ(StatusCode::OK_200, res->status);
  3845. EXPECT_EQ("Hello World!", res->body);
  3846. }
  3847. {
  3848. Client cli("::1", PORT);
  3849. auto res = cli.Get("/1");
  3850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3851. EXPECT_EQ(StatusCode::OK_200, res->status);
  3852. EXPECT_EQ("Hello World!", res->body);
  3853. }
  3854. }
  3855. TEST(BindServerTest, BindAndListenSeparately) {
  3856. Server svr;
  3857. int port = svr.bind_to_any_port("0.0.0.0");
  3858. ASSERT_TRUE(svr.is_valid());
  3859. ASSERT_TRUE(port > 0);
  3860. svr.stop();
  3861. }
  3862. // Reports whether anything is still listening on a loopback port. A plain
  3863. // connect() is used instead of a Client request because a socket left bound by
  3864. // mistake accepts the connection into its backlog and never answers, which
  3865. // would hang the test instead of failing it.
  3866. static bool is_loopback_port_accepting(int port) {
  3867. sockaddr_in addr{};
  3868. addr.sin_family = AF_INET;
  3869. addr.sin_port = htons(static_cast<uint16_t>(port));
  3870. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3871. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3872. EXPECT_NE(sock, INVALID_SOCKET);
  3873. if (sock == INVALID_SOCKET) { return false; }
  3874. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3875. static_cast<socklen_t>(sizeof(addr)));
  3876. detail::close_socket(sock);
  3877. return ret == 0;
  3878. }
  3879. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3880. Server svr;
  3881. auto port = svr.bind_to_any_port("127.0.0.1");
  3882. ASSERT_TRUE(port > 0);
  3883. svr.stop();
  3884. // bind_to_any_port() already called listen(2), so until stop() closed the
  3885. // descriptor the port kept accepting connections into the backlog. ASSERT
  3886. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3887. // below blocks forever in the accept loop.
  3888. ASSERT_FALSE(is_loopback_port_accepting(port));
  3889. // Nothing is left to accept on, so listen_after_bind() must report failure
  3890. // instead of returning success without ever serving.
  3891. EXPECT_FALSE(svr.listen_after_bind());
  3892. // The failed listen marks the server decommissioned, so a waiter returns
  3893. // instead of spinning forever.
  3894. svr.wait_until_ready();
  3895. }
  3896. #ifdef CPPHTTPLIB_SSL_ENABLED
  3897. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3899. CLIENT_CA_CERT_DIR);
  3900. int port = svr.bind_to_any_port("0.0.0.0");
  3901. ASSERT_TRUE(svr.is_valid());
  3902. ASSERT_TRUE(port > 0);
  3903. svr.stop();
  3904. }
  3905. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3906. // or a rejected CustomRoute() registration would not stop the server binding.
  3907. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3908. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3909. CLIENT_CA_CERT_DIR);
  3910. ASSERT_TRUE(svr.is_valid());
  3911. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3912. EXPECT_FALSE(svr.is_valid());
  3913. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3914. }
  3915. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3916. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3917. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3918. int port = svr.bind_to_any_port("0.0.0.0");
  3919. ASSERT_TRUE(svr.is_valid());
  3920. ASSERT_TRUE(port > 0);
  3921. svr.stop();
  3922. }
  3923. TEST(BindServerTest, UpdateCertsPem) {
  3924. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3925. int port = svr.bind_to_any_port("0.0.0.0");
  3926. ASSERT_TRUE(svr.is_valid());
  3927. ASSERT_TRUE(port > 0);
  3928. // Read PEM files
  3929. std::string cert_pem, key_pem, ca_pem;
  3930. read_file(SERVER_CERT_FILE, cert_pem);
  3931. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3932. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3933. // Update server certificates using PEM API
  3934. ASSERT_TRUE(
  3935. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3936. ASSERT_TRUE(svr.is_valid());
  3937. svr.stop();
  3938. }
  3939. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3940. // Start server with client CA (enables client auth)
  3941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3942. ASSERT_TRUE(svr.is_valid());
  3943. bool handler_called = false;
  3944. svr.Get("/test", [&](const Request &req, Response &res) {
  3945. handler_called = true;
  3946. // Verify client certificate is present
  3947. auto cert = req.peer_cert();
  3948. EXPECT_TRUE(static_cast<bool>(cert));
  3949. res.set_content("ok", "text/plain");
  3950. });
  3951. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3952. auto se = detail::scope_exit([&] {
  3953. svr.stop();
  3954. t.join();
  3955. ASSERT_FALSE(svr.is_running());
  3956. });
  3957. svr.wait_until_ready();
  3958. // Read PEM files
  3959. std::string cert_pem, key_pem, ca_pem;
  3960. read_file(SERVER_CERT_FILE, cert_pem);
  3961. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3962. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3963. // Update server certificates and client CA using PEM API while server running
  3964. ASSERT_TRUE(
  3965. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3966. // Connect with client certificate
  3967. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3968. cli.enable_server_certificate_verification(false);
  3969. cli.set_connection_timeout(30);
  3970. auto res = cli.Get("/test");
  3971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3972. ASSERT_EQ(StatusCode::OK_200, res->status);
  3973. ASSERT_TRUE(handler_called);
  3974. EXPECT_EQ("ok", res->body);
  3975. }
  3976. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  3977. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3978. ASSERT_TRUE(svr.is_valid());
  3979. svr.Get("/test", [](const Request &, Response &res) {
  3980. res.set_content("ok", "text/plain");
  3981. });
  3982. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3983. auto se = detail::scope_exit([&] {
  3984. svr.stop();
  3985. t.join();
  3986. ASSERT_FALSE(svr.is_running());
  3987. });
  3988. svr.wait_until_ready();
  3989. // A connection that sends no ClientHello keeps its handshake in progress,
  3990. // once the server has had a moment to start it.
  3991. auto error = Error::Success;
  3992. auto sock = detail::create_client_socket(
  3993. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3994. /*connection_timeout_sec=*/5, 0,
  3995. /*read_timeout_sec=*/5, 0,
  3996. /*write_timeout_sec=*/5, 0, std::string(), error);
  3997. ASSERT_NE(INVALID_SOCKET, sock);
  3998. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3999. std::string cert_pem, key_pem;
  4000. read_file(SERVER_CERT_FILE, cert_pem);
  4001. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4002. auto update = std::async(std::launch::async, [&]() {
  4003. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4004. });
  4005. EXPECT_EQ(std::future_status::timeout,
  4006. update.wait_for(std::chrono::milliseconds(200)));
  4007. detail::close_socket(sock);
  4008. EXPECT_TRUE(update.get());
  4009. SSLClient cli(HOST, PORT);
  4010. cli.enable_server_certificate_verification(false);
  4011. auto res = cli.Get("/test");
  4012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4013. EXPECT_EQ(StatusCode::OK_200, res->status);
  4014. }
  4015. #endif
  4016. TEST(ErrorHandlerTest, ContentLength) {
  4017. Server svr;
  4018. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4019. res.status = StatusCode::OK_200;
  4020. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4021. "text/html"); // <= Content-Length still 13
  4022. });
  4023. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4024. res.set_content("Hello World!\n", "text/plain");
  4025. res.status = 524;
  4026. });
  4027. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4028. auto se = detail::scope_exit([&] {
  4029. svr.stop();
  4030. thread.join();
  4031. ASSERT_FALSE(svr.is_running());
  4032. });
  4033. svr.wait_until_ready();
  4034. {
  4035. Client cli(HOST, PORT);
  4036. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4038. EXPECT_EQ(StatusCode::OK_200, res->status);
  4039. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4040. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4041. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4042. }
  4043. }
  4044. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4045. TEST(ExceptionTest, WithoutExceptionHandler) {
  4046. Server svr;
  4047. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4048. throw std::runtime_error("exception...");
  4049. });
  4050. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4051. throw std::runtime_error("exception\r\n...");
  4052. });
  4053. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4054. auto se = detail::scope_exit([&] {
  4055. svr.stop();
  4056. listen_thread.join();
  4057. ASSERT_FALSE(svr.is_running());
  4058. });
  4059. svr.wait_until_ready();
  4060. Client cli("localhost", PORT);
  4061. {
  4062. auto res = cli.Get("/exception");
  4063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4064. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4065. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4066. }
  4067. {
  4068. auto res = cli.Get("/unknown");
  4069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4070. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4071. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4072. }
  4073. }
  4074. TEST(ExceptionTest, WithExceptionHandler) {
  4075. Server svr;
  4076. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4077. std::exception_ptr ep) {
  4078. EXPECT_FALSE(ep == nullptr);
  4079. try {
  4080. std::rethrow_exception(ep);
  4081. } catch (std::exception &e) {
  4082. EXPECT_EQ("abc", std::string(e.what()));
  4083. } catch (...) {}
  4084. res.status = StatusCode::InternalServerError_500;
  4085. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4086. "text/html"); // <= Content-Length still 13 at this point
  4087. });
  4088. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4089. res.set_content("Hello World!\n", "text/plain");
  4090. throw std::runtime_error("abc");
  4091. });
  4092. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4093. auto se = detail::scope_exit([&] {
  4094. svr.stop();
  4095. thread.join();
  4096. ASSERT_FALSE(svr.is_running());
  4097. });
  4098. svr.wait_until_ready();
  4099. for (size_t i = 0; i < 10; i++) {
  4100. Client cli(HOST, PORT);
  4101. for (size_t j = 0; j < 100; j++) {
  4102. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4104. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4105. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4106. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4107. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4108. }
  4109. cli.set_keep_alive(true);
  4110. for (size_t j = 0; j < 100; j++) {
  4111. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4113. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4114. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4115. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4116. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4117. }
  4118. }
  4119. }
  4120. TEST(ExceptionTest, AndErrorHandler) {
  4121. Server svr;
  4122. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4123. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4124. });
  4125. svr.set_exception_handler(
  4126. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4127. EXPECT_FALSE(ep == nullptr);
  4128. try {
  4129. std::rethrow_exception(ep);
  4130. } catch (std::exception &e) {
  4131. res.set_content(e.what(), "text/html");
  4132. } catch (...) {}
  4133. res.status = StatusCode::InternalServerError_500;
  4134. });
  4135. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4136. throw std::runtime_error("EXCEPTION");
  4137. });
  4138. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4139. res.set_content("ERROR", "text/html");
  4140. res.status = StatusCode::InternalServerError_500;
  4141. });
  4142. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4143. auto se = detail::scope_exit([&] {
  4144. svr.stop();
  4145. thread.join();
  4146. ASSERT_FALSE(svr.is_running());
  4147. });
  4148. svr.wait_until_ready();
  4149. Client cli(HOST, PORT);
  4150. {
  4151. auto res = cli.Get("/exception");
  4152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4153. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4154. EXPECT_EQ("EXCEPTION", res->body);
  4155. }
  4156. {
  4157. auto res = cli.Get("/error");
  4158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4159. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4160. EXPECT_EQ("ERROR", res->body);
  4161. }
  4162. {
  4163. auto res = cli.Get("/invalid");
  4164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4165. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4166. EXPECT_EQ("NOT_FOUND", res->body);
  4167. }
  4168. }
  4169. #endif
  4170. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4171. // process_request() wraps only routing() in a try/catch, so an exception from
  4172. // any other user callback used to unwind into the task queue - which does not
  4173. // catch - and terminate the process. Each test below runs the server on a
  4174. // single worker thread: a guard that catches the exception but still loses the
  4175. // thread would otherwise be hidden by a spare worker serving the follow-up
  4176. // request. Note that a regression here aborts the whole test binary rather
  4177. // than failing one test.
  4178. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4179. Server svr;
  4180. svr.new_task_queue = [] { return new ThreadPool(1); };
  4181. std::atomic<int> reported{0};
  4182. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4183. if (err == Error::UserCallbackException) { reported++; }
  4184. });
  4185. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4186. res.set_content_provider(
  4187. 1024, "text/plain",
  4188. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4189. sink.write("hello", 5);
  4190. throw std::runtime_error("from the content provider");
  4191. });
  4192. });
  4193. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4194. res.set_content("ok", "text/plain");
  4195. });
  4196. auto port = svr.bind_to_any_port(HOST);
  4197. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4198. auto se = detail::scope_exit([&] {
  4199. svr.stop();
  4200. listen_thread.join();
  4201. ASSERT_FALSE(svr.is_running());
  4202. });
  4203. svr.wait_until_ready();
  4204. {
  4205. Client cli(HOST, port);
  4206. cli.set_read_timeout(5, 0);
  4207. EXPECT_FALSE(cli.Get("/throw"));
  4208. }
  4209. EXPECT_TRUE(svr.is_running());
  4210. EXPECT_EQ(1, reported.load());
  4211. // A request on a fresh connection is still served.
  4212. {
  4213. Client cli(HOST, port);
  4214. auto res = cli.Get("/ok");
  4215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4216. EXPECT_EQ(StatusCode::OK_200, res->status);
  4217. EXPECT_EQ("ok", res->body);
  4218. }
  4219. }
  4220. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4221. Server svr;
  4222. svr.new_task_queue = [] { return new ThreadPool(1); };
  4223. std::atomic<bool> should_throw{true};
  4224. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4225. res.set_content("hi", "text/plain");
  4226. });
  4227. svr.set_post_routing_handler(
  4228. [&](const Request & /*req*/, Response & /*res*/) {
  4229. if (should_throw) {
  4230. throw std::runtime_error("from the post-routing handler");
  4231. }
  4232. });
  4233. auto port = svr.bind_to_any_port(HOST);
  4234. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4235. auto se = detail::scope_exit([&] {
  4236. svr.stop();
  4237. listen_thread.join();
  4238. ASSERT_FALSE(svr.is_running());
  4239. });
  4240. svr.wait_until_ready();
  4241. {
  4242. Client cli(HOST, port);
  4243. cli.set_read_timeout(5, 0);
  4244. EXPECT_FALSE(cli.Get("/hi"));
  4245. }
  4246. EXPECT_TRUE(svr.is_running());
  4247. should_throw = false;
  4248. {
  4249. Client cli(HOST, port);
  4250. auto res = cli.Get("/hi");
  4251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4252. EXPECT_EQ(StatusCode::OK_200, res->status);
  4253. EXPECT_EQ("hi", res->body);
  4254. }
  4255. }
  4256. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4257. // The guard reports the caught exception through the error logger, which is
  4258. // a user callback too. A logger that throws has to be contained as well, or
  4259. // the process would terminate from inside the catch.
  4260. Server svr;
  4261. svr.new_task_queue = [] { return new ThreadPool(1); };
  4262. std::atomic<int> reported{0};
  4263. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4264. if (err == Error::UserCallbackException) {
  4265. reported++;
  4266. throw std::runtime_error("from the error logger");
  4267. }
  4268. });
  4269. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4270. res.set_content_provider(
  4271. 1024, "text/plain",
  4272. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4273. sink.write("hello", 5);
  4274. throw std::runtime_error("from the content provider");
  4275. });
  4276. });
  4277. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4278. res.set_content("ok", "text/plain");
  4279. });
  4280. auto port = svr.bind_to_any_port(HOST);
  4281. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4282. auto se = detail::scope_exit([&] {
  4283. svr.stop();
  4284. listen_thread.join();
  4285. ASSERT_FALSE(svr.is_running());
  4286. });
  4287. svr.wait_until_ready();
  4288. {
  4289. Client cli(HOST, port);
  4290. cli.set_read_timeout(5, 0);
  4291. EXPECT_FALSE(cli.Get("/throw"));
  4292. }
  4293. EXPECT_TRUE(svr.is_running());
  4294. EXPECT_EQ(1, reported.load());
  4295. {
  4296. Client cli(HOST, port);
  4297. auto res = cli.Get("/ok");
  4298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4299. EXPECT_EQ(StatusCode::OK_200, res->status);
  4300. EXPECT_EQ("ok", res->body);
  4301. }
  4302. }
  4303. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4304. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4305. // so the exception unwinds through the ws::WebSocket object on its way to
  4306. // the guard. None of the HTTP cases above cross that.
  4307. Server svr;
  4308. svr.new_task_queue = [] { return new ThreadPool(1); };
  4309. std::atomic<int> reported{0};
  4310. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4311. if (err == Error::UserCallbackException) { reported++; }
  4312. });
  4313. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4314. throw std::runtime_error("from the WebSocket handler");
  4315. });
  4316. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4317. res.set_content("ok", "text/plain");
  4318. });
  4319. auto port = svr.bind_to_any_port(HOST);
  4320. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4321. auto se = detail::scope_exit([&] {
  4322. svr.stop();
  4323. listen_thread.join();
  4324. ASSERT_FALSE(svr.is_running());
  4325. });
  4326. svr.wait_until_ready();
  4327. {
  4328. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4329. "/ws");
  4330. auto res = client.connect();
  4331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4332. // The server dropped the connection instead of dying.
  4333. std::string msg;
  4334. EXPECT_FALSE(client.read(msg));
  4335. client.close();
  4336. }
  4337. EXPECT_TRUE(svr.is_running());
  4338. EXPECT_EQ(1, reported.load());
  4339. {
  4340. Client cli(HOST, port);
  4341. auto res = cli.Get("/ok");
  4342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4343. EXPECT_EQ(StatusCode::OK_200, res->status);
  4344. EXPECT_EQ("ok", res->body);
  4345. }
  4346. }
  4347. #ifdef CPPHTTPLIB_SSL_ENABLED
  4348. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4349. // SSLServer::process_and_close_socket() is a separate overload with its own
  4350. // guard, so it is exercised on its own.
  4351. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4352. ASSERT_TRUE(svr.is_valid());
  4353. svr.new_task_queue = [] { return new ThreadPool(1); };
  4354. std::atomic<int> reported{0};
  4355. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4356. if (err == Error::UserCallbackException) { reported++; }
  4357. });
  4358. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4359. res.set_content_provider(
  4360. 1024, "text/plain",
  4361. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4362. sink.write("hello", 5);
  4363. throw std::runtime_error("from the content provider");
  4364. });
  4365. });
  4366. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4367. res.set_content("ok", "text/plain");
  4368. });
  4369. auto port = svr.bind_to_any_port(HOST);
  4370. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4371. auto se = detail::scope_exit([&] {
  4372. svr.stop();
  4373. listen_thread.join();
  4374. ASSERT_FALSE(svr.is_running());
  4375. });
  4376. svr.wait_until_ready();
  4377. {
  4378. SSLClient cli(HOST, port);
  4379. cli.enable_server_certificate_verification(false);
  4380. cli.set_read_timeout(5, 0);
  4381. EXPECT_FALSE(cli.Get("/throw"));
  4382. }
  4383. EXPECT_TRUE(svr.is_running());
  4384. EXPECT_EQ(1, reported.load());
  4385. {
  4386. SSLClient cli(HOST, port);
  4387. cli.enable_server_certificate_verification(false);
  4388. auto res = cli.Get("/ok");
  4389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4390. EXPECT_EQ(StatusCode::OK_200, res->status);
  4391. EXPECT_EQ("ok", res->body);
  4392. }
  4393. }
  4394. #endif
  4395. #endif
  4396. TEST(NoContentTest, ContentLength) {
  4397. Server svr;
  4398. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4399. res.status = StatusCode::NoContent_204;
  4400. });
  4401. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4402. auto se = detail::scope_exit([&] {
  4403. svr.stop();
  4404. thread.join();
  4405. ASSERT_FALSE(svr.is_running());
  4406. });
  4407. svr.wait_until_ready();
  4408. {
  4409. Client cli(HOST, PORT);
  4410. auto res = cli.Get("/hi");
  4411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4412. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4413. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4414. }
  4415. }
  4416. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4417. #ifdef CPPHTTPLIB_SSL_ENABLED
  4418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4419. ASSERT_TRUE(svr.is_valid());
  4420. #else
  4421. Server svr;
  4422. #endif
  4423. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4424. if (req.path == "/routing_handler") {
  4425. res.set_header("PRE_ROUTING", "on");
  4426. res.set_content("Routing Handler", "text/plain");
  4427. return httplib::Server::HandlerResponse::Handled;
  4428. }
  4429. return httplib::Server::HandlerResponse::Unhandled;
  4430. });
  4431. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4432. res.set_content("Error", "text/html");
  4433. });
  4434. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4435. if (req.path == "/routing_handler") {
  4436. res.set_header("POST_ROUTING", "on");
  4437. }
  4438. });
  4439. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4440. res.set_content("Hello World!\n", "text/plain");
  4441. });
  4442. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4443. auto se = detail::scope_exit([&] {
  4444. svr.stop();
  4445. thread.join();
  4446. ASSERT_FALSE(svr.is_running());
  4447. });
  4448. svr.wait_until_ready();
  4449. {
  4450. #ifdef CPPHTTPLIB_SSL_ENABLED
  4451. SSLClient cli(HOST, PORT);
  4452. cli.enable_server_certificate_verification(false);
  4453. #else
  4454. Client cli(HOST, PORT);
  4455. #endif
  4456. auto res = cli.Get("/routing_handler");
  4457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4458. EXPECT_EQ(StatusCode::OK_200, res->status);
  4459. EXPECT_EQ("Routing Handler", res->body);
  4460. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4461. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4462. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4463. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4464. }
  4465. {
  4466. #ifdef CPPHTTPLIB_SSL_ENABLED
  4467. SSLClient cli(HOST, PORT);
  4468. cli.enable_server_certificate_verification(false);
  4469. #else
  4470. Client cli(HOST, PORT);
  4471. #endif
  4472. auto res = cli.Get("/hi");
  4473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4474. EXPECT_EQ(StatusCode::OK_200, res->status);
  4475. EXPECT_EQ("Hello World!\n", res->body);
  4476. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4477. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4478. }
  4479. {
  4480. #ifdef CPPHTTPLIB_SSL_ENABLED
  4481. SSLClient cli(HOST, PORT);
  4482. cli.enable_server_certificate_verification(false);
  4483. #else
  4484. Client cli(HOST, PORT);
  4485. #endif
  4486. auto res = cli.Get("/aaa");
  4487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4488. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4489. EXPECT_EQ("Error", res->body);
  4490. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4491. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4492. }
  4493. }
  4494. TEST(RequestHandlerTest, PreRequestHandler) {
  4495. auto route_path = "/user/:user";
  4496. Server svr;
  4497. svr.Get("/hi", [](const Request &, Response &res) {
  4498. res.set_content("hi", "text/plain");
  4499. });
  4500. svr.Get(route_path, [](const Request &req, Response &res) {
  4501. res.set_content(req.path_params.at("user"), "text/plain");
  4502. });
  4503. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4504. if (req.matched_route == route_path) {
  4505. auto user = req.path_params.at("user");
  4506. if (user != "john") {
  4507. res.status = StatusCode::Forbidden_403;
  4508. res.set_content("error", "text/html");
  4509. return Server::HandlerResponse::Handled;
  4510. }
  4511. }
  4512. return Server::HandlerResponse::Unhandled;
  4513. });
  4514. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4515. auto se = detail::scope_exit([&] {
  4516. svr.stop();
  4517. thread.join();
  4518. ASSERT_FALSE(svr.is_running());
  4519. });
  4520. svr.wait_until_ready();
  4521. Client cli(HOST, PORT);
  4522. {
  4523. auto res = cli.Get("/hi");
  4524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4525. EXPECT_EQ(StatusCode::OK_200, res->status);
  4526. EXPECT_EQ("hi", res->body);
  4527. }
  4528. {
  4529. auto res = cli.Get("/user/john");
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ(StatusCode::OK_200, res->status);
  4532. EXPECT_EQ("john", res->body);
  4533. }
  4534. {
  4535. auto res = cli.Get("/user/invalid-user");
  4536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4537. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4538. EXPECT_EQ("error", res->body);
  4539. }
  4540. }
  4541. // The pre-request handler must run before the request body is read, so a
  4542. // rejected request never forces the server to buffer a (potentially large)
  4543. // body. Here the posted body is larger than the payload limit: if the body
  4544. // were read first the server would answer 413, but because the pre-request
  4545. // handler runs first it answers 403 and the body is never read.
  4546. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4547. Server svr;
  4548. svr.set_payload_max_length(8);
  4549. auto handler_ran = false;
  4550. svr.Post("/reject", [&](const Request &req, Response &res) {
  4551. handler_ran = true;
  4552. res.set_content(req.body, "text/plain");
  4553. });
  4554. svr.Post("/accept", [](const Request &req, Response &res) {
  4555. res.set_content(req.body, "text/plain");
  4556. });
  4557. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4558. if (req.matched_route == "/reject") {
  4559. res.status = StatusCode::Forbidden_403;
  4560. res.set_content("denied", "text/plain");
  4561. return Server::HandlerResponse::Handled;
  4562. }
  4563. return Server::HandlerResponse::Unhandled;
  4564. });
  4565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4566. auto se = detail::scope_exit([&] {
  4567. svr.stop();
  4568. thread.join();
  4569. ASSERT_FALSE(svr.is_running());
  4570. });
  4571. svr.wait_until_ready();
  4572. Client cli(HOST, PORT);
  4573. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4574. // rejects with 403 before the body is read, so 413 is never reached.
  4575. {
  4576. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4578. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4579. EXPECT_EQ("denied", res->body);
  4580. EXPECT_FALSE(handler_ran);
  4581. }
  4582. // An approved route still reads the body and enforces the payload limit.
  4583. {
  4584. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4586. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4587. }
  4588. }
  4589. TEST(UserDataTest, BasicOperations) {
  4590. httplib::UserData ud;
  4591. // Initially empty
  4592. EXPECT_FALSE(ud.has("key"));
  4593. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4594. // set and get
  4595. ud.set("key", 42);
  4596. EXPECT_TRUE(ud.has("key"));
  4597. auto *p = ud.get<int>("key");
  4598. ASSERT_NE(nullptr, p);
  4599. EXPECT_EQ(42, *p);
  4600. // Type mismatch → nullptr
  4601. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4602. // Overwrite with different type
  4603. ud.set("key", std::string("hello"));
  4604. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4605. auto *s = ud.get<std::string>("key");
  4606. ASSERT_NE(nullptr, s);
  4607. EXPECT_EQ("hello", *s);
  4608. // erase
  4609. ud.erase("key");
  4610. EXPECT_FALSE(ud.has("key"));
  4611. // clear
  4612. ud.set("a", 1);
  4613. ud.set("b", 2);
  4614. ud.clear();
  4615. EXPECT_FALSE(ud.has("a"));
  4616. EXPECT_FALSE(ud.has("b"));
  4617. }
  4618. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4619. struct AuthCtx {
  4620. std::string user_id;
  4621. };
  4622. Server svr;
  4623. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4624. res.user_data.set("auth", AuthCtx{"alice"});
  4625. return Server::HandlerResponse::Unhandled;
  4626. });
  4627. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4628. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4629. ASSERT_NE(nullptr, ctx);
  4630. res.set_content("Hello " + ctx->user_id, "text/plain");
  4631. });
  4632. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4633. auto se = detail::scope_exit([&] {
  4634. svr.stop();
  4635. thread.join();
  4636. ASSERT_FALSE(svr.is_running());
  4637. });
  4638. svr.wait_until_ready();
  4639. Client cli(HOST, PORT);
  4640. auto res = cli.Get("/me");
  4641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4642. EXPECT_EQ(StatusCode::OK_200, res->status);
  4643. EXPECT_EQ("Hello alice", res->body);
  4644. }
  4645. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4646. struct RoleCtx {
  4647. std::string role;
  4648. };
  4649. Server svr;
  4650. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4651. res.user_data.set("role", RoleCtx{"admin"});
  4652. return Server::HandlerResponse::Unhandled;
  4653. });
  4654. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4655. auto *ctx = res.user_data.get<RoleCtx>("role");
  4656. ASSERT_NE(nullptr, ctx);
  4657. res.set_content(ctx->role, "text/plain");
  4658. });
  4659. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4660. auto se = detail::scope_exit([&] {
  4661. svr.stop();
  4662. thread.join();
  4663. ASSERT_FALSE(svr.is_running());
  4664. });
  4665. svr.wait_until_ready();
  4666. Client cli(HOST, PORT);
  4667. auto res = cli.Get("/role");
  4668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4669. EXPECT_EQ(StatusCode::OK_200, res->status);
  4670. EXPECT_EQ("admin", res->body);
  4671. }
  4672. TEST(InvalidFormatTest, StatusCode) {
  4673. Server svr;
  4674. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4675. res.set_content("Hello World!\n", "text/plain");
  4676. res.status = 9999; // Status should be a three-digit code...
  4677. });
  4678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4679. auto se = detail::scope_exit([&] {
  4680. svr.stop();
  4681. thread.join();
  4682. ASSERT_FALSE(svr.is_running());
  4683. });
  4684. svr.wait_until_ready();
  4685. {
  4686. Client cli(HOST, PORT);
  4687. auto res = cli.Get("/hi");
  4688. ASSERT_FALSE(res);
  4689. }
  4690. }
  4691. TEST(URLFragmentTest, WithFragment) {
  4692. Server svr;
  4693. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4694. EXPECT_TRUE(req.target == "/hi");
  4695. });
  4696. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4697. auto se = detail::scope_exit([&] {
  4698. svr.stop();
  4699. thread.join();
  4700. ASSERT_FALSE(svr.is_running());
  4701. });
  4702. svr.wait_until_ready();
  4703. {
  4704. Client cli(HOST, PORT);
  4705. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4706. EXPECT_TRUE(res);
  4707. EXPECT_EQ(StatusCode::OK_200, res->status);
  4708. res = cli.Get("/hi%23key1=val1=key2=val2");
  4709. EXPECT_TRUE(res);
  4710. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4711. }
  4712. }
  4713. TEST(HeaderWriter, SetHeaderWriter) {
  4714. Server svr;
  4715. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4716. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4717. return detail::write_headers(strm, hdrs);
  4718. });
  4719. svr.Get("/hi", [](const Request &req, Response &res) {
  4720. auto it = req.headers.find("CustomClientHeader");
  4721. EXPECT_TRUE(it != req.headers.end());
  4722. EXPECT_EQ(it->second, "CustomClientValue");
  4723. res.set_content("Hello World!\n", "text/plain");
  4724. });
  4725. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4726. auto se = detail::scope_exit([&] {
  4727. svr.stop();
  4728. thread.join();
  4729. ASSERT_FALSE(svr.is_running());
  4730. });
  4731. svr.wait_until_ready();
  4732. {
  4733. Client cli(HOST, PORT);
  4734. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4735. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4736. return detail::write_headers(strm, hdrs);
  4737. });
  4738. auto res = cli.Get("/hi");
  4739. EXPECT_TRUE(res);
  4740. EXPECT_EQ(StatusCode::OK_200, res->status);
  4741. auto it = res->headers.find("CustomServerHeader");
  4742. EXPECT_TRUE(it != res->headers.end());
  4743. EXPECT_EQ(it->second, "CustomServerValue");
  4744. }
  4745. }
  4746. class ServerTest : public ::testing::Test {
  4747. protected:
  4748. ServerTest()
  4749. : cli_(HOST, PORT)
  4750. #ifdef CPPHTTPLIB_SSL_ENABLED
  4751. ,
  4752. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4753. #endif
  4754. {
  4755. #ifdef CPPHTTPLIB_SSL_ENABLED
  4756. cli_.enable_server_certificate_verification(false);
  4757. #endif
  4758. // Allow LARGE_DATA (100MB) responses
  4759. cli_.set_payload_max_length(200 * 1024 * 1024);
  4760. }
  4761. virtual void SetUp() {
  4762. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4763. svr_.set_payload_max_length(200 * 1024 * 1024);
  4764. svr_.set_mount_point("/", "./www");
  4765. svr_.set_mount_point("/mount", "./www2");
  4766. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4767. svr_.Get("/hi",
  4768. [&](const Request & /*req*/, Response &res) {
  4769. res.set_content("Hello World!", "text/plain");
  4770. })
  4771. .Get("/file_content",
  4772. [&](const Request & /*req*/, Response &res) {
  4773. res.set_file_content("./www/dir/test.html");
  4774. })
  4775. .Get("/file_content_with_content_type",
  4776. [&](const Request & /*req*/, Response &res) {
  4777. res.set_file_content("./www/file", "text/plain");
  4778. })
  4779. .Get("/invalid_file_content",
  4780. [&](const Request & /*req*/, Response &res) {
  4781. res.set_file_content("./www/dir/invalid_file_path");
  4782. })
  4783. .Get("/http_response_splitting",
  4784. [&](const Request & /*req*/, Response &res) {
  4785. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4786. EXPECT_EQ(0U, res.headers.size());
  4787. EXPECT_FALSE(res.has_header("a"));
  4788. res.set_header("a", "1\nSet-Cookie: a=1");
  4789. EXPECT_EQ(0U, res.headers.size());
  4790. EXPECT_FALSE(res.has_header("a"));
  4791. res.set_header("a", "1\rSet-Cookie: a=1");
  4792. EXPECT_EQ(0U, res.headers.size());
  4793. EXPECT_FALSE(res.has_header("a"));
  4794. res.set_header("a\r\nb", "0");
  4795. EXPECT_EQ(0U, res.headers.size());
  4796. EXPECT_FALSE(res.has_header("a"));
  4797. res.set_header("a\rb", "0");
  4798. EXPECT_EQ(0U, res.headers.size());
  4799. EXPECT_FALSE(res.has_header("a"));
  4800. res.set_header("a\nb", "0");
  4801. EXPECT_EQ(0U, res.headers.size());
  4802. EXPECT_FALSE(res.has_header("a"));
  4803. res.set_redirect("1\r\nSet-Cookie: a=1");
  4804. EXPECT_EQ(0U, res.headers.size());
  4805. EXPECT_FALSE(res.has_header("Location"));
  4806. })
  4807. .Get("/slow",
  4808. [&](const Request & /*req*/, Response &res) {
  4809. std::this_thread::sleep_for(std::chrono::seconds(4));
  4810. res.set_content("slow", "text/plain");
  4811. })
  4812. #if 0
  4813. .Post("/slowpost",
  4814. [&](const Request & /*req*/, Response &res) {
  4815. std::this_thread::sleep_for(std::chrono::seconds(2));
  4816. res.set_content("slow", "text/plain");
  4817. })
  4818. #endif
  4819. .Get("/remote_addr",
  4820. [&](const Request &req, Response &res) {
  4821. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4822. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4823. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4824. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4825. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4826. #endif
  4827. res.set_content(req.remote_addr, "text/plain");
  4828. })
  4829. .Get("/local_addr",
  4830. [&](const Request &req, Response &res) {
  4831. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4832. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4833. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4834. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4835. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4836. #endif
  4837. auto local_addr = req.local_addr;
  4838. auto local_port = std::to_string(req.local_port);
  4839. res.set_content(local_addr.append(":").append(local_port),
  4840. "text/plain");
  4841. })
  4842. .Get("/endwith%",
  4843. [&](const Request & /*req*/, Response &res) {
  4844. res.set_content("Hello World!", "text/plain");
  4845. })
  4846. .Get("/a\\+\\+b",
  4847. [&](const Request &req, Response &res) {
  4848. ASSERT_TRUE(req.has_param("a +b"));
  4849. auto val = req.get_param_value("a +b");
  4850. res.set_content(val, "text/plain");
  4851. })
  4852. .Get("/", [&](const Request & /*req*/,
  4853. Response &res) { res.set_redirect("/hi"); })
  4854. .Post("/1",
  4855. [](const Request & /*req*/, Response &res) {
  4856. res.set_redirect("/2", StatusCode::SeeOther_303);
  4857. })
  4858. .Get("/2",
  4859. [](const Request & /*req*/, Response &res) {
  4860. res.set_content("redirected.", "text/plain");
  4861. res.status = StatusCode::OK_200;
  4862. })
  4863. .Post("/person",
  4864. [&](const Request &req, Response &res) {
  4865. if (req.has_param("name") && req.has_param("note")) {
  4866. persons_[req.get_param_value("name")] =
  4867. req.get_param_value("note");
  4868. } else {
  4869. res.status = StatusCode::BadRequest_400;
  4870. }
  4871. })
  4872. .Put("/person",
  4873. [&](const Request &req, Response &res) {
  4874. if (req.has_param("name") && req.has_param("note")) {
  4875. persons_[req.get_param_value("name")] =
  4876. req.get_param_value("note");
  4877. } else {
  4878. res.status = StatusCode::BadRequest_400;
  4879. }
  4880. })
  4881. .Get("/person/(.*)",
  4882. [&](const Request &req, Response &res) {
  4883. string name = req.matches[1];
  4884. if (persons_.find(name) != persons_.end()) {
  4885. auto note = persons_[name];
  4886. res.set_content(note, "text/plain");
  4887. } else {
  4888. res.status = StatusCode::NotFound_404;
  4889. }
  4890. })
  4891. .Delete("/person",
  4892. [&](const Request &req, Response &res) {
  4893. if (req.has_param("name")) {
  4894. string name = req.get_param_value("name");
  4895. if (persons_.find(name) != persons_.end()) {
  4896. persons_.erase(name);
  4897. res.set_content("DELETED", "text/plain");
  4898. } else {
  4899. res.status = StatusCode::NotFound_404;
  4900. }
  4901. } else {
  4902. res.status = StatusCode::BadRequest_400;
  4903. }
  4904. })
  4905. .Post("/x-www-form-urlencoded-json",
  4906. [&](const Request &req, Response &res) {
  4907. auto json = req.get_param_value("json");
  4908. ASSERT_EQ(JSON_DATA, json);
  4909. res.set_content(json, "appliation/json");
  4910. res.status = StatusCode::OK_200;
  4911. })
  4912. .Get("/streamed-chunked",
  4913. [&](const Request & /*req*/, Response &res) {
  4914. res.set_chunked_content_provider(
  4915. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4916. sink.os << "123";
  4917. sink.os << "456";
  4918. sink.os << "789";
  4919. sink.done();
  4920. return true;
  4921. });
  4922. })
  4923. .Get("/streamed-chunked-with-prohibited-trailer",
  4924. [&](const Request & /*req*/, Response &res) {
  4925. auto i = new int(0);
  4926. // Declare both a prohibited trailer (Content-Length) and an
  4927. // allowed one
  4928. res.set_header("Trailer", "Content-Length, X-Allowed");
  4929. res.set_chunked_content_provider(
  4930. "text/plain",
  4931. [i](size_t /*offset*/, DataSink &sink) {
  4932. switch (*i) {
  4933. case 0: sink.os << "123"; break;
  4934. case 1: sink.os << "456"; break;
  4935. case 2: sink.os << "789"; break;
  4936. case 3: {
  4937. sink.done_with_trailer(
  4938. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4939. } break;
  4940. }
  4941. (*i)++;
  4942. return true;
  4943. },
  4944. [i](bool success) {
  4945. EXPECT_TRUE(success);
  4946. delete i;
  4947. });
  4948. })
  4949. .Get("/streamed-chunked2",
  4950. [&](const Request & /*req*/, Response &res) {
  4951. auto i = new int(0);
  4952. res.set_chunked_content_provider(
  4953. "text/plain",
  4954. [i](size_t /*offset*/, DataSink &sink) {
  4955. switch (*i) {
  4956. case 0: sink.os << "123"; break;
  4957. case 1: sink.os << "456"; break;
  4958. case 2: sink.os << "789"; break;
  4959. case 3: sink.done(); break;
  4960. }
  4961. (*i)++;
  4962. return true;
  4963. },
  4964. [i](bool success) {
  4965. EXPECT_TRUE(success);
  4966. delete i;
  4967. });
  4968. })
  4969. .Get("/streamed-chunked-with-trailer",
  4970. [&](const Request & /*req*/, Response &res) {
  4971. auto i = new int(0);
  4972. res.set_header("Trailer", "Dummy1, Dummy2");
  4973. res.set_chunked_content_provider(
  4974. "text/plain",
  4975. [i](size_t /*offset*/, DataSink &sink) {
  4976. switch (*i) {
  4977. case 0: sink.os << "123"; break;
  4978. case 1: sink.os << "456"; break;
  4979. case 2: sink.os << "789"; break;
  4980. case 3: {
  4981. sink.done_with_trailer(
  4982. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4983. } break;
  4984. }
  4985. (*i)++;
  4986. return true;
  4987. },
  4988. [i](bool success) {
  4989. EXPECT_TRUE(success);
  4990. delete i;
  4991. });
  4992. })
  4993. .Get("/streamed",
  4994. [&](const Request & /*req*/, Response &res) {
  4995. res.set_content_provider(
  4996. 6, "text/plain",
  4997. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4998. sink.os << (offset < 3 ? "a" : "b");
  4999. return true;
  5000. });
  5001. })
  5002. .Get("/streamed-without-length",
  5003. [&](const Request & /*req*/, Response &res) {
  5004. auto data = new std::string("abcdefg");
  5005. res.set_content_provider(
  5006. "text/plain",
  5007. [data](size_t offset, DataSink &sink) {
  5008. if (offset < data->size()) {
  5009. sink.os << data->substr(offset);
  5010. }
  5011. sink.done();
  5012. return true;
  5013. },
  5014. [data](bool success) {
  5015. EXPECT_TRUE(success);
  5016. delete data;
  5017. });
  5018. })
  5019. .Get("/streamed-with-range",
  5020. [&](const Request &req, Response &res) {
  5021. auto data = new std::string("abcdefg");
  5022. // An explicit status keeps the server from picking the 206 it
  5023. // would otherwise choose for a ranged request, so the response
  5024. // is not a partial representation.
  5025. auto status = req.get_param_value("status");
  5026. if (status == "200") {
  5027. res.status = StatusCode::OK_200;
  5028. } else if (status == "403") {
  5029. res.status = StatusCode::Forbidden_403;
  5030. }
  5031. res.set_content_provider(
  5032. data->size(), "text/plain",
  5033. [data](size_t offset, size_t length, DataSink &sink) {
  5034. size_t DATA_CHUNK_SIZE = 4;
  5035. const auto &d = *data;
  5036. auto out_len =
  5037. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5038. auto ret =
  5039. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5040. EXPECT_TRUE(ret);
  5041. return true;
  5042. },
  5043. [data, &req](bool success) {
  5044. EXPECT_EQ(success, !req.has_param("error"));
  5045. delete data;
  5046. });
  5047. })
  5048. .Get("/streamed-cancel",
  5049. [&](const Request & /*req*/, Response &res) {
  5050. res.set_content_provider(
  5051. size_t(-1), "text/plain",
  5052. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5053. sink.os << "data_chunk";
  5054. return true;
  5055. });
  5056. })
  5057. .Get("/regex-with-delimiter",
  5058. [&](const Request &req, Response & /*res*/) {
  5059. ASSERT_TRUE(req.has_param("key"));
  5060. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5061. })
  5062. .Get("/with-range",
  5063. [&](const Request & /*req*/, Response &res) {
  5064. res.set_content("abcdefg", "text/plain");
  5065. })
  5066. .Get("/test-start-time",
  5067. [&](const Request &req, Response & /*res*/) {
  5068. EXPECT_NE(req.start_time_,
  5069. std::chrono::steady_clock::time_point::min());
  5070. })
  5071. .Get("/with-range-customized-response",
  5072. [&](const Request & /*req*/, Response &res) {
  5073. res.status = StatusCode::BadRequest_400;
  5074. res.set_content(JSON_DATA, "application/json");
  5075. })
  5076. .Post("/chunked",
  5077. [&](const Request &req, Response & /*res*/) {
  5078. EXPECT_EQ(req.body, "dechunked post body");
  5079. })
  5080. .Post("/large-chunked",
  5081. [&](const Request &req, Response & /*res*/) {
  5082. std::string expected(6 * 30 * 1024u, 'a');
  5083. EXPECT_EQ(req.body, expected);
  5084. })
  5085. .Post("/multipart",
  5086. [&](const Request &req, Response & /*res*/) {
  5087. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5088. req.form.get_field_count("text2") +
  5089. req.form.get_field_count("file3") +
  5090. req.form.get_field_count("file4"));
  5091. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5092. req.form.get_file_count("file2"));
  5093. ASSERT_TRUE(!req.form.has_file("???"));
  5094. ASSERT_TRUE(!req.form.has_field("???"));
  5095. ASSERT_TRUE(req.body.empty());
  5096. {
  5097. const auto &text = req.form.get_field("text1");
  5098. EXPECT_EQ("text default", text);
  5099. }
  5100. {
  5101. const auto &text = req.form.get_field("text2");
  5102. EXPECT_EQ("aωb", text);
  5103. }
  5104. {
  5105. const auto &file = req.form.get_file("file1");
  5106. EXPECT_EQ("hello.txt", file.filename);
  5107. EXPECT_EQ("text/plain", file.content_type);
  5108. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5109. }
  5110. {
  5111. const auto &file = req.form.get_file("file2");
  5112. EXPECT_EQ("world.json", file.filename);
  5113. EXPECT_EQ("application/json", file.content_type);
  5114. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5115. }
  5116. {
  5117. const auto &text = req.form.get_field("file3");
  5118. EXPECT_EQ(0u, text.size());
  5119. }
  5120. {
  5121. const auto &text = req.form.get_field("file4");
  5122. EXPECT_EQ(0u, text.size());
  5123. }
  5124. })
  5125. .Post("/multipart/multi_file_values",
  5126. [&](const Request &req, Response & /*res*/) {
  5127. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5128. req.form.get_field_count("multi_text1"));
  5129. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5130. ASSERT_TRUE(!req.form.has_file("???"));
  5131. ASSERT_TRUE(!req.form.has_field("???"));
  5132. ASSERT_TRUE(req.body.empty());
  5133. {
  5134. const auto &text = req.form.get_field("text");
  5135. EXPECT_EQ("default text", text);
  5136. }
  5137. {
  5138. const auto &text1_values = req.form.get_fields("multi_text1");
  5139. EXPECT_EQ(2u, text1_values.size());
  5140. EXPECT_EQ("aaaaa", text1_values[0]);
  5141. EXPECT_EQ("bbbbb", text1_values[1]);
  5142. }
  5143. {
  5144. const auto &file1_values = req.form.get_files("multi_file1");
  5145. EXPECT_EQ(2u, file1_values.size());
  5146. auto file1 = file1_values[0];
  5147. EXPECT_EQ(file1.filename, "hello.txt");
  5148. EXPECT_EQ(file1.content_type, "text/plain");
  5149. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5150. auto file2 = file1_values[1];
  5151. EXPECT_EQ(file2.filename, "world.json");
  5152. EXPECT_EQ(file2.content_type, "application/json");
  5153. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5154. }
  5155. })
  5156. .Post("/empty",
  5157. [&](const Request &req, Response &res) {
  5158. EXPECT_EQ(req.body, "");
  5159. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5160. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5161. res.set_content("empty", "text/plain");
  5162. })
  5163. .Post("/empty-no-content-type",
  5164. [&](const Request &req, Response &res) {
  5165. EXPECT_EQ(req.body, "");
  5166. EXPECT_FALSE(req.has_header("Content-Type"));
  5167. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5168. res.set_content("empty-no-content-type", "text/plain");
  5169. })
  5170. .Post("/path-only",
  5171. [&](const Request &req, Response &res) {
  5172. EXPECT_EQ(req.body, "");
  5173. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5174. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5175. res.set_content("path-only", "text/plain");
  5176. })
  5177. .Post("/path-headers-only",
  5178. [&](const Request &req, Response &res) {
  5179. EXPECT_EQ(req.body, "");
  5180. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5181. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5182. EXPECT_EQ("world", req.get_header_value("hello"));
  5183. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5184. res.set_content("path-headers-only", "text/plain");
  5185. })
  5186. .Post("/post-large",
  5187. [&](const Request &req, Response &res) {
  5188. EXPECT_EQ(req.body, LARGE_DATA);
  5189. res.set_content(req.body, "text/plain");
  5190. })
  5191. .Post("/post-loopback",
  5192. [&](const Request &, Response &res,
  5193. ContentReader const &content_reader) {
  5194. std::string body;
  5195. content_reader([&](const char *data, size_t data_length) {
  5196. body.append(data, data_length);
  5197. return true;
  5198. });
  5199. res.set_content(body, "text/plain");
  5200. })
  5201. .Put("/put-loopback",
  5202. [&](const Request &, Response &res,
  5203. ContentReader const &content_reader) {
  5204. std::string body;
  5205. content_reader([&](const char *data, size_t data_length) {
  5206. body.append(data, data_length);
  5207. return true;
  5208. });
  5209. res.set_content(body, "text/plain");
  5210. })
  5211. .Patch("/patch-loopback",
  5212. [&](const Request &, Response &res,
  5213. ContentReader const &content_reader) {
  5214. std::string body;
  5215. content_reader([&](const char *data, size_t data_length) {
  5216. body.append(data, data_length);
  5217. return true;
  5218. });
  5219. res.set_content(body, "text/plain");
  5220. })
  5221. .Put("/empty-no-content-type",
  5222. [&](const Request &req, Response &res) {
  5223. EXPECT_EQ(req.body, "");
  5224. EXPECT_FALSE(req.has_header("Content-Type"));
  5225. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5226. res.set_content("empty-no-content-type", "text/plain");
  5227. })
  5228. .Put("/put",
  5229. [&](const Request &req, Response &res) {
  5230. EXPECT_EQ(req.body, "PUT");
  5231. res.set_content(req.body, "text/plain");
  5232. })
  5233. .Put("/put-large",
  5234. [&](const Request &req, Response &res) {
  5235. EXPECT_EQ(req.body, LARGE_DATA);
  5236. res.set_content(req.body, "text/plain");
  5237. })
  5238. .Patch("/patch",
  5239. [&](const Request &req, Response &res) {
  5240. EXPECT_EQ(req.body, "PATCH");
  5241. res.set_content(req.body, "text/plain");
  5242. })
  5243. .Delete("/delete",
  5244. [&](const Request & /*req*/, Response &res) {
  5245. res.set_content("DELETE", "text/plain");
  5246. })
  5247. .Delete("/delete-body",
  5248. [&](const Request &req, Response &res) {
  5249. EXPECT_EQ(req.body, "content");
  5250. res.set_content(req.body, "text/plain");
  5251. })
  5252. .Options(R"(\*)",
  5253. [&](const Request & /*req*/, Response &res) {
  5254. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5255. })
  5256. .CustomRoute("PROPFIND", "/dav/:id",
  5257. [&](const Request &req, Response &res) {
  5258. res.set_header("x-body-size",
  5259. std::to_string(req.body.size()));
  5260. res.set_header("x-matched-route", req.matched_route);
  5261. res.set_header("x-dav-id", req.path_params.at("id"));
  5262. res.status = StatusCode::MultiStatus_207;
  5263. res.set_content(req.body, "application/xml");
  5264. })
  5265. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5266. [&](const Request &req, Response &res) {
  5267. res.set_header("x-dav-match", req.matches[1]);
  5268. res.status = StatusCode::MultiStatus_207;
  5269. })
  5270. .CustomRoute("MKCOL", "/dav-mkcol",
  5271. [&](const Request &req, Response &res) {
  5272. EXPECT_TRUE(req.body.empty());
  5273. res.status = StatusCode::Created_201;
  5274. })
  5275. .CustomRoute(
  5276. "REPORT", "/dav-report",
  5277. [&](const Request & /*req*/, Response &res,
  5278. const ContentReader &content_reader) {
  5279. std::string body;
  5280. content_reader([&](const char *data, size_t data_length) {
  5281. body.append(data, data_length);
  5282. return true;
  5283. });
  5284. res.set_header("x-body-size", std::to_string(body.size()));
  5285. res.status = StatusCode::MultiStatus_207;
  5286. res.set_content(body, "application/xml");
  5287. })
  5288. .Get("/request-target",
  5289. [&](const Request &req, Response & /*res*/) {
  5290. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5291. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5292. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5293. })
  5294. .Get("/long-query-value",
  5295. [&](const Request &req, Response & /*res*/) {
  5296. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5297. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5298. })
  5299. .Get("/too-long-query-value",
  5300. [&](const Request &req, Response & /*res*/) {
  5301. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5302. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5303. })
  5304. .Get("/array-param",
  5305. [&](const Request &req, Response & /*res*/) {
  5306. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5307. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5308. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5309. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5310. })
  5311. .Get("/array-param-values",
  5312. [&](const Request &req, Response & /*res*/) {
  5313. auto values = req.get_param_values("array");
  5314. EXPECT_EQ(3u, values.size());
  5315. EXPECT_EQ("value1", values[0]);
  5316. EXPECT_EQ("value2", values[1]);
  5317. EXPECT_EQ("value3", values[2]);
  5318. auto empty = req.get_param_values("nonexistent");
  5319. EXPECT_TRUE(empty.empty());
  5320. })
  5321. .Post("/validate-no-multiple-headers",
  5322. [&](const Request &req, Response & /*res*/) {
  5323. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5324. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5325. })
  5326. .Post("/content_receiver",
  5327. [&](const Request &req, Response &res,
  5328. const ContentReader &content_reader) {
  5329. if (req.is_multipart_form_data()) {
  5330. std::vector<FormData> items;
  5331. content_reader(
  5332. [&](const FormData &file) {
  5333. items.push_back(file);
  5334. return true;
  5335. },
  5336. [&](const char *data, size_t data_length) {
  5337. items.back().content.append(data, data_length);
  5338. return true;
  5339. });
  5340. EXPECT_EQ(5u, items.size());
  5341. {
  5342. const auto &file = get_file_value(items, "text1");
  5343. EXPECT_TRUE(file.filename.empty());
  5344. EXPECT_EQ("text default", file.content);
  5345. }
  5346. {
  5347. const auto &file = get_file_value(items, "text2");
  5348. EXPECT_TRUE(file.filename.empty());
  5349. EXPECT_EQ("aωb", file.content);
  5350. }
  5351. {
  5352. const auto &file = get_file_value(items, "file1");
  5353. EXPECT_EQ("hello.txt", file.filename);
  5354. EXPECT_EQ("text/plain", file.content_type);
  5355. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5356. }
  5357. {
  5358. const auto &file = get_file_value(items, "file2");
  5359. EXPECT_EQ("world.json", file.filename);
  5360. EXPECT_EQ("application/json", file.content_type);
  5361. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5362. }
  5363. {
  5364. const auto &file = get_file_value(items, "file3");
  5365. EXPECT_TRUE(file.filename.empty());
  5366. EXPECT_EQ("application/octet-stream", file.content_type);
  5367. EXPECT_EQ(0u, file.content.size());
  5368. }
  5369. } else {
  5370. std::string body;
  5371. content_reader([&](const char *data, size_t data_length) {
  5372. EXPECT_EQ(7U, data_length);
  5373. body.append(data, data_length);
  5374. return true;
  5375. });
  5376. EXPECT_EQ(body, "content");
  5377. res.set_content(body, "text/plain");
  5378. }
  5379. })
  5380. .Put("/content_receiver",
  5381. [&](const Request & /*req*/, Response &res,
  5382. const ContentReader &content_reader) {
  5383. std::string body;
  5384. content_reader([&](const char *data, size_t data_length) {
  5385. body.append(data, data_length);
  5386. return true;
  5387. });
  5388. EXPECT_EQ(body, "content");
  5389. res.set_content(body, "text/plain");
  5390. })
  5391. .Patch("/content_receiver",
  5392. [&](const Request & /*req*/, Response &res,
  5393. const ContentReader &content_reader) {
  5394. std::string body;
  5395. content_reader([&](const char *data, size_t data_length) {
  5396. body.append(data, data_length);
  5397. return true;
  5398. });
  5399. EXPECT_EQ(body, "content");
  5400. res.set_content(body, "text/plain");
  5401. })
  5402. .Post("/query-string-and-body",
  5403. [&](const Request &req, Response & /*res*/) {
  5404. ASSERT_TRUE(req.has_param("key"));
  5405. EXPECT_EQ(req.get_param_value("key"), "value");
  5406. EXPECT_EQ(req.body, "content");
  5407. })
  5408. .Get("/last-request",
  5409. [&](const Request &req, Response & /*res*/) {
  5410. EXPECT_EQ("close", req.get_header_value("Connection"));
  5411. })
  5412. .Get(R"(/redirect/(\d+))",
  5413. [&](const Request &req, Response &res) {
  5414. auto num = std::stoi(req.matches[1]) + 1;
  5415. std::string url = "/redirect/" + std::to_string(num);
  5416. res.set_redirect(url);
  5417. })
  5418. .Post("/binary",
  5419. [&](const Request &req, Response &res) {
  5420. EXPECT_EQ(4U, req.body.size());
  5421. EXPECT_EQ("application/octet-stream",
  5422. req.get_header_value("Content-Type"));
  5423. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5424. res.set_content(req.body, "application/octet-stream");
  5425. })
  5426. .Put("/binary",
  5427. [&](const Request &req, Response &res) {
  5428. EXPECT_EQ(4U, req.body.size());
  5429. EXPECT_EQ("application/octet-stream",
  5430. req.get_header_value("Content-Type"));
  5431. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5432. res.set_content(req.body, "application/octet-stream");
  5433. })
  5434. .Patch("/binary",
  5435. [&](const Request &req, Response &res) {
  5436. EXPECT_EQ(4U, req.body.size());
  5437. EXPECT_EQ("application/octet-stream",
  5438. req.get_header_value("Content-Type"));
  5439. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5440. res.set_content(req.body, "application/octet-stream");
  5441. })
  5442. .Delete("/binary",
  5443. [&](const Request &req, Response &res) {
  5444. EXPECT_EQ(4U, req.body.size());
  5445. EXPECT_EQ("application/octet-stream",
  5446. req.get_header_value("Content-Type"));
  5447. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5448. res.set_content(req.body, "application/octet-stream");
  5449. })
  5450. .Get("/issue1772",
  5451. [&](const Request & /*req*/, Response &res) {
  5452. res.status = 401;
  5453. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5454. })
  5455. .Delete("/issue609",
  5456. [](const httplib::Request &, httplib::Response &res,
  5457. const httplib::ContentReader &) {
  5458. res.set_content("ok", "text/plain");
  5459. })
  5460. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5461. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5462. .Get("/compress",
  5463. [&](const Request & /*req*/, Response &res) {
  5464. res.set_content(
  5465. "12345678901234567890123456789012345678901234567890123456789"
  5466. "01234567890123456789012345678901234567890",
  5467. "text/plain");
  5468. })
  5469. .Get("/compress-with-charset",
  5470. [&](const Request & /*req*/, Response &res) {
  5471. res.set_content(
  5472. "12345678901234567890123456789012345678901234567890123456789"
  5473. "01234567890123456789012345678901234567890",
  5474. "application/json; charset=utf-8");
  5475. })
  5476. .Get("/nocompress",
  5477. [&](const Request & /*req*/, Response &res) {
  5478. res.set_content(
  5479. "12345678901234567890123456789012345678901234567890123456789"
  5480. "01234567890123456789012345678901234567890",
  5481. "application/octet-stream");
  5482. })
  5483. .Post("/compress-multipart",
  5484. [&](const Request &req, Response & /*res*/) {
  5485. EXPECT_EQ(2u, req.form.fields.size());
  5486. ASSERT_TRUE(!req.form.has_field("???"));
  5487. {
  5488. const auto &text = req.form.get_field("key1");
  5489. EXPECT_EQ("test", text);
  5490. }
  5491. {
  5492. const auto &text = req.form.get_field("key2");
  5493. EXPECT_EQ("--abcdefg123", text);
  5494. }
  5495. })
  5496. #endif
  5497. ;
  5498. persons_["john"] = "programmer";
  5499. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5500. svr_.wait_until_ready();
  5501. }
  5502. virtual void TearDown() {
  5503. svr_.stop();
  5504. if (!request_threads_.empty()) {
  5505. std::this_thread::sleep_for(std::chrono::seconds(1));
  5506. for (auto &t : request_threads_) {
  5507. t.join();
  5508. }
  5509. }
  5510. t_.join();
  5511. }
  5512. map<string, string> persons_;
  5513. #ifdef CPPHTTPLIB_SSL_ENABLED
  5514. SSLClient cli_;
  5515. SSLServer svr_;
  5516. #else
  5517. Client cli_;
  5518. Server svr_;
  5519. #endif
  5520. thread t_;
  5521. std::vector<thread> request_threads_;
  5522. };
  5523. TEST_F(ServerTest, GetMethod200) {
  5524. auto res = cli_.Get("/hi");
  5525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5526. EXPECT_EQ("HTTP/1.1", res->version);
  5527. EXPECT_EQ(StatusCode::OK_200, res->status);
  5528. EXPECT_EQ("OK", res->reason);
  5529. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5530. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5531. EXPECT_EQ("Hello World!", res->body);
  5532. }
  5533. TEST_F(ServerTest, GetEmptyFile) {
  5534. auto res = cli_.Get("/empty_file");
  5535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5536. EXPECT_EQ(StatusCode::OK_200, res->status);
  5537. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5538. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5539. EXPECT_EQ("", res->body);
  5540. }
  5541. TEST_F(ServerTest, GetFileContent) {
  5542. auto res = cli_.Get("/file_content");
  5543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5544. EXPECT_EQ(StatusCode::OK_200, res->status);
  5545. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5546. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5547. EXPECT_EQ("test.html", res->body);
  5548. }
  5549. TEST_F(ServerTest, GetFileContentWithRange) {
  5550. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5553. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5554. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5555. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5556. EXPECT_EQ("est", res->body);
  5557. }
  5558. TEST_F(ServerTest, GetFileContentWithContentType) {
  5559. auto res = cli_.Get("/file_content_with_content_type");
  5560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5561. EXPECT_EQ(StatusCode::OK_200, res->status);
  5562. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5563. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5564. EXPECT_EQ("file\n", res->body);
  5565. }
  5566. TEST_F(ServerTest, GetInvalidFileContent) {
  5567. auto res = cli_.Get("/invalid_file_content");
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5570. }
  5571. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5572. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5574. EXPECT_EQ("HTTP/1.1", res->version);
  5575. EXPECT_EQ(StatusCode::OK_200, res->status);
  5576. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5577. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5578. EXPECT_EQ("Hello World!", res->body);
  5579. }
  5580. TEST_F(ServerTest, GetMethod302) {
  5581. auto res = cli_.Get("/");
  5582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5583. EXPECT_EQ(StatusCode::Found_302, res->status);
  5584. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5585. }
  5586. TEST_F(ServerTest, GetMethod302Redirect) {
  5587. cli_.set_follow_location(true);
  5588. auto res = cli_.Get("/");
  5589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5590. EXPECT_EQ(StatusCode::OK_200, res->status);
  5591. EXPECT_EQ("Hello World!", res->body);
  5592. EXPECT_EQ("/hi", res->location);
  5593. }
  5594. TEST_F(ServerTest, GetMethod404) {
  5595. auto res = cli_.Get("/invalid");
  5596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5597. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5598. }
  5599. TEST_F(ServerTest, HeadMethod200) {
  5600. auto res = cli_.Head("/hi");
  5601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5602. EXPECT_EQ(StatusCode::OK_200, res->status);
  5603. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5604. EXPECT_TRUE(res->body.empty());
  5605. }
  5606. TEST_F(ServerTest, HeadMethod200Static) {
  5607. auto res = cli_.Head("/mount/dir/index.html");
  5608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5609. EXPECT_EQ(StatusCode::OK_200, res->status);
  5610. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5611. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5612. EXPECT_TRUE(res->body.empty());
  5613. }
  5614. TEST_F(ServerTest, HeadMethod404) {
  5615. auto res = cli_.Head("/invalid");
  5616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5617. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5618. EXPECT_TRUE(res->body.empty());
  5619. }
  5620. TEST_F(ServerTest, GetMethodPersonJohn) {
  5621. auto res = cli_.Get("/person/john");
  5622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5623. EXPECT_EQ(StatusCode::OK_200, res->status);
  5624. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5625. EXPECT_EQ("programmer", res->body);
  5626. }
  5627. TEST_F(ServerTest, PostMethod1) {
  5628. auto res = cli_.Get("/person/john1");
  5629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5630. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5631. res = cli_.Post("/person", "name=john1&note=coder",
  5632. "application/x-www-form-urlencoded");
  5633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5634. ASSERT_EQ(StatusCode::OK_200, res->status);
  5635. res = cli_.Get("/person/john1");
  5636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5637. ASSERT_EQ(StatusCode::OK_200, res->status);
  5638. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5639. ASSERT_EQ("coder", res->body);
  5640. }
  5641. TEST_F(ServerTest, PostMethod2) {
  5642. auto res = cli_.Get("/person/john2");
  5643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5644. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5645. Params params;
  5646. params.emplace("name", "john2");
  5647. params.emplace("note", "coder");
  5648. res = cli_.Post("/person", params);
  5649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5650. ASSERT_EQ(StatusCode::OK_200, res->status);
  5651. res = cli_.Get("/person/john2");
  5652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5653. ASSERT_EQ(StatusCode::OK_200, res->status);
  5654. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5655. ASSERT_EQ("coder", res->body);
  5656. }
  5657. TEST_F(ServerTest, PutMethod3) {
  5658. auto res = cli_.Get("/person/john3");
  5659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5660. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5661. Params params;
  5662. params.emplace("name", "john3");
  5663. params.emplace("note", "coder");
  5664. res = cli_.Put("/person", params);
  5665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5666. ASSERT_EQ(StatusCode::OK_200, res->status);
  5667. res = cli_.Get("/person/john3");
  5668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5669. ASSERT_EQ(StatusCode::OK_200, res->status);
  5670. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5671. ASSERT_EQ("coder", res->body);
  5672. }
  5673. TEST_F(ServerTest, DeleteMethod1) {
  5674. auto res = cli_.Get("/person/john4");
  5675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5676. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5677. Params params;
  5678. params.emplace("name", "john4");
  5679. params.emplace("note", "coder");
  5680. res = cli_.Post("/person", params);
  5681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5682. ASSERT_EQ(StatusCode::OK_200, res->status);
  5683. res = cli_.Get("/person/john4");
  5684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5685. ASSERT_EQ(StatusCode::OK_200, res->status);
  5686. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5687. ASSERT_EQ("coder", res->body);
  5688. Params delete_params;
  5689. delete_params.emplace("name", "john4");
  5690. res = cli_.Delete("/person", delete_params);
  5691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5692. ASSERT_EQ(StatusCode::OK_200, res->status);
  5693. ASSERT_EQ("DELETED", res->body);
  5694. res = cli_.Get("/person/john4");
  5695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5696. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5697. }
  5698. TEST_F(ServerTest, DeleteMethod2) {
  5699. auto res = cli_.Get("/person/john5");
  5700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5701. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5702. Params params;
  5703. params.emplace("name", "john5");
  5704. params.emplace("note", "developer");
  5705. res = cli_.Post("/person", params);
  5706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5707. ASSERT_EQ(StatusCode::OK_200, res->status);
  5708. res = cli_.Get("/person/john5");
  5709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5710. ASSERT_EQ(StatusCode::OK_200, res->status);
  5711. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5712. ASSERT_EQ("developer", res->body);
  5713. Params delete_params;
  5714. delete_params.emplace("name", "john5");
  5715. Headers headers;
  5716. headers.emplace("Custom-Header", "test-value");
  5717. res = cli_.Delete("/person", headers, delete_params);
  5718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5719. ASSERT_EQ(StatusCode::OK_200, res->status);
  5720. ASSERT_EQ("DELETED", res->body);
  5721. res = cli_.Get("/person/john5");
  5722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5723. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5724. }
  5725. TEST_F(ServerTest, DeleteMethod3) {
  5726. auto res = cli_.Get("/person/john6");
  5727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5728. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5729. Params params;
  5730. params.emplace("name", "john6");
  5731. params.emplace("note", "tester");
  5732. res = cli_.Post("/person", params);
  5733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5734. ASSERT_EQ(StatusCode::OK_200, res->status);
  5735. res = cli_.Get("/person/john6");
  5736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5737. ASSERT_EQ(StatusCode::OK_200, res->status);
  5738. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5739. ASSERT_EQ("tester", res->body);
  5740. Params delete_params;
  5741. delete_params.emplace("name", "john6");
  5742. Headers headers;
  5743. headers.emplace("Custom-Header", "test-value");
  5744. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. ASSERT_EQ(StatusCode::OK_200, res->status);
  5747. ASSERT_EQ("DELETED", res->body);
  5748. res = cli_.Get("/person/john6");
  5749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5750. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5751. }
  5752. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5753. Params params;
  5754. params.emplace("json", JSON_DATA);
  5755. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. ASSERT_EQ(StatusCode::OK_200, res->status);
  5758. ASSERT_EQ(JSON_DATA, res->body);
  5759. }
  5760. TEST_F(ServerTest, PostEmptyContent) {
  5761. auto res = cli_.Post("/empty", "", "text/plain");
  5762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5763. ASSERT_EQ(StatusCode::OK_200, res->status);
  5764. ASSERT_EQ("empty", res->body);
  5765. }
  5766. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5767. auto res = cli_.Post("/empty-no-content-type");
  5768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5769. ASSERT_EQ(StatusCode::OK_200, res->status);
  5770. ASSERT_EQ("empty-no-content-type", res->body);
  5771. }
  5772. TEST_F(ServerTest, PostPathOnly) {
  5773. auto res = cli_.Post("/path-only");
  5774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5775. ASSERT_EQ(StatusCode::OK_200, res->status);
  5776. ASSERT_EQ("path-only", res->body);
  5777. }
  5778. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5779. auto res = cli_.Post("/path-headers-only",
  5780. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5782. ASSERT_EQ(StatusCode::OK_200, res->status);
  5783. ASSERT_EQ("path-headers-only", res->body);
  5784. }
  5785. TEST_F(ServerTest, PostLarge) {
  5786. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5788. ASSERT_EQ(StatusCode::OK_200, res->status);
  5789. EXPECT_EQ(LARGE_DATA, res->body);
  5790. }
  5791. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5792. auto res = cli_.Put("/empty-no-content-type");
  5793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5794. ASSERT_EQ(StatusCode::OK_200, res->status);
  5795. ASSERT_EQ("empty-no-content-type", res->body);
  5796. }
  5797. TEST_F(ServerTest, GetMethodDir) {
  5798. auto res = cli_.Get("/dir/");
  5799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5800. EXPECT_EQ(StatusCode::OK_200, res->status);
  5801. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5802. auto body = R"(<html>
  5803. <head>
  5804. </head>
  5805. <body>
  5806. <a href="/dir/test.html">Test</a>
  5807. <a href="/hi">hi</a>
  5808. </body>
  5809. </html>
  5810. )";
  5811. EXPECT_EQ(body, res->body);
  5812. }
  5813. TEST_F(ServerTest, GetMethodDirTest) {
  5814. auto res = cli_.Get("/dir/test.html");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::OK_200, res->status);
  5817. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5818. EXPECT_EQ("test.html", res->body);
  5819. }
  5820. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5821. auto res = cli_.Get("/dir/../dir/test.html");
  5822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5823. EXPECT_EQ(StatusCode::OK_200, res->status);
  5824. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5825. EXPECT_EQ("test.html", res->body);
  5826. }
  5827. TEST_F(ServerTest, GetMethodInvalidPath) {
  5828. auto res = cli_.Get("/dir/../test.html");
  5829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5830. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5831. }
  5832. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5833. auto res = cli_.Get("/../www/dir/test.html");
  5834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5835. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5836. }
  5837. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5838. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5840. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5841. }
  5842. TEST_F(ServerTest, GetMethodDirMountTest) {
  5843. auto res = cli_.Get("/mount/dir/test.html");
  5844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5845. EXPECT_EQ(StatusCode::OK_200, res->status);
  5846. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5847. EXPECT_EQ("test.html", res->body);
  5848. }
  5849. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5850. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5852. EXPECT_EQ(StatusCode::OK_200, res->status);
  5853. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5854. EXPECT_EQ("test.html", res->body);
  5855. }
  5856. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5857. auto res = cli_.Get("/mount/dir/../test.html");
  5858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5860. }
  5861. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5862. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5865. }
  5866. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5867. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5869. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5870. }
  5871. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5872. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5875. }
  5876. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5877. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5880. }
  5881. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5882. auto res = cli_.Get("/mount/dir");
  5883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5884. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5885. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5886. }
  5887. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5888. auto res = cli_.Get("//dir");
  5889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5890. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5891. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5892. }
  5893. TEST_F(ServerTest, PostMethod303) {
  5894. auto res = cli_.Post("/1", "body", "text/plain");
  5895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5896. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5897. EXPECT_EQ("/2", res->get_header_value("Location"));
  5898. }
  5899. TEST_F(ServerTest, PostMethod303Redirect) {
  5900. cli_.set_follow_location(true);
  5901. auto res = cli_.Post("/1", "body", "text/plain");
  5902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5903. EXPECT_EQ(StatusCode::OK_200, res->status);
  5904. EXPECT_EQ("redirected.", res->body);
  5905. EXPECT_EQ("/2", res->location);
  5906. }
  5907. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5908. auto res = cli_.Get("/dir/test.abcde");
  5909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5910. EXPECT_EQ(StatusCode::OK_200, res->status);
  5911. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5912. EXPECT_EQ("abcde", res->body);
  5913. }
  5914. TEST_F(ServerTest, StaticFileRange) {
  5915. auto res =
  5916. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5919. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5920. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5921. EXPECT_EQ(true, res->has_header("Content-Range"));
  5922. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5923. EXPECT_EQ(std::string("cd"), res->body);
  5924. }
  5925. TEST_F(ServerTest, StaticFileRanges) {
  5926. auto res = cli_.Get("/dir/test.abcde",
  5927. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5929. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5930. EXPECT_TRUE(
  5931. res->get_header_value("Content-Type")
  5932. .find(
  5933. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5934. 0);
  5935. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5936. }
  5937. TEST_F(ServerTest, StaticFileRangeHead) {
  5938. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5940. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5941. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5942. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5943. EXPECT_EQ(true, res->has_header("Content-Range"));
  5944. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5945. }
  5946. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5947. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5949. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5950. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5951. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5952. EXPECT_EQ(true, res->has_header("Content-Range"));
  5953. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5954. res->get_header_value("Content-Range"));
  5955. EXPECT_EQ("LAST\n", res->body);
  5956. }
  5957. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5958. auto res =
  5959. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5961. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5962. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5963. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5964. EXPECT_EQ(true, res->has_header("Content-Range"));
  5965. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5966. }
  5967. TEST_F(ServerTest, StaticFileBigFile) {
  5968. auto res = cli_.Get("/dir/1MB.txt");
  5969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5970. EXPECT_EQ(StatusCode::OK_200, res->status);
  5971. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5972. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5973. }
  5974. TEST_F(ServerTest, InvalidBaseDirMount) {
  5975. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5976. }
  5977. TEST_F(ServerTest, Binary) {
  5978. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5979. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5980. "application/octet-stream");
  5981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5982. ASSERT_EQ(StatusCode::OK_200, res->status);
  5983. ASSERT_EQ(4U, res->body.size());
  5984. res = cli_.Put("/binary", binary.data(), binary.size(),
  5985. "application/octet-stream");
  5986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5987. ASSERT_EQ(StatusCode::OK_200, res->status);
  5988. ASSERT_EQ(4U, res->body.size());
  5989. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5990. "application/octet-stream");
  5991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5992. ASSERT_EQ(StatusCode::OK_200, res->status);
  5993. ASSERT_EQ(4U, res->body.size());
  5994. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5995. "application/octet-stream");
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. ASSERT_EQ(StatusCode::OK_200, res->status);
  5998. ASSERT_EQ(4U, res->body.size());
  5999. }
  6000. TEST_F(ServerTest, BinaryString) {
  6001. auto binary = std::string("\x00\x01\x02\x03", 4);
  6002. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6004. ASSERT_EQ(StatusCode::OK_200, res->status);
  6005. ASSERT_EQ(4U, res->body.size());
  6006. res = cli_.Put("/binary", binary, "application/octet-stream");
  6007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6008. ASSERT_EQ(StatusCode::OK_200, res->status);
  6009. ASSERT_EQ(4U, res->body.size());
  6010. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6012. ASSERT_EQ(StatusCode::OK_200, res->status);
  6013. ASSERT_EQ(4U, res->body.size());
  6014. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6016. ASSERT_EQ(StatusCode::OK_200, res->status);
  6017. ASSERT_EQ(4U, res->body.size());
  6018. }
  6019. TEST_F(ServerTest, EmptyRequest) {
  6020. auto res = cli_.Get("");
  6021. ASSERT_TRUE(!res);
  6022. EXPECT_EQ(Error::Connection, res.error());
  6023. }
  6024. TEST_F(ServerTest, LongRequest) {
  6025. std::string request;
  6026. for (size_t i = 0; i < 545; i++) {
  6027. request += "/TooLongRequest";
  6028. }
  6029. request += "OK";
  6030. auto res = cli_.Get(request.c_str());
  6031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6032. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6033. }
  6034. TEST_F(ServerTest, TooLongRequest) {
  6035. std::string request;
  6036. for (size_t i = 0; i < 546; i++) {
  6037. request += "/TooLongRequest";
  6038. }
  6039. request += "_NG";
  6040. auto start = std::chrono::high_resolution_clock::now();
  6041. cli_.set_keep_alive(true);
  6042. auto res = cli_.Get(request.c_str());
  6043. auto end = std::chrono::high_resolution_clock::now();
  6044. auto elapsed =
  6045. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6046. .count();
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6049. EXPECT_LE(elapsed, 1000);
  6050. EXPECT_EQ("close", res->get_header_value("Connection"));
  6051. EXPECT_FALSE(cli_.is_socket_open());
  6052. }
  6053. TEST_F(ServerTest, AlmostTooLongRequest) {
  6054. // test for #2046 - URI length check shouldn't include other content on req
  6055. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6056. // leading /, space, HTTP/1.1)
  6057. std::string request =
  6058. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6059. auto res = cli_.Get(request.c_str());
  6060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6061. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6062. }
  6063. TEST_F(ServerTest, LongHeader) {
  6064. Request req;
  6065. req.method = "GET";
  6066. req.path = "/hi";
  6067. std::string host_and_port;
  6068. host_and_port += HOST;
  6069. host_and_port += ":";
  6070. host_and_port += std::to_string(PORT);
  6071. req.headers.emplace("Host", host_and_port.c_str());
  6072. req.headers.emplace("Accept", "*/*");
  6073. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6074. req.headers.emplace(
  6075. "Header-Name",
  6076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6082. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6083. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6084. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6085. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6104. "@@@@@@@@@@@@@@@@");
  6105. auto res = std::make_shared<Response>();
  6106. auto error = Error::Success;
  6107. auto ret = cli_.send(req, *res, error);
  6108. ASSERT_TRUE(ret);
  6109. EXPECT_EQ(StatusCode::OK_200, res->status);
  6110. }
  6111. TEST_F(ServerTest, LongQueryValue) {
  6112. auto start = std::chrono::high_resolution_clock::now();
  6113. cli_.set_keep_alive(true);
  6114. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6115. auto end = std::chrono::high_resolution_clock::now();
  6116. auto elapsed =
  6117. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6118. .count();
  6119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6120. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6121. EXPECT_LE(elapsed, 1000);
  6122. EXPECT_EQ("close", res->get_header_value("Connection"));
  6123. EXPECT_FALSE(cli_.is_socket_open());
  6124. }
  6125. TEST_F(ServerTest, TooLongQueryValue) {
  6126. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6127. ASSERT_FALSE(res);
  6128. EXPECT_EQ(Error::Read, res.error());
  6129. }
  6130. TEST_F(ServerTest, TooLongHeader) {
  6131. Request req;
  6132. req.method = "GET";
  6133. req.path = "/hi";
  6134. std::string host_and_port;
  6135. host_and_port += HOST;
  6136. host_and_port += ":";
  6137. host_and_port += std::to_string(PORT);
  6138. req.headers.emplace("Host", host_and_port.c_str());
  6139. req.headers.emplace("Accept", "*/*");
  6140. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6141. req.headers.emplace(
  6142. "Header-Name",
  6143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6171. "@@@@@@@@@@@@@@@@@");
  6172. auto res = std::make_shared<Response>();
  6173. auto error = Error::Success;
  6174. auto ret = cli_.send(req, *res, error);
  6175. ASSERT_TRUE(ret);
  6176. EXPECT_EQ(StatusCode::OK_200, res->status);
  6177. }
  6178. TEST_F(ServerTest, HeaderCountAtLimit) {
  6179. // Test with headers just under the 100 limit
  6180. httplib::Headers headers;
  6181. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6182. // This should keep us just under the 100 header limit
  6183. for (int i = 0; i < 95; i++) {
  6184. std::string name = "X-Test-Header-" + std::to_string(i);
  6185. std::string value = "value" + std::to_string(i);
  6186. headers.emplace(name, value);
  6187. }
  6188. // This should work fine as we're under the limit
  6189. auto res = cli_.Get("/hi", headers);
  6190. EXPECT_TRUE(res);
  6191. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6192. }
  6193. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6194. // Test with many headers to exceed the 100 limit
  6195. httplib::Headers headers;
  6196. // Add 150 headers to definitely exceed the 100 limit
  6197. for (int i = 0; i < 150; i++) {
  6198. std::string name = "X-Test-Header-" + std::to_string(i);
  6199. std::string value = "value" + std::to_string(i);
  6200. headers.emplace(name, value);
  6201. }
  6202. // This should fail due to exceeding header count limit
  6203. cli_.set_keep_alive(true);
  6204. auto res = cli_.Get("/hi", headers);
  6205. // The server should respond with 400 Bad Request
  6206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6207. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6208. EXPECT_EQ("close", res->get_header_value("Connection"));
  6209. EXPECT_FALSE(cli_.is_socket_open());
  6210. }
  6211. TEST_F(ServerTest, PercentEncoding) {
  6212. auto res = cli_.Get("/e%6edwith%");
  6213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. }
  6216. TEST_F(ServerTest, PercentEncodingUnicode) {
  6217. auto res = cli_.Get("/e%u006edwith%");
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. EXPECT_EQ(StatusCode::OK_200, res->status);
  6220. }
  6221. TEST_F(ServerTest, InvalidPercentEncoding) {
  6222. auto res = cli_.Get("/%endwith%");
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6225. }
  6226. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6227. auto res = cli_.Get("/%uendwith%");
  6228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6229. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6230. }
  6231. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6232. auto res = cli_.Get("/hello?aaa=bbb%");
  6233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6234. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6235. }
  6236. TEST_F(ServerTest, PlusSignEncoding) {
  6237. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6239. EXPECT_EQ(StatusCode::OK_200, res->status);
  6240. EXPECT_EQ("a +b", res->body);
  6241. }
  6242. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6243. // This test simulates a potential DoS attack using many headers
  6244. // to verify our security fix prevents memory exhaustion
  6245. httplib::Headers attack_headers;
  6246. // Attempt to add many headers like an attacker would (200 headers to far
  6247. // exceed limit)
  6248. for (int i = 0; i < 200; i++) {
  6249. std::string name = "X-Attack-Header-" + std::to_string(i);
  6250. std::string value = "attack_payload_" + std::to_string(i);
  6251. attack_headers.emplace(name, value);
  6252. }
  6253. // Try to POST with excessive headers
  6254. cli_.set_keep_alive(true);
  6255. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6256. // Should either fail or return 400 Bad Request due to security limit
  6257. if (res) {
  6258. // If we get a response, it should be 400 Bad Request
  6259. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6260. EXPECT_EQ("close", res->get_header_value("Connection"));
  6261. }
  6262. EXPECT_FALSE(cli_.is_socket_open());
  6263. }
  6264. TEST_F(ServerTest, MultipartFormData) {
  6265. UploadFormDataItems items = {
  6266. {"text1", "text default", "", ""},
  6267. {"text2", "aωb", "", ""},
  6268. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6269. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6270. {"file3", "", "", "application/octet-stream"},
  6271. {"file4", "", "", " application/json tmp-string "}};
  6272. auto res = cli_.Post("/multipart", items);
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. }
  6276. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6277. UploadFormDataItems items = {
  6278. {"text", "default text", "", ""},
  6279. {"multi_text1", "aaaaa", "", ""},
  6280. {"multi_text1", "bbbbb", "", ""},
  6281. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6282. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6283. "application/json"},
  6284. };
  6285. auto res = cli_.Post("/multipart/multi_file_values", items);
  6286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6287. EXPECT_EQ(StatusCode::OK_200, res->status);
  6288. }
  6289. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6290. auto res = cli_.Get("/hi");
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. EXPECT_EQ(StatusCode::OK_200, res->status);
  6293. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6294. EXPECT_EQ("Hello World!", res->body);
  6295. }
  6296. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6297. Request req;
  6298. req.method = "POST";
  6299. req.path = "/chunked";
  6300. std::string host_and_port;
  6301. host_and_port += HOST;
  6302. host_and_port += ":";
  6303. host_and_port += std::to_string(PORT);
  6304. req.headers.emplace("Host", host_and_port.c_str());
  6305. req.headers.emplace("Accept", "*/*");
  6306. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6307. req.headers.emplace("Content-Type", "text/plain");
  6308. req.headers.emplace("Content-Length", "0");
  6309. req.headers.emplace(
  6310. "Transfer-Encoding",
  6311. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6312. // Client does not chunk, so make a chunked body manually.
  6313. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6314. auto res = std::make_shared<Response>();
  6315. auto error = Error::Success;
  6316. auto ret = cli_.send(req, *res, error);
  6317. ASSERT_TRUE(ret);
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. }
  6320. template <typename ClientT>
  6321. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6322. int expected_status) {
  6323. Request req;
  6324. req.method = "POST";
  6325. req.path = "/chunked";
  6326. std::string host_and_port;
  6327. host_and_port += HOST;
  6328. host_and_port += ":";
  6329. host_and_port += std::to_string(PORT);
  6330. req.headers.emplace("Host", host_and_port.c_str());
  6331. req.headers.emplace("Content-Length", "0");
  6332. req.headers.emplace("Transfer-Encoding", "chunked");
  6333. req.body = body;
  6334. auto res = std::make_shared<Response>();
  6335. auto error = Error::Success;
  6336. ASSERT_TRUE(cli.send(req, *res, error));
  6337. EXPECT_EQ(expected_status, res->status);
  6338. }
  6339. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6340. // rather than treat them as valid lengths.
  6341. template <typename ClientT>
  6342. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6343. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6344. }
  6345. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6346. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6347. }
  6348. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6349. expect_chunked_body_rejected(
  6350. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6351. }
  6352. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6353. // chunk-size line carries no CR, LF or other control character ahead of its
  6354. // terminator. Such a line must be refused rather than read as extension text.
  6355. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6356. expect_chunked_body_rejected(
  6357. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6358. }
  6359. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6360. expect_chunked_body_rejected(
  6361. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6362. }
  6363. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6364. expect_chunked_body_rejected(
  6365. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6366. }
  6367. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6368. // The literal stays split: a hex escape consumes every hex digit that
  6369. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6370. expect_chunked_body_rejected(
  6371. cli_, "4;a\x01"
  6372. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6373. }
  6374. TEST_F(ServerTest, AcceptsChunkExtension) {
  6375. expect_chunked_body_status(cli_,
  6376. "4;name=value\r\ndech\r\n"
  6377. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6378. "0;last\r\n\r\n",
  6379. StatusCode::OK_200);
  6380. }
  6381. TEST_F(ServerTest, GetStreamed2) {
  6382. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6384. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6385. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6386. EXPECT_EQ(true, res->has_header("Content-Range"));
  6387. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6388. EXPECT_EQ(std::string("ab"), res->body);
  6389. }
  6390. TEST_F(ServerTest, GetStreamed) {
  6391. auto res = cli_.Get("/streamed");
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::OK_200, res->status);
  6394. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6395. EXPECT_EQ(std::string("aaabbb"), res->body);
  6396. }
  6397. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6398. auto res = cli_.Get("/streamed-without-length",
  6399. Headers{make_range_header({{0, -1}})});
  6400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6401. EXPECT_EQ(StatusCode::OK_200, res->status);
  6402. EXPECT_EQ(false, res->has_header("Content-Length"));
  6403. EXPECT_EQ(false, res->has_header("Content-Range"));
  6404. EXPECT_EQ(std::string("abcdefg"), res->body);
  6405. }
  6406. TEST_F(ServerTest, GetStreamedWithRange1) {
  6407. auto res =
  6408. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6410. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6411. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6412. EXPECT_EQ(true, res->has_header("Content-Range"));
  6413. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6414. EXPECT_EQ(std::string("def"), res->body);
  6415. }
  6416. TEST_F(ServerTest, GetStreamedWithRange2) {
  6417. auto res =
  6418. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6420. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6421. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6422. EXPECT_EQ(true, res->has_header("Content-Range"));
  6423. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6424. EXPECT_EQ(std::string("bcdefg"), res->body);
  6425. }
  6426. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6427. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6430. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6431. EXPECT_EQ(true, res->has_header("Content-Range"));
  6432. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6433. EXPECT_EQ(std::string("efg"), res->body);
  6434. }
  6435. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6436. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6437. // the entire representation.
  6438. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6439. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6442. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6443. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6444. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6445. }
  6446. }
  6447. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6448. auto res =
  6449. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6452. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6453. EXPECT_EQ(false, res->has_header("Content-Range"));
  6454. EXPECT_EQ(0U, res->body.size());
  6455. }
  6456. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6457. // Only a 206 is served as a partial representation. Under any other status
  6458. // `apply_ranges()` reported the full content length, so the body must match
  6459. // that header, and the content provider must never be asked for an offset
  6460. // outside the representation.
  6461. auto check = [&](int status, const char *range) {
  6462. auto path =
  6463. std::string("/streamed-with-range?status=") + std::to_string(status);
  6464. auto ctx = path + " Range: " + range;
  6465. auto res = cli_.Get(path, Headers{{"Range", range}});
  6466. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6467. EXPECT_EQ(status, res->status) << ctx;
  6468. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6469. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6470. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6471. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6472. };
  6473. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6474. check(403, "bytes=3-5");
  6475. // The offset is far past the representation.
  6476. check(403, "bytes=100000-100200");
  6477. // `first_pos` is still -1 here, and the bounds asserts in
  6478. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6479. check(403, "bytes=-3");
  6480. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6481. // multipart branch would have written one that is empty.
  6482. check(403, "bytes=1-2, 4-5");
  6483. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6484. // covers the whole representation.
  6485. check(200, "bytes=3-5");
  6486. check(200, "bytes=1-2, 4-5");
  6487. }
  6488. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6489. auto res =
  6490. cli_.Get("/streamed-with-range",
  6491. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6492. "92233720368547758079223372036854775807"}});
  6493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6494. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6495. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6496. EXPECT_EQ(false, res->has_header("Content-Range"));
  6497. EXPECT_EQ(0U, res->body.size());
  6498. }
  6499. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6500. auto res = cli_.Get(
  6501. "/with-range",
  6502. Headers{{"Range",
  6503. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6504. {"Accept-Encoding", ""}});
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6507. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6508. EXPECT_EQ(true, res->has_header("Content-Range"));
  6509. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6510. EXPECT_EQ(std::string("abcdefg"), res->body);
  6511. }
  6512. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6513. auto res = cli_.Get("/with-range", Headers{
  6514. {"Range", "bytes=0-"},
  6515. {"Accept-Encoding", ""},
  6516. });
  6517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6518. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6519. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6520. EXPECT_EQ(true, res->has_header("Content-Range"));
  6521. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6522. EXPECT_EQ(std::string("abcdefg"), res->body);
  6523. }
  6524. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6525. auto res = cli_.Get("/streamed-with-range",
  6526. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6528. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6529. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6530. EXPECT_EQ(false, res->has_header("Content-Range"));
  6531. EXPECT_EQ(267U, res->body.size());
  6532. // Check that both range contents are present
  6533. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6534. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6535. // Check that Content-Range headers are present for both ranges
  6536. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6537. std::string::npos);
  6538. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6539. std::string::npos);
  6540. }
  6541. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6542. Ranges ranges;
  6543. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6544. ranges.emplace_back(0, -1);
  6545. }
  6546. auto res = cli_.Get("/streamed-with-range?error",
  6547. Headers{{make_range_header(ranges)}});
  6548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6549. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6550. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6551. EXPECT_EQ(false, res->has_header("Content-Range"));
  6552. EXPECT_EQ(0U, res->body.size());
  6553. }
  6554. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6555. auto res = cli_.Get("/streamed-with-range",
  6556. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6558. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6559. EXPECT_EQ(5U, res->body.size());
  6560. // Check that overlapping ranges are coalesced into a single range
  6561. EXPECT_EQ("bcdef", res->body);
  6562. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6563. // Should be single range, not multipart
  6564. EXPECT_TRUE(res->has_header("Content-Range"));
  6565. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6566. }
  6567. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6568. auto res = cli_.Get("/streamed-with-range",
  6569. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6571. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6572. EXPECT_EQ(268U, res->body.size());
  6573. // Check that both range contents are present
  6574. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6575. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6576. // Check that Content-Range headers are present for both ranges
  6577. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6578. std::string::npos);
  6579. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6580. std::string::npos);
  6581. }
  6582. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6583. auto res = cli_.Get("/streamed-with-range",
  6584. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6586. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6587. EXPECT_EQ(269U, res->body.size());
  6588. // Check that both duplicate range contents are present
  6589. size_t first_abc = res->body.find("abc\r\n");
  6590. EXPECT_TRUE(first_abc != std::string::npos);
  6591. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6592. EXPECT_TRUE(second_abc != std::string::npos);
  6593. // Check that Content-Range headers are present for both ranges
  6594. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6595. EXPECT_TRUE(first_range != std::string::npos);
  6596. size_t second_range =
  6597. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6598. EXPECT_TRUE(second_range != std::string::npos);
  6599. }
  6600. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6601. auto res =
  6602. cli_.Get("/streamed-with-range?error",
  6603. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6605. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6606. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6607. EXPECT_EQ(false, res->has_header("Content-Range"));
  6608. EXPECT_EQ(0U, res->body.size());
  6609. }
  6610. TEST_F(ServerTest, GetStreamedEndless) {
  6611. uint64_t offset = 0;
  6612. auto res = cli_.Get("/streamed-cancel",
  6613. [&](const char * /*data*/, uint64_t data_length) {
  6614. if (offset < 100) {
  6615. offset += data_length;
  6616. return true;
  6617. }
  6618. return false;
  6619. });
  6620. ASSERT_TRUE(!res);
  6621. EXPECT_EQ(Error::Canceled, res.error());
  6622. }
  6623. TEST_F(ServerTest, ClientStop) {
  6624. std::atomic_size_t count{4};
  6625. std::vector<std::thread> threads;
  6626. for (auto i = count.load(); i != 0; --i) {
  6627. threads.emplace_back([&]() {
  6628. auto res = cli_.Get("/streamed-cancel",
  6629. [&](const char *, uint64_t) { return true; });
  6630. --count;
  6631. ASSERT_TRUE(!res);
  6632. EXPECT_TRUE(res.error() == Error::Canceled ||
  6633. res.error() == Error::Read || res.error() == Error::Write);
  6634. });
  6635. }
  6636. std::this_thread::sleep_for(std::chrono::seconds(2));
  6637. while (count != 0) {
  6638. cli_.stop();
  6639. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6640. }
  6641. for (auto &t : threads) {
  6642. t.join();
  6643. }
  6644. }
  6645. TEST_F(ServerTest, GetWithRange1) {
  6646. auto res = cli_.Get("/with-range", Headers{
  6647. make_range_header({{3, 5}}),
  6648. {"Accept-Encoding", ""},
  6649. });
  6650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6651. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6652. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6653. EXPECT_EQ(true, res->has_header("Content-Range"));
  6654. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6655. EXPECT_EQ(std::string("def"), res->body);
  6656. }
  6657. TEST_F(ServerTest, GetWithRange2) {
  6658. auto res = cli_.Get("/with-range", Headers{
  6659. make_range_header({{1, -1}}),
  6660. {"Accept-Encoding", ""},
  6661. });
  6662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6663. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6664. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6665. EXPECT_EQ(true, res->has_header("Content-Range"));
  6666. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6667. EXPECT_EQ(std::string("bcdefg"), res->body);
  6668. }
  6669. TEST_F(ServerTest, GetWithRange3) {
  6670. auto res = cli_.Get("/with-range", Headers{
  6671. make_range_header({{0, 0}}),
  6672. {"Accept-Encoding", ""},
  6673. });
  6674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6675. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6676. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6677. EXPECT_EQ(true, res->has_header("Content-Range"));
  6678. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6679. EXPECT_EQ(std::string("a"), res->body);
  6680. }
  6681. TEST_F(ServerTest, GetWithRange4) {
  6682. auto res = cli_.Get("/with-range", Headers{
  6683. make_range_header({{-1, 2}}),
  6684. {"Accept-Encoding", ""},
  6685. });
  6686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6687. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6688. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6689. EXPECT_EQ(true, res->has_header("Content-Range"));
  6690. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6691. EXPECT_EQ(std::string("fg"), res->body);
  6692. }
  6693. TEST_F(ServerTest, GetWithRange5) {
  6694. auto res = cli_.Get("/with-range", Headers{
  6695. make_range_header({{0, 5}}),
  6696. {"Accept-Encoding", ""},
  6697. });
  6698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6699. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6700. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6701. EXPECT_EQ(true, res->has_header("Content-Range"));
  6702. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6703. EXPECT_EQ(std::string("abcdef"), res->body);
  6704. }
  6705. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6706. auto res =
  6707. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6710. }
  6711. TEST_F(ServerTest, GetWithRangeMultipart) {
  6712. auto res =
  6713. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6715. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6716. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6717. EXPECT_EQ(false, res->has_header("Content-Range"));
  6718. EXPECT_EQ(267U, res->body.size());
  6719. }
  6720. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6721. auto res = cli_.Get("/with-range",
  6722. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6725. }
  6726. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6727. auto res = cli_.Get("/with-range-customized-response",
  6728. Headers{{make_range_header({{1, 2}})}});
  6729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6730. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6731. EXPECT_EQ(true, res->has_header("Content-Length"));
  6732. EXPECT_EQ(false, res->has_header("Content-Range"));
  6733. EXPECT_EQ(JSON_DATA, res->body);
  6734. }
  6735. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6736. auto res = cli_.Get("/with-range-customized-response",
  6737. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6739. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6740. EXPECT_EQ(true, res->has_header("Content-Length"));
  6741. EXPECT_EQ(false, res->has_header("Content-Range"));
  6742. EXPECT_EQ(JSON_DATA, res->body);
  6743. }
  6744. TEST_F(ServerTest, Issue1772) {
  6745. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6747. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6748. }
  6749. TEST_F(ServerTest, Issue609) {
  6750. auto res = cli_.Delete("/issue609");
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. EXPECT_EQ(StatusCode::OK_200, res->status);
  6753. EXPECT_EQ(std::string("ok"), res->body);
  6754. }
  6755. TEST_F(ServerTest, GetStreamedChunked) {
  6756. auto res = cli_.Get("/streamed-chunked");
  6757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6758. EXPECT_EQ(StatusCode::OK_200, res->status);
  6759. EXPECT_EQ(std::string("123456789"), res->body);
  6760. }
  6761. TEST_F(ServerTest, GetStreamedChunked2) {
  6762. auto res = cli_.Get("/streamed-chunked2");
  6763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6764. EXPECT_EQ(StatusCode::OK_200, res->status);
  6765. EXPECT_EQ(std::string("123456789"), res->body);
  6766. }
  6767. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6768. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6770. EXPECT_EQ(StatusCode::OK_200, res->status);
  6771. EXPECT_EQ(std::string("123456789"), res->body);
  6772. EXPECT_TRUE(res->has_header("Trailer"));
  6773. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6774. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6775. // Trailers are now stored separately from headers (security fix)
  6776. EXPECT_EQ(2U, res->trailers.size());
  6777. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6778. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6779. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6780. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6781. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6782. // Verify trailers are NOT in headers (security verification)
  6783. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6784. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6785. }
  6786. TEST_F(ServerTest, LargeChunkedPost) {
  6787. Request req;
  6788. req.method = "POST";
  6789. req.path = "/large-chunked";
  6790. std::string host_and_port;
  6791. host_and_port += HOST;
  6792. host_and_port += ":";
  6793. host_and_port += std::to_string(PORT);
  6794. req.headers.emplace("Host", host_and_port.c_str());
  6795. req.headers.emplace("Accept", "*/*");
  6796. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6797. req.headers.emplace("Content-Type", "text/plain");
  6798. req.headers.emplace("Content-Length", "0");
  6799. req.headers.emplace("Transfer-Encoding", "chunked");
  6800. std::string long_string(30 * 1024u, 'a');
  6801. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6802. // Attempt to make a large enough post to exceed OS buffers, to test that
  6803. // the server handles short reads if the full chunk data isn't available.
  6804. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6805. auto res = std::make_shared<Response>();
  6806. auto error = Error::Success;
  6807. auto ret = cli_.send(req, *res, error);
  6808. ASSERT_TRUE(ret);
  6809. EXPECT_EQ(StatusCode::OK_200, res->status);
  6810. }
  6811. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6812. auto res = cli_.Get("/remote_addr");
  6813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6816. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6817. }
  6818. TEST_F(ServerTest, GetMethodLocalAddr) {
  6819. auto res = cli_.Get("/local_addr");
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6823. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6824. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6825. }
  6826. TEST_F(ServerTest, HTTPResponseSplitting) {
  6827. auto res = cli_.Get("/http_response_splitting");
  6828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6829. EXPECT_EQ(StatusCode::OK_200, res->status);
  6830. }
  6831. TEST_F(ServerTest, SlowRequest) {
  6832. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6833. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6834. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6835. }
  6836. #if 0
  6837. TEST_F(ServerTest, SlowPost) {
  6838. char buffer[64 * 1024];
  6839. memset(buffer, 0x42, sizeof(buffer));
  6840. auto res = cli_.Post(
  6841. "/slowpost", 64 * 1024 * 1024,
  6842. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6843. auto ret = sink.write(buffer, sizeof(buffer));
  6844. EXPECT_TRUE(ret);
  6845. return true;
  6846. },
  6847. "text/plain");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::OK_200, res->status);
  6850. }
  6851. TEST_F(ServerTest, SlowPostFail) {
  6852. char buffer[64 * 1024];
  6853. memset(buffer, 0x42, sizeof(buffer));
  6854. cli_.set_write_timeout(std::chrono::seconds(0));
  6855. auto res = cli_.Post(
  6856. "/slowpost", 64 * 1024 * 1024,
  6857. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6858. sink.write(buffer, sizeof(buffer));
  6859. return true;
  6860. },
  6861. "text/plain");
  6862. ASSERT_TRUE(!res);
  6863. EXPECT_EQ(Error::Write, res.error());
  6864. }
  6865. #endif
  6866. TEST_F(ServerTest, Put) {
  6867. auto res = cli_.Put("/put", "PUT", "text/plain");
  6868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. EXPECT_EQ("PUT", res->body);
  6871. }
  6872. TEST_F(ServerTest, PutWithContentProvider) {
  6873. auto res = cli_.Put(
  6874. "/put", 3,
  6875. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6876. sink.os << "PUT";
  6877. return true;
  6878. },
  6879. "text/plain");
  6880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6881. EXPECT_EQ(StatusCode::OK_200, res->status);
  6882. EXPECT_EQ("PUT", res->body);
  6883. }
  6884. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6885. auto res = cli_.Post(
  6886. "/post", 42,
  6887. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6888. return false;
  6889. },
  6890. "text/plain");
  6891. ASSERT_TRUE(!res);
  6892. EXPECT_EQ(Error::Canceled, res.error());
  6893. }
  6894. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6895. auto res = cli_.Put(
  6896. "/put",
  6897. [](size_t /*offset*/, DataSink &sink) {
  6898. sink.os << "PUT";
  6899. sink.done();
  6900. return true;
  6901. },
  6902. "text/plain");
  6903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6904. EXPECT_EQ(StatusCode::OK_200, res->status);
  6905. EXPECT_EQ("PUT", res->body);
  6906. }
  6907. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6908. auto res = cli_.Post(
  6909. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6910. "text/plain");
  6911. ASSERT_TRUE(!res);
  6912. EXPECT_EQ(Error::Canceled, res.error());
  6913. }
  6914. TEST_F(ServerTest, PostLoopBack) {
  6915. std::string body;
  6916. auto res = cli_.Post(
  6917. "/post-loopback", 9,
  6918. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6919. EXPECT_EQ(9u, length);
  6920. sink.write("123", 3);
  6921. sink.write("456", 3);
  6922. sink.write("789", 3);
  6923. return true;
  6924. },
  6925. "text/plain",
  6926. [&body](const char *data, size_t data_length) {
  6927. body.append(data, data_length);
  6928. return true;
  6929. });
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::OK_200, res->status);
  6932. EXPECT_EQ("123456789", body);
  6933. }
  6934. TEST_F(ServerTest, PutLoopBack) {
  6935. std::string body;
  6936. auto res = cli_.Put(
  6937. "/put-loopback", 9,
  6938. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6939. EXPECT_EQ(9u, length);
  6940. sink.write("123", 3);
  6941. sink.write("456", 3);
  6942. sink.write("789", 3);
  6943. return true;
  6944. },
  6945. "text/plain",
  6946. [&body](const char *data, size_t data_length) {
  6947. body.append(data, data_length);
  6948. return true;
  6949. });
  6950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6951. EXPECT_EQ(StatusCode::OK_200, res->status);
  6952. EXPECT_EQ("123456789", body);
  6953. }
  6954. TEST_F(ServerTest, PatchLoopBack) {
  6955. std::string body;
  6956. auto res = cli_.Patch(
  6957. "/patch-loopback", 9,
  6958. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6959. EXPECT_EQ(9u, length);
  6960. sink.write("123", 3);
  6961. sink.write("456", 3);
  6962. sink.write("789", 3);
  6963. return true;
  6964. },
  6965. "text/plain",
  6966. [&body](const char *data, size_t data_length) {
  6967. body.append(data, data_length);
  6968. return true;
  6969. });
  6970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6971. EXPECT_EQ(StatusCode::OK_200, res->status);
  6972. EXPECT_EQ("123456789", body);
  6973. }
  6974. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6975. std::string body;
  6976. auto res = cli_.Post(
  6977. "/post-loopback",
  6978. [](size_t /*offset*/, DataSink &sink) {
  6979. sink.write("123", 3);
  6980. sink.write("456", 3);
  6981. sink.write("789", 3);
  6982. sink.done();
  6983. return true;
  6984. },
  6985. "text/plain",
  6986. [&body](const char *data, size_t data_length) {
  6987. body.append(data, data_length);
  6988. return true;
  6989. });
  6990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6991. EXPECT_EQ(StatusCode::OK_200, res->status);
  6992. EXPECT_EQ("123456789", body);
  6993. }
  6994. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6995. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6996. cli_.set_compress(true);
  6997. auto res = cli_.Put(
  6998. "/put", 3,
  6999. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7000. sink.os << "PUT";
  7001. return true;
  7002. },
  7003. "text/plain");
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. EXPECT_EQ("PUT", res->body);
  7007. }
  7008. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7009. cli_.set_compress(true);
  7010. auto res = cli_.Post(
  7011. "/post", 42,
  7012. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7013. return false;
  7014. },
  7015. "text/plain");
  7016. ASSERT_TRUE(!res);
  7017. EXPECT_EQ(Error::Canceled, res.error());
  7018. }
  7019. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7020. cli_.set_compress(true);
  7021. auto res = cli_.Put(
  7022. "/put",
  7023. [](size_t /*offset*/, DataSink &sink) {
  7024. sink.os << "PUT";
  7025. sink.done();
  7026. return true;
  7027. },
  7028. "text/plain");
  7029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7030. EXPECT_EQ(StatusCode::OK_200, res->status);
  7031. EXPECT_EQ("PUT", res->body);
  7032. }
  7033. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7034. cli_.set_compress(true);
  7035. auto res = cli_.Post(
  7036. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7037. "text/plain");
  7038. ASSERT_TRUE(!res);
  7039. EXPECT_EQ(Error::Canceled, res.error());
  7040. }
  7041. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7042. cli_.set_compress(true);
  7043. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::OK_200, res->status);
  7046. EXPECT_EQ(LARGE_DATA, res->body);
  7047. }
  7048. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7049. #ifdef CPPHTTPLIB_SSL_ENABLED
  7050. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7051. Client cli(s.c_str());
  7052. cli.enable_server_certificate_verification(false);
  7053. #else
  7054. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7055. Client cli(s.c_str());
  7056. #endif
  7057. cli.set_compress(true);
  7058. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::OK_200, res->status);
  7061. EXPECT_EQ(LARGE_DATA, res->body);
  7062. // The compressed size should be less than a 10th of the original. May vary
  7063. // depending on the zlib library.
  7064. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7065. static_cast<uint64_t>(10 * 1024 * 1024));
  7066. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7067. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7068. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7069. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7070. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7071. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7072. #endif
  7073. }
  7074. TEST_F(ServerTest, PutContentWithDeflate) {
  7075. cli_.set_compress(false);
  7076. Headers headers;
  7077. headers.emplace("Content-Encoding", "deflate");
  7078. // PUT in deflate format:
  7079. auto res = cli_.Put("/put", headers,
  7080. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. EXPECT_EQ(StatusCode::OK_200, res->status);
  7083. EXPECT_EQ("PUT", res->body);
  7084. }
  7085. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7086. Headers headers;
  7087. headers.emplace("Accept-Encoding", "gzip, deflate");
  7088. auto res = cli_.Get("/streamed-chunked", headers);
  7089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7090. EXPECT_EQ(StatusCode::OK_200, res->status);
  7091. EXPECT_EQ(std::string("123456789"), res->body);
  7092. }
  7093. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7094. Headers headers;
  7095. headers.emplace("Accept-Encoding", "gzip, deflate");
  7096. auto res = cli_.Get("/streamed-chunked2", headers);
  7097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7098. EXPECT_EQ(StatusCode::OK_200, res->status);
  7099. EXPECT_EQ(std::string("123456789"), res->body);
  7100. }
  7101. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7102. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7104. EXPECT_EQ(StatusCode::OK_200, res->status);
  7105. }
  7106. TEST(GzipDecompressor, ChunkedDecompression) {
  7107. std::string data;
  7108. for (size_t i = 0; i < 32 * 1024; ++i) {
  7109. data.push_back(static_cast<char>('a' + i % 26));
  7110. }
  7111. std::string compressed_data;
  7112. {
  7113. httplib::detail::gzip_compressor compressor;
  7114. bool result = compressor.compress(
  7115. data.data(), data.size(),
  7116. /*last=*/true,
  7117. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7118. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7119. compressed_data_size);
  7120. return true;
  7121. });
  7122. ASSERT_TRUE(result);
  7123. }
  7124. std::string decompressed_data;
  7125. {
  7126. httplib::detail::gzip_decompressor decompressor;
  7127. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7128. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7129. size_t chunk_size = 130;
  7130. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7131. chunk_begin += chunk_size) {
  7132. size_t current_chunk_size =
  7133. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7134. bool result = decompressor.decompress(
  7135. compressed_data.data() + chunk_begin, current_chunk_size,
  7136. [&](const char *decompressed_data_chunk,
  7137. size_t decompressed_data_chunk_size) {
  7138. decompressed_data.insert(decompressed_data.size(),
  7139. decompressed_data_chunk,
  7140. decompressed_data_chunk_size);
  7141. return true;
  7142. });
  7143. ASSERT_TRUE(result);
  7144. }
  7145. }
  7146. ASSERT_EQ(data, decompressed_data);
  7147. }
  7148. TEST(GzipDecompressor, DeflateDecompression) {
  7149. std::string original_text = "Raw deflate without gzip";
  7150. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7151. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7152. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7153. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7154. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7155. std::string decompressed_data;
  7156. {
  7157. httplib::detail::gzip_decompressor decompressor;
  7158. bool result = decompressor.decompress(
  7159. compressed_data.data(), compressed_data.size(),
  7160. [&](const char *decompressed_data_chunk,
  7161. size_t decompressed_data_chunk_size) {
  7162. decompressed_data.insert(decompressed_data.size(),
  7163. decompressed_data_chunk,
  7164. decompressed_data_chunk_size);
  7165. return true;
  7166. });
  7167. ASSERT_TRUE(result);
  7168. }
  7169. ASSERT_EQ(original_text, decompressed_data);
  7170. }
  7171. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7172. std::string original_text = "Raw deflate without gzip";
  7173. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7174. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7175. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7176. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7177. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7178. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7179. std::string decompressed_data;
  7180. {
  7181. httplib::detail::gzip_decompressor decompressor;
  7182. bool result = decompressor.decompress(
  7183. compressed_data.data(), compressed_data.size(),
  7184. [&](const char *decompressed_data_chunk,
  7185. size_t decompressed_data_chunk_size) {
  7186. decompressed_data.insert(decompressed_data.size(),
  7187. decompressed_data_chunk,
  7188. decompressed_data_chunk_size);
  7189. return true;
  7190. });
  7191. ASSERT_TRUE(result);
  7192. }
  7193. ASSERT_EQ(original_text, decompressed_data);
  7194. }
  7195. #endif
  7196. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7197. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7198. Headers headers;
  7199. headers.emplace("Accept-Encoding", "br");
  7200. auto res = cli_.Get("/streamed-chunked", headers);
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::OK_200, res->status);
  7203. EXPECT_EQ(std::string("123456789"), res->body);
  7204. }
  7205. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7206. Headers headers;
  7207. headers.emplace("Accept-Encoding", "br");
  7208. auto res = cli_.Get("/streamed-chunked2", headers);
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. EXPECT_EQ(StatusCode::OK_200, res->status);
  7211. EXPECT_EQ(std::string("123456789"), res->body);
  7212. }
  7213. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7214. cli_.set_compress(true);
  7215. auto res = cli_.Put(
  7216. "/put", 3,
  7217. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7218. sink.os << "PUT";
  7219. return true;
  7220. },
  7221. "text/plain");
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::OK_200, res->status);
  7224. EXPECT_EQ("PUT", res->body);
  7225. }
  7226. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7227. cli_.set_compress(true);
  7228. auto res = cli_.Put(
  7229. "/put",
  7230. [](size_t /*offset*/, DataSink &sink) {
  7231. sink.os << "PUT";
  7232. sink.done();
  7233. return true;
  7234. },
  7235. "text/plain");
  7236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7237. EXPECT_EQ(StatusCode::OK_200, res->status);
  7238. EXPECT_EQ("PUT", res->body);
  7239. }
  7240. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7241. cli_.set_compress(true);
  7242. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ(LARGE_DATA, res->body);
  7246. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7247. }
  7248. #endif
  7249. TEST_F(ServerTest, Patch) {
  7250. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7252. EXPECT_EQ(StatusCode::OK_200, res->status);
  7253. EXPECT_EQ("PATCH", res->body);
  7254. }
  7255. TEST_F(ServerTest, Delete) {
  7256. auto res = cli_.Delete("/delete");
  7257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7258. EXPECT_EQ(StatusCode::OK_200, res->status);
  7259. EXPECT_EQ("DELETE", res->body);
  7260. }
  7261. TEST_F(ServerTest, DeleteContentReceiver) {
  7262. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7264. EXPECT_EQ(StatusCode::OK_200, res->status);
  7265. EXPECT_EQ("content", res->body);
  7266. }
  7267. TEST_F(ServerTest, Options) {
  7268. auto res = cli_.Options("*");
  7269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7270. EXPECT_EQ(StatusCode::OK_200, res->status);
  7271. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7272. EXPECT_TRUE(res->body.empty());
  7273. }
  7274. TEST_F(ServerTest, URL) {
  7275. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7277. EXPECT_EQ(StatusCode::OK_200, res->status);
  7278. }
  7279. TEST_F(ServerTest, ArrayParam) {
  7280. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7282. EXPECT_EQ(StatusCode::OK_200, res->status);
  7283. }
  7284. TEST_F(ServerTest, ArrayParamValues) {
  7285. auto res =
  7286. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7288. EXPECT_EQ(StatusCode::OK_200, res->status);
  7289. }
  7290. TEST_F(ServerTest, NoMultipleHeaders) {
  7291. Headers headers = {{"Content-Length", "5"}};
  7292. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7293. "text/plain");
  7294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7295. EXPECT_EQ(StatusCode::OK_200, res->status);
  7296. }
  7297. TEST_F(ServerTest, PostContentReceiver) {
  7298. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7300. ASSERT_EQ(StatusCode::OK_200, res->status);
  7301. ASSERT_EQ("content", res->body);
  7302. }
  7303. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7304. UploadFormDataItems items = {
  7305. {"text1", "text default", "", ""},
  7306. {"text2", "aωb", "", ""},
  7307. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7308. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7309. {"file3", "", "", "application/octet-stream"},
  7310. };
  7311. auto res = cli_.Post("/content_receiver", items);
  7312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7313. EXPECT_EQ(StatusCode::OK_200, res->status);
  7314. }
  7315. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7316. UploadFormDataItems items = {
  7317. {"text1", "text default", "", ""},
  7318. {"text2", "aωb", "", ""},
  7319. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7320. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7321. {"file3", "", "", "application/octet-stream"},
  7322. };
  7323. auto boundary = std::string("+++++");
  7324. std::string body;
  7325. for (const auto &item : items) {
  7326. body += "--" + boundary + "\r\n";
  7327. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7328. if (!item.filename.empty()) {
  7329. body += "; filename=\"" + item.filename + "\"";
  7330. }
  7331. body += "\r\n";
  7332. if (!item.content_type.empty()) {
  7333. body += "Content-Type: " + item.content_type + "\r\n";
  7334. }
  7335. body += "\r\n";
  7336. body += item.content + "\r\n";
  7337. }
  7338. body += "--" + boundary + "--\r\n";
  7339. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7340. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7342. EXPECT_EQ(StatusCode::OK_200, res->status);
  7343. }
  7344. TEST(MultipartFormDataTest, FieldEscaping) {
  7345. Server svr;
  7346. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7347. const ContentReader &content_reader) {
  7348. ASSERT_TRUE(req.is_multipart_form_data());
  7349. std::vector<FormData> received;
  7350. content_reader(
  7351. [&](const FormData &file) {
  7352. received.push_back(file);
  7353. return true;
  7354. },
  7355. [&](const char *data, size_t data_length) {
  7356. received.back().content.append(data, data_length);
  7357. return true;
  7358. });
  7359. // '"', CR and LF in names and filenames are escaped following the
  7360. // WHATWG HTML standard, so each part still parses as a single part
  7361. // with no injected headers. Content types get CR/LF escaped too,
  7362. // while '"' (legal there, e.g. quoted charset) is preserved.
  7363. ASSERT_EQ(4U, received.size());
  7364. EXPECT_EQ("na%22me", received[0].name);
  7365. EXPECT_EQ("quoted name", received[0].content);
  7366. EXPECT_EQ("file", received[1].name);
  7367. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7368. received[1].filename);
  7369. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7370. EXPECT_EQ("injected", received[1].content);
  7371. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7372. EXPECT_EQ("my%22file.txt", received[2].filename);
  7373. EXPECT_EQ("cr lf name", received[2].content);
  7374. EXPECT_EQ("typed", received[3].name);
  7375. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7376. received[3].content_type);
  7377. EXPECT_EQ("typed content", received[3].content);
  7378. });
  7379. auto port = svr.bind_to_any_port("localhost");
  7380. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7381. auto se = detail::scope_exit([&] {
  7382. svr.stop();
  7383. t.join();
  7384. ASSERT_FALSE(svr.is_running());
  7385. });
  7386. svr.wait_until_ready();
  7387. Client cli("localhost", port);
  7388. UploadFormDataItems items = {
  7389. {"na\"me", "quoted name", "", ""},
  7390. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7391. "application/octet-stream"},
  7392. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7393. {"typed", "typed content", "",
  7394. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7395. };
  7396. auto res = cli.Post("/post", items);
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::OK_200, res->status);
  7399. }
  7400. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7401. const UploadFormDataItems items = {
  7402. {"name1", "Content 1", "", ""},
  7403. {"name2", "Content 2", "file2.txt", "text/plain"},
  7404. };
  7405. Server svr;
  7406. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7407. const ContentReader &content_reader) {
  7408. ASSERT_TRUE(req.is_multipart_form_data());
  7409. std::vector<FormData> received;
  7410. content_reader(
  7411. [&](const FormData &file) {
  7412. received.push_back(file);
  7413. return true;
  7414. },
  7415. [&](const char *data, size_t data_length) {
  7416. received.back().content.append(data, data_length);
  7417. return true;
  7418. });
  7419. ASSERT_EQ(2U, received.size());
  7420. EXPECT_EQ("name1", received[0].name);
  7421. EXPECT_EQ("Content 1", received[0].content);
  7422. EXPECT_EQ("name2", received[1].name);
  7423. EXPECT_EQ("Content 2", received[1].content);
  7424. EXPECT_EQ("file2.txt", received[1].filename);
  7425. EXPECT_EQ("text/plain", received[1].content_type);
  7426. });
  7427. auto port = svr.bind_to_any_port("localhost");
  7428. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7429. auto se = detail::scope_exit([&] {
  7430. svr.stop();
  7431. t.join();
  7432. ASSERT_FALSE(svr.is_running());
  7433. });
  7434. svr.wait_until_ready();
  7435. Client cli("localhost", port);
  7436. // Whole-body serialization with a generated boundary
  7437. {
  7438. MultipartFormDataWriter writer;
  7439. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7440. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7441. writer.content_type());
  7442. auto body = writer.serialize(items);
  7443. EXPECT_EQ(body.size(), writer.content_length(items));
  7444. auto res = cli.Post("/post", body, writer.content_type());
  7445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7446. EXPECT_EQ(StatusCode::OK_200, res->status);
  7447. }
  7448. // Per-part framing with a custom boundary via a content provider
  7449. {
  7450. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7451. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7452. MultipartFormDataWriter writer("custom-boundary_123");
  7453. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7454. std::string body;
  7455. for (const auto &item : items) {
  7456. body += writer.item_begin(item);
  7457. body += item.content;
  7458. body += MultipartFormDataWriter::item_end();
  7459. }
  7460. body += writer.finish();
  7461. EXPECT_EQ(body.size(), writer.content_length(items));
  7462. auto res = cli.Post(
  7463. "/post", body.size(),
  7464. [&](size_t offset, size_t length, DataSink &sink) {
  7465. sink.write(body.data() + offset, length);
  7466. return true;
  7467. },
  7468. writer.content_type());
  7469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7470. EXPECT_EQ(StatusCode::OK_200, res->status);
  7471. }
  7472. }
  7473. TEST_F(ServerTest, PostContentReceiverGzip) {
  7474. cli_.set_compress(true);
  7475. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7477. ASSERT_EQ(StatusCode::OK_200, res->status);
  7478. ASSERT_EQ("content", res->body);
  7479. }
  7480. TEST_F(ServerTest, PutContentReceiver) {
  7481. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7483. ASSERT_EQ(StatusCode::OK_200, res->status);
  7484. ASSERT_EQ("content", res->body);
  7485. }
  7486. TEST_F(ServerTest, PatchContentReceiver) {
  7487. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7489. ASSERT_EQ(StatusCode::OK_200, res->status);
  7490. ASSERT_EQ("content", res->body);
  7491. }
  7492. template <typename ClientType>
  7493. void TestWithHeadersAndContentReceiver(
  7494. ClientType &cli,
  7495. std::function<Result(ClientType &, const std::string &, const Headers &,
  7496. const std::string &, const std::string &,
  7497. ContentReceiver, DownloadProgress)>
  7498. request_func) {
  7499. Headers headers;
  7500. headers.emplace("X-Custom-Header", "test-value");
  7501. std::string received_body;
  7502. auto res = request_func(
  7503. cli, "/content_receiver", headers, "content", "application/json",
  7504. [&](const char *data, size_t data_length) {
  7505. received_body.append(data, data_length);
  7506. return true;
  7507. },
  7508. nullptr);
  7509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7510. EXPECT_EQ(StatusCode::OK_200, res->status);
  7511. EXPECT_EQ("content", received_body);
  7512. }
  7513. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7514. #ifdef CPPHTTPLIB_SSL_ENABLED
  7515. using ClientT = SSLClient;
  7516. #else
  7517. using ClientT = Client;
  7518. #endif
  7519. TestWithHeadersAndContentReceiver<ClientT>(
  7520. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7521. const std::string &body, const std::string &content_type,
  7522. ContentReceiver receiver, DownloadProgress progress) {
  7523. return cli.Post(path, headers, body, content_type, receiver, progress);
  7524. });
  7525. }
  7526. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7527. #ifdef CPPHTTPLIB_SSL_ENABLED
  7528. using ClientT = SSLClient;
  7529. #else
  7530. using ClientT = Client;
  7531. #endif
  7532. TestWithHeadersAndContentReceiver<ClientT>(
  7533. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7534. const std::string &body, const std::string &content_type,
  7535. ContentReceiver receiver, DownloadProgress progress) {
  7536. return cli.Put(path, headers, body, content_type, receiver, progress);
  7537. });
  7538. }
  7539. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7540. #ifdef CPPHTTPLIB_SSL_ENABLED
  7541. using ClientT = SSLClient;
  7542. #else
  7543. using ClientT = Client;
  7544. #endif
  7545. TestWithHeadersAndContentReceiver<ClientT>(
  7546. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7547. const std::string &body, const std::string &content_type,
  7548. ContentReceiver receiver, DownloadProgress progress) {
  7549. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7550. });
  7551. }
  7552. template <typename ClientType>
  7553. void TestWithHeadersAndContentReceiverWithProgress(
  7554. ClientType &cli,
  7555. std::function<Result(ClientType &, const std::string &, const Headers &,
  7556. const std::string &, const std::string &,
  7557. ContentReceiver, DownloadProgress)>
  7558. request_func) {
  7559. Headers headers;
  7560. headers.emplace("X-Test-Header", "progress-test");
  7561. std::string received_body;
  7562. auto progress_called = false;
  7563. auto res = request_func(
  7564. cli, "/content_receiver", headers, "content", "text/plain",
  7565. [&](const char *data, size_t data_length) {
  7566. received_body.append(data, data_length);
  7567. return true;
  7568. },
  7569. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7570. progress_called = true;
  7571. return true;
  7572. });
  7573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7574. EXPECT_EQ(StatusCode::OK_200, res->status);
  7575. EXPECT_EQ("content", received_body);
  7576. EXPECT_TRUE(progress_called);
  7577. }
  7578. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7579. #ifdef CPPHTTPLIB_SSL_ENABLED
  7580. using ClientT = SSLClient;
  7581. #else
  7582. using ClientT = Client;
  7583. #endif
  7584. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7585. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7586. const std::string &body, const std::string &content_type,
  7587. ContentReceiver receiver, DownloadProgress progress) {
  7588. return cli.Post(path, headers, body, content_type, receiver, progress);
  7589. });
  7590. }
  7591. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7592. #ifdef CPPHTTPLIB_SSL_ENABLED
  7593. using ClientT = SSLClient;
  7594. #else
  7595. using ClientT = Client;
  7596. #endif
  7597. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7598. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7599. const std::string &body, const std::string &content_type,
  7600. ContentReceiver receiver, DownloadProgress progress) {
  7601. return cli.Put(path, headers, body, content_type, receiver, progress);
  7602. });
  7603. }
  7604. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7605. #ifdef CPPHTTPLIB_SSL_ENABLED
  7606. using ClientT = SSLClient;
  7607. #else
  7608. using ClientT = Client;
  7609. #endif
  7610. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7611. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7612. const std::string &body, const std::string &content_type,
  7613. ContentReceiver receiver, DownloadProgress progress) {
  7614. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7615. });
  7616. }
  7617. template <typename ClientType>
  7618. void TestWithHeadersAndContentReceiverError(
  7619. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7620. const Headers &, const std::string &,
  7621. const std::string &, ContentReceiver)>
  7622. request_func) {
  7623. Headers headers;
  7624. headers.emplace("X-Error-Test", "true");
  7625. std::string received_body;
  7626. auto receiver_failed = false;
  7627. auto res =
  7628. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7629. [&](const char *data, size_t data_length) {
  7630. received_body.append(data, data_length);
  7631. receiver_failed = true;
  7632. return false;
  7633. });
  7634. ASSERT_FALSE(res);
  7635. EXPECT_TRUE(receiver_failed);
  7636. }
  7637. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7638. #ifdef CPPHTTPLIB_SSL_ENABLED
  7639. using ClientT = SSLClient;
  7640. #else
  7641. using ClientT = Client;
  7642. #endif
  7643. TestWithHeadersAndContentReceiverError<ClientT>(
  7644. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7645. const std::string &body, const std::string &content_type,
  7646. ContentReceiver receiver) {
  7647. return cli.Post(path, headers, body, content_type, receiver);
  7648. });
  7649. }
  7650. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7651. #ifdef CPPHTTPLIB_SSL_ENABLED
  7652. using ClientT = SSLClient;
  7653. #else
  7654. using ClientT = Client;
  7655. #endif
  7656. TestWithHeadersAndContentReceiverError<ClientT>(
  7657. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7658. const std::string &body, const std::string &content_type,
  7659. ContentReceiver receiver) {
  7660. return cli.Put(path, headers, body, content_type, receiver);
  7661. });
  7662. }
  7663. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7664. #ifdef CPPHTTPLIB_SSL_ENABLED
  7665. using ClientT = SSLClient;
  7666. #else
  7667. using ClientT = Client;
  7668. #endif
  7669. TestWithHeadersAndContentReceiverError<ClientT>(
  7670. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7671. const std::string &body, const std::string &content_type,
  7672. ContentReceiver receiver) {
  7673. return cli.Patch(path, headers, body, content_type, receiver);
  7674. });
  7675. }
  7676. TEST_F(ServerTest, PostQueryStringAndBody) {
  7677. auto res =
  7678. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. ASSERT_EQ(StatusCode::OK_200, res->status);
  7681. }
  7682. TEST_F(ServerTest, HTTP2Magic) {
  7683. Request req;
  7684. req.method = "PRI";
  7685. req.path = "*";
  7686. req.body = "SM";
  7687. auto res = std::make_shared<Response>();
  7688. auto error = Error::Success;
  7689. auto ret = cli_.send(req, *res, error);
  7690. ASSERT_TRUE(ret);
  7691. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7692. }
  7693. TEST_F(ServerTest, KeepAlive) {
  7694. auto res = cli_.Get("/hi");
  7695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7696. EXPECT_EQ(StatusCode::OK_200, res->status);
  7697. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7698. EXPECT_EQ("Hello World!", res->body);
  7699. res = cli_.Get("/hi");
  7700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7701. EXPECT_EQ(StatusCode::OK_200, res->status);
  7702. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7703. EXPECT_EQ("Hello World!", res->body);
  7704. res = cli_.Get("/hi");
  7705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7706. EXPECT_EQ(StatusCode::OK_200, res->status);
  7707. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7708. EXPECT_EQ("Hello World!", res->body);
  7709. res = cli_.Get("/not-exist");
  7710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7711. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7712. res = cli_.Post("/empty", "", "text/plain");
  7713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7714. EXPECT_EQ(StatusCode::OK_200, res->status);
  7715. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7716. EXPECT_EQ("empty", res->body);
  7717. EXPECT_EQ("close", res->get_header_value("Connection"));
  7718. res = cli_.Post(
  7719. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7720. "text/plain");
  7721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7722. EXPECT_EQ(StatusCode::OK_200, res->status);
  7723. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7724. EXPECT_EQ("empty", res->body);
  7725. cli_.set_keep_alive(false);
  7726. res = cli_.Get("/last-request");
  7727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7728. EXPECT_EQ(StatusCode::OK_200, res->status);
  7729. EXPECT_EQ("close", res->get_header_value("Connection"));
  7730. }
  7731. TEST_F(ServerTest, TooManyRedirect) {
  7732. cli_.set_follow_location(true);
  7733. auto res = cli_.Get("/redirect/0");
  7734. ASSERT_TRUE(!res);
  7735. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7736. }
  7737. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7738. Request req;
  7739. req.method = "FOOBAR";
  7740. req.path = "/hi";
  7741. cli_.set_keep_alive(true);
  7742. auto res = cli_.send(req);
  7743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7744. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7745. EXPECT_EQ("close", res->get_header_value("Connection"));
  7746. EXPECT_FALSE(cli_.is_socket_open());
  7747. }
  7748. TEST_F(ServerTest, CustomRouteReadsBody) {
  7749. const std::string xml =
  7750. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7751. Request req;
  7752. req.method = "PROPFIND";
  7753. req.path = "/dav/dir";
  7754. req.set_header("Depth", "1");
  7755. req.body = xml;
  7756. auto res = cli_.send(req);
  7757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7758. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7759. EXPECT_EQ(xml, res->body);
  7760. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7761. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7762. }
  7763. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7764. Request req;
  7765. req.method = "PROPFIND";
  7766. req.path = "/dav/42";
  7767. auto res = cli_.send(req);
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7770. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7771. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7772. }
  7773. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7774. Request req;
  7775. req.method = "PROPFIND";
  7776. req.path = "/dav-re/123";
  7777. auto res = cli_.send(req);
  7778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7779. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7780. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7781. }
  7782. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7783. Request req;
  7784. req.method = "MKCOL";
  7785. req.path = "/dav-mkcol";
  7786. auto res = cli_.send(req);
  7787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7788. EXPECT_EQ(StatusCode::Created_201, res->status);
  7789. }
  7790. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7791. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7792. Request req;
  7793. req.method = "REPORT";
  7794. req.path = "/dav-report";
  7795. req.body = xml;
  7796. auto res = cli_.send(req);
  7797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7798. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7799. EXPECT_EQ(xml, res->body);
  7800. }
  7801. // A content reader route must fire even when the request carries no body,
  7802. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7803. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7804. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7805. Request req;
  7806. req.method = "REPORT";
  7807. req.path = "/dav-report";
  7808. auto res = cli_.send(req);
  7809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7810. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7811. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7812. }
  7813. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7814. Request req;
  7815. req.method = "PROPFIND";
  7816. req.path = "/not-dav";
  7817. auto res = cli_.send(req);
  7818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7819. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7820. }
  7821. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7822. Request req;
  7823. req.method = "UNLOCK";
  7824. req.path = "/dav/dir";
  7825. cli_.set_keep_alive(true);
  7826. auto res = cli_.send(req);
  7827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7828. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7829. EXPECT_EQ("close", res->get_header_value("Connection"));
  7830. EXPECT_FALSE(cli_.is_socket_open());
  7831. }
  7832. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7833. // The mount point serves this path, but only for GET and HEAD.
  7834. auto get_res = cli_.Get("/dir/index.html");
  7835. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7836. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7837. Request req;
  7838. req.method = "PROPFIND";
  7839. req.path = "/dir/index.html";
  7840. auto res = cli_.send(req);
  7841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7842. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7843. }
  7844. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7845. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7846. cli_.set_keep_alive(true);
  7847. for (auto i = 0; i < 2; i++) {
  7848. Request req;
  7849. req.method = "PROPFIND";
  7850. req.path = "/dav/dir";
  7851. req.body = xml;
  7852. auto res = cli_.send(req);
  7853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7854. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7855. EXPECT_EQ(xml, res->body);
  7856. EXPECT_TRUE(cli_.is_socket_open());
  7857. }
  7858. // A built-in method must still be served on the same connection.
  7859. cli_.set_keep_alive(false);
  7860. auto res = cli_.Get("/hi");
  7861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7862. EXPECT_EQ(StatusCode::OK_200, res->status);
  7863. EXPECT_EQ("close", res->get_header_value("Connection"));
  7864. }
  7865. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7866. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7867. Request req;
  7868. req.method = "PROPFIND";
  7869. req.path = "/dav/dir";
  7870. req.set_header("Expect", "100-continue");
  7871. req.body = xml;
  7872. auto res = cli_.send(req);
  7873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7874. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7875. EXPECT_EQ(xml, res->body);
  7876. }
  7877. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7878. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7879. TEST_F(ServerTest, Gzip) {
  7880. Headers headers;
  7881. headers.emplace("Accept-Encoding", "gzip, deflate");
  7882. auto res = cli_.Get("/compress", headers);
  7883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7884. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7885. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7886. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7887. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7888. "7890123456789012345678901234567890",
  7889. res->body);
  7890. EXPECT_EQ(StatusCode::OK_200, res->status);
  7891. }
  7892. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7893. Headers headers;
  7894. headers.emplace("Accept-Encoding", "gzip, deflate");
  7895. auto res = cli_.Get("/compress-with-charset", headers);
  7896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7897. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7898. EXPECT_EQ("application/json; charset=utf-8",
  7899. res->get_header_value("Content-Type"));
  7900. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7901. "7890123456789012345678901234567890",
  7902. res->body);
  7903. EXPECT_EQ(StatusCode::OK_200, res->status);
  7904. }
  7905. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7906. Headers headers;
  7907. headers.emplace("Accept-Encoding", "");
  7908. auto res = cli_.Get("/compress", headers);
  7909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7910. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7911. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7912. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7913. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7914. "7890123456789012345678901234567890",
  7915. res->body);
  7916. EXPECT_EQ(StatusCode::OK_200, res->status);
  7917. }
  7918. TEST_F(ServerTest, GzipWithContentReceiver) {
  7919. Headers headers;
  7920. headers.emplace("Accept-Encoding", "gzip, deflate");
  7921. std::string body;
  7922. auto res = cli_.Get("/compress", headers,
  7923. [&](const char *data, uint64_t data_length) {
  7924. EXPECT_EQ(100U, data_length);
  7925. body.append(data, data_length);
  7926. return true;
  7927. });
  7928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7929. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7930. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7931. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7932. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7933. "7890123456789012345678901234567890",
  7934. body);
  7935. EXPECT_EQ(StatusCode::OK_200, res->status);
  7936. }
  7937. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7938. Headers headers;
  7939. headers.emplace("Accept-Encoding", "gzip, deflate");
  7940. cli_.set_decompress(false);
  7941. auto res = cli_.Get("/compress", headers);
  7942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7943. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7944. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7945. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7946. EXPECT_EQ(33U, res->body.size());
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. }
  7949. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7950. Headers headers;
  7951. headers.emplace("Accept-Encoding", "");
  7952. std::string body;
  7953. auto res = cli_.Get("/compress", headers,
  7954. [&](const char *data, uint64_t data_length) {
  7955. EXPECT_EQ(100U, data_length);
  7956. body.append(data, data_length);
  7957. return true;
  7958. });
  7959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7960. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7961. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7962. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7963. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7964. "7890123456789012345678901234567890",
  7965. body);
  7966. EXPECT_EQ(StatusCode::OK_200, res->status);
  7967. }
  7968. TEST_F(ServerTest, NoGzip) {
  7969. Headers headers;
  7970. headers.emplace("Accept-Encoding", "gzip, deflate");
  7971. auto res = cli_.Get("/nocompress", headers);
  7972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7973. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7974. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7975. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7976. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7977. "7890123456789012345678901234567890",
  7978. res->body);
  7979. EXPECT_EQ(StatusCode::OK_200, res->status);
  7980. }
  7981. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7982. Headers headers;
  7983. headers.emplace("Accept-Encoding", "gzip, deflate");
  7984. std::string body;
  7985. auto res = cli_.Get("/nocompress", headers,
  7986. [&](const char *data, uint64_t data_length) {
  7987. EXPECT_EQ(100U, data_length);
  7988. body.append(data, data_length);
  7989. return true;
  7990. });
  7991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7992. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7993. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7994. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7995. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7996. "7890123456789012345678901234567890",
  7997. body);
  7998. EXPECT_EQ(StatusCode::OK_200, res->status);
  7999. }
  8000. TEST_F(ServerTest, MultipartFormDataGzip) {
  8001. UploadFormDataItems items = {
  8002. {"key1", "test", "", ""},
  8003. {"key2", "--abcdefg123", "", ""},
  8004. };
  8005. cli_.set_compress(true);
  8006. auto res = cli_.Post("/compress-multipart", items);
  8007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8008. EXPECT_EQ(StatusCode::OK_200, res->status);
  8009. }
  8010. #endif
  8011. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8012. // Static file compression is opt-in, so these run their own server rather than
  8013. // flipping it on for the shared ServerTest fixture, which would silently
  8014. // rewrite what every other static file test is asserting.
  8015. class StaticFileCompressionTest : public ::testing::Test {
  8016. protected:
  8017. void TearDown() override {
  8018. if (t_.joinable()) {
  8019. svr_.stop();
  8020. t_.join();
  8021. }
  8022. }
  8023. int start(const std::function<void(Server &)> &configure = nullptr) {
  8024. // Serves the same tree as a directory of build-time compressed assets
  8025. // would be served: the mount point names the coding the files are already
  8026. // stored in. Registered before "/" so it is the one that matches.
  8027. svr_.set_mount_point("/pre-encoded", "./www",
  8028. {{"Content-Encoding", "gzip"}});
  8029. svr_.set_mount_point("/", "./www");
  8030. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8031. res.set_file_content("./www/dir/index.html", "text/html");
  8032. });
  8033. svr_.Get("/pre-encoded-file-content",
  8034. [](const Request & /*req*/, Response &res) {
  8035. res.set_header("Content-Encoding", "gzip");
  8036. res.set_file_content("./www/dir/index.html", "text/html");
  8037. });
  8038. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8039. res.set_content_provider(
  8040. 6, "text/plain",
  8041. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8042. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8043. return true;
  8044. });
  8045. });
  8046. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8047. res.set_content_provider(
  8048. 1000, "text/plain",
  8049. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8050. if (offset < 100) {
  8051. std::string data(100, 'A');
  8052. sink.write(data.data(), data.size());
  8053. return true;
  8054. }
  8055. std::this_thread::sleep_for(std::chrono::seconds(2));
  8056. std::string data(900, 'B');
  8057. sink.write(data.data(), data.size());
  8058. return true;
  8059. });
  8060. });
  8061. if (configure) { configure(svr_); }
  8062. auto port = svr_.bind_to_any_port(HOST);
  8063. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8064. svr_.wait_until_ready();
  8065. return port;
  8066. }
  8067. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8068. // Every file under ./www except 1MB.txt is smaller than the default
  8069. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8070. // it out of the way.
  8071. static void enable_without_floor(Server &svr) {
  8072. svr.set_static_file_compression(true);
  8073. svr.set_static_file_compression_min_length(0);
  8074. }
  8075. Server svr_;
  8076. std::thread t_;
  8077. };
  8078. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8079. auto port = start();
  8080. Client cli(HOST, port);
  8081. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8083. EXPECT_EQ(StatusCode::OK_200, res->status);
  8084. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8085. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8086. EXPECT_EQ(1048576U, res->body.size());
  8087. }
  8088. TEST_F(StaticFileCompressionTest, MountPoint) {
  8089. auto port = start(enable);
  8090. Client cli(HOST, port);
  8091. cli.set_decompress(false);
  8092. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8094. EXPECT_EQ(StatusCode::OK_200, res->status);
  8095. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8096. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8097. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8098. // The response stays self-delimiting: a length, not a chunked body.
  8099. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8100. EXPECT_EQ(std::to_string(res->body.size()),
  8101. res->get_header_value("Content-Length"));
  8102. EXPECT_LT(res->body.size(), 1048576U);
  8103. EXPECT_FALSE(res->body.empty());
  8104. }
  8105. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8106. auto port = start(enable);
  8107. Client cli(HOST, port);
  8108. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8110. EXPECT_EQ(StatusCode::OK_200, res->status);
  8111. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8112. EXPECT_EQ(1048576U, res->body.size());
  8113. }
  8114. TEST_F(StaticFileCompressionTest, FileContent) {
  8115. auto port = start(enable_without_floor);
  8116. Client cli(HOST, port);
  8117. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8119. EXPECT_EQ(StatusCode::OK_200, res->status);
  8120. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8121. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8122. EXPECT_EQ(104U, res->body.size());
  8123. }
  8124. // A handler that serves an already-encoded file names the coding itself. The
  8125. // file-backed path decided its coding from Accept-Encoding and the content
  8126. // type alone, so it compressed the stored bytes a second time and appended a
  8127. // second Content-Encoding field line.
  8128. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8129. auto port = start(enable_without_floor);
  8130. Client cli(HOST, port);
  8131. cli.set_decompress(false);
  8132. auto res = cli.Get("/pre-encoded-file-content",
  8133. Headers{{"Accept-Encoding", "gzip"}});
  8134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8135. EXPECT_EQ(StatusCode::OK_200, res->status);
  8136. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8137. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8138. // Vary belongs to a coding the server chose, and it chose none here.
  8139. EXPECT_FALSE(res->has_header("Vary"));
  8140. // The file travels exactly as it is stored on disk.
  8141. EXPECT_EQ(104U, res->body.size());
  8142. }
  8143. // The 1MB file clears the default floor, so this one runs the configuration a
  8144. // deployment would actually have.
  8145. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8146. auto port = start(enable);
  8147. Client cli(HOST, port);
  8148. cli.set_decompress(false);
  8149. auto res =
  8150. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8152. EXPECT_EQ(StatusCode::OK_200, res->status);
  8153. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8154. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8155. EXPECT_FALSE(res->has_header("Vary"));
  8156. EXPECT_EQ(1048576U, res->body.size());
  8157. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8158. }
  8159. TEST_F(StaticFileCompressionTest, Head) {
  8160. auto port = start(enable);
  8161. Client cli(HOST, port);
  8162. cli.set_decompress(false);
  8163. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8164. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8165. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. EXPECT_EQ(StatusCode::OK_200, res->status);
  8168. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8169. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8170. // HEAD still reports the size a GET would return.
  8171. EXPECT_EQ(get->get_header_value("Content-Length"),
  8172. res->get_header_value("Content-Length"));
  8173. EXPECT_TRUE(res->body.empty());
  8174. }
  8175. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8176. auto port = start(enable);
  8177. Client cli(HOST, port);
  8178. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8179. {"Accept-Encoding", "gzip"}});
  8180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8181. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8182. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8183. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8184. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8185. EXPECT_EQ("cd", res->body);
  8186. }
  8187. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8188. auto port = start(enable);
  8189. Client cli(HOST, port);
  8190. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8192. EXPECT_EQ(StatusCode::OK_200, res->status);
  8193. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8194. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8195. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8196. }
  8197. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8198. auto port = start(enable);
  8199. Client cli(HOST, port);
  8200. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8202. EXPECT_EQ(StatusCode::OK_200, res->status);
  8203. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8204. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8205. EXPECT_TRUE(res->body.empty());
  8206. }
  8207. TEST_F(StaticFileCompressionTest, MinLength) {
  8208. auto port = start(enable);
  8209. Client cli(HOST, port);
  8210. // 104 bytes, well under the default floor. Compressing it would add the
  8211. // gzip header and trailer to a body that already fits in one packet.
  8212. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8214. EXPECT_EQ(StatusCode::OK_200, res->status);
  8215. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8216. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8217. }
  8218. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8219. auto port = start([](Server &svr) {
  8220. svr.set_static_file_compression(true);
  8221. svr.set_static_file_compression_min_length(1);
  8222. });
  8223. Client cli(HOST, port);
  8224. cli.set_decompress(false);
  8225. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8227. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8228. // A 9-byte file comes back larger than it went in, because gzip's header and
  8229. // trailer outweigh anything deflate can save. That is the end of the range
  8230. // the floor exists to keep out.
  8231. EXPECT_GT(res->body.size(), 9U);
  8232. }
  8233. TEST_F(StaticFileCompressionTest, MaxLength) {
  8234. auto port = start([](Server &svr) {
  8235. svr.set_static_file_compression(true);
  8236. svr.set_static_file_compression_min_length(0);
  8237. svr.set_static_file_compression_max_length(1024);
  8238. });
  8239. Client cli(HOST, port);
  8240. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8241. // defines `small` as a macro on Windows.
  8242. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8243. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8244. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8245. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8246. // Under it: compressed.
  8247. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8248. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8249. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8250. }
  8251. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8252. auto port = start(enable_without_floor);
  8253. Client cli(HOST, port);
  8254. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8255. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8256. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8257. auto identity_etag = identity->get_header_value("ETag");
  8258. ASSERT_FALSE(identity_etag.empty());
  8259. auto gzipped =
  8260. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8261. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8262. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8263. auto gzip_etag = gzipped->get_header_value("ETag");
  8264. ASSERT_FALSE(gzip_etag.empty());
  8265. // Two representations, two validators.
  8266. EXPECT_NE(identity_etag, gzip_etag);
  8267. // Each one revalidates against the request that would produce it...
  8268. auto fresh =
  8269. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8270. {"If-None-Match", gzip_etag}});
  8271. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8272. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8273. auto fresh_identity =
  8274. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8275. {"If-None-Match", identity_etag}});
  8276. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8277. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8278. // ...and not against the other representation.
  8279. auto crossed =
  8280. cli.Get("/dir/index.html",
  8281. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8282. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8283. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8284. }
  8285. // The opt-in covers responses the server reads off disk itself. A caller's own
  8286. // known-length provider keeps its Content-Length and, more importantly, keeps
  8287. // delivering incrementally: routing it through a compressor would hold every
  8288. // write back until zlib's window filled.
  8289. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8290. auto port = start(enable);
  8291. Client cli(HOST, port);
  8292. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8294. EXPECT_EQ(StatusCode::OK_200, res->status);
  8295. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8296. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8297. EXPECT_EQ("aaabbb", res->body);
  8298. }
  8299. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8300. auto port = start(enable);
  8301. Client cli(HOST, port);
  8302. cli.set_read_timeout(1, 0);
  8303. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8304. Headers{{"Accept-Encoding", "gzip"}});
  8305. ASSERT_TRUE(handle.is_valid());
  8306. // The provider writes 100 bytes and then stalls for longer than the read
  8307. // timeout. Those first bytes have to arrive anyway: run the response through
  8308. // a compressor and zlib holds them until its window fills, so the read would
  8309. // come back empty instead.
  8310. char buf[256];
  8311. auto n = handle.read(buf, sizeof(buf));
  8312. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8313. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8314. }
  8315. #endif
  8316. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8317. TEST_F(ServerTest, Brotli) {
  8318. Headers headers;
  8319. headers.emplace("Accept-Encoding", "br");
  8320. auto res = cli_.Get("/compress", headers);
  8321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8322. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8323. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8324. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8325. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8326. "7890123456789012345678901234567890",
  8327. res->body);
  8328. EXPECT_EQ(StatusCode::OK_200, res->status);
  8329. }
  8330. #endif
  8331. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8332. TEST_F(ServerTest, Zstd) {
  8333. Headers headers;
  8334. headers.emplace("Accept-Encoding", "zstd");
  8335. auto res = cli_.Get("/compress", headers);
  8336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8337. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8339. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8340. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8341. "7890123456789012345678901234567890",
  8342. res->body);
  8343. EXPECT_EQ(StatusCode::OK_200, res->status);
  8344. }
  8345. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8346. Headers headers;
  8347. headers.emplace("Accept-Encoding", "");
  8348. auto res = cli_.Get("/compress", headers);
  8349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8350. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8351. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8352. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8353. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8354. "7890123456789012345678901234567890",
  8355. res->body);
  8356. EXPECT_EQ(StatusCode::OK_200, res->status);
  8357. }
  8358. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8359. Headers headers;
  8360. headers.emplace("Accept-Encoding", "zstd");
  8361. std::string body;
  8362. auto res = cli_.Get("/compress", headers,
  8363. [&](const char *data, uint64_t data_length) {
  8364. EXPECT_EQ(100U, data_length);
  8365. body.append(data, data_length);
  8366. return true;
  8367. });
  8368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8369. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8370. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8371. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8372. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8373. "7890123456789012345678901234567890",
  8374. body);
  8375. EXPECT_EQ(StatusCode::OK_200, res->status);
  8376. }
  8377. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8378. Headers headers;
  8379. headers.emplace("Accept-Encoding", "zstd");
  8380. cli_.set_decompress(false);
  8381. auto res = cli_.Get("/compress", headers);
  8382. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8383. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8384. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8385. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8387. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8388. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8389. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8390. EXPECT_EQ(StatusCode::OK_200, res->status);
  8391. ASSERT_EQ(26U, res->body.size());
  8392. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8393. 0);
  8394. }
  8395. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8396. Headers headers;
  8397. headers.emplace("Accept-Encoding", "");
  8398. std::string body;
  8399. auto res = cli_.Get("/compress", headers,
  8400. [&](const char *data, uint64_t data_length) {
  8401. EXPECT_EQ(100U, data_length);
  8402. body.append(data, data_length);
  8403. return true;
  8404. });
  8405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8406. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8407. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8408. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8409. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8410. "7890123456789012345678901234567890",
  8411. body);
  8412. EXPECT_EQ(StatusCode::OK_200, res->status);
  8413. }
  8414. TEST_F(ServerTest, NoZstd) {
  8415. Headers headers;
  8416. headers.emplace("Accept-Encoding", "zstd");
  8417. auto res = cli_.Get("/nocompress", headers);
  8418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8419. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8420. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8421. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8422. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8423. "7890123456789012345678901234567890",
  8424. res->body);
  8425. EXPECT_EQ(StatusCode::OK_200, res->status);
  8426. }
  8427. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8428. Headers headers;
  8429. headers.emplace("Accept-Encoding", "zstd");
  8430. std::string body;
  8431. auto res = cli_.Get("/nocompress", headers,
  8432. [&](const char *data, uint64_t data_length) {
  8433. EXPECT_EQ(100U, data_length);
  8434. body.append(data, data_length);
  8435. return true;
  8436. });
  8437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8438. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8439. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8440. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8441. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8442. "7890123456789012345678901234567890",
  8443. body);
  8444. EXPECT_EQ(StatusCode::OK_200, res->status);
  8445. }
  8446. // TODO: How to enable zstd ??
  8447. TEST_F(ServerTest, MultipartFormDataZstd) {
  8448. UploadFormDataItems items = {
  8449. {"key1", "test", "", ""},
  8450. {"key2", "--abcdefg123", "", ""},
  8451. };
  8452. Headers headers;
  8453. headers.emplace("Accept-Encoding", "zstd");
  8454. cli_.set_compress(true);
  8455. auto res = cli_.Post("/compress-multipart", headers, items);
  8456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8457. EXPECT_EQ(StatusCode::OK_200, res->status);
  8458. }
  8459. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8460. Headers headers;
  8461. headers.emplace("Accept-Encoding", "zstd");
  8462. cli_.set_compress(true);
  8463. auto res = cli_.Put(
  8464. "/put", headers, 3,
  8465. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8466. sink.os << "PUT";
  8467. return true;
  8468. },
  8469. "text/plain");
  8470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8471. EXPECT_EQ(StatusCode::OK_200, res->status);
  8472. EXPECT_EQ("PUT", res->body);
  8473. }
  8474. // Pre-compression logging tests
  8475. TEST_F(ServerTest, PreCompressionLogging) {
  8476. // Test data for compression (matches the actual /compress endpoint content)
  8477. const std::string test_content =
  8478. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8479. "3456789012345678901234567890";
  8480. // Variables to capture logging data
  8481. std::string pre_compression_body;
  8482. std::string pre_compression_content_type;
  8483. std::string pre_compression_content_encoding;
  8484. std::string post_compression_body;
  8485. std::string post_compression_content_type;
  8486. std::string post_compression_content_encoding;
  8487. // Set up pre-compression logger
  8488. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8489. const Response &res) {
  8490. pre_compression_body = res.body;
  8491. pre_compression_content_type = res.get_header_value("Content-Type");
  8492. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8493. });
  8494. // Set up post-compression logger
  8495. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8496. post_compression_body = res.body;
  8497. post_compression_content_type = res.get_header_value("Content-Type");
  8498. post_compression_content_encoding =
  8499. res.get_header_value("Content-Encoding");
  8500. });
  8501. // Test with gzip compression
  8502. Headers headers;
  8503. headers.emplace("Accept-Encoding", "gzip");
  8504. auto res = cli_.Get("/compress", headers);
  8505. // Verify response was compressed
  8506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8507. EXPECT_EQ(StatusCode::OK_200, res->status);
  8508. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8509. // Verify pre-compression logger captured uncompressed content
  8510. EXPECT_EQ(test_content, pre_compression_body);
  8511. EXPECT_EQ("text/plain", pre_compression_content_type);
  8512. EXPECT_TRUE(pre_compression_content_encoding
  8513. .empty()); // No encoding header before compression
  8514. // Verify post-compression logger captured compressed content
  8515. EXPECT_NE(test_content,
  8516. post_compression_body); // Should be different after compression
  8517. EXPECT_EQ("text/plain", post_compression_content_type);
  8518. EXPECT_EQ("gzip", post_compression_content_encoding);
  8519. // Verify compressed content is smaller
  8520. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8521. }
  8522. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8523. const std::string test_content =
  8524. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8525. "3456789012345678901234567890";
  8526. std::string pre_compression_body;
  8527. std::string post_compression_body;
  8528. svr_.set_pre_compression_logger(
  8529. [&](const Request & /*req*/, const Response &res) {
  8530. pre_compression_body = res.body;
  8531. });
  8532. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8533. post_compression_body = res.body;
  8534. });
  8535. Headers headers;
  8536. headers.emplace("Accept-Encoding", "br");
  8537. auto res = cli_.Get("/compress", headers);
  8538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8539. EXPECT_EQ(StatusCode::OK_200, res->status);
  8540. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8541. // Verify pre-compression content is uncompressed
  8542. EXPECT_EQ(test_content, pre_compression_body);
  8543. // Verify post-compression content is compressed
  8544. EXPECT_NE(test_content, post_compression_body);
  8545. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8546. }
  8547. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8548. const std::string test_content =
  8549. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8550. "3456789012345678901234567890";
  8551. std::string pre_compression_body;
  8552. std::string post_compression_body;
  8553. svr_.set_pre_compression_logger(
  8554. [&](const Request & /*req*/, const Response &res) {
  8555. pre_compression_body = res.body;
  8556. });
  8557. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8558. post_compression_body = res.body;
  8559. });
  8560. // Request without compression (use /nocompress endpoint)
  8561. Headers headers;
  8562. auto res = cli_.Get("/nocompress", headers);
  8563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8564. EXPECT_EQ(StatusCode::OK_200, res->status);
  8565. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8566. // Pre-compression logger should not be called when no compression is applied
  8567. EXPECT_TRUE(
  8568. pre_compression_body.empty()); // Pre-compression logger not called
  8569. EXPECT_EQ(
  8570. test_content,
  8571. post_compression_body); // Post-compression logger captures final content
  8572. }
  8573. TEST_F(ServerTest, LoggerSeesContentLength) {
  8574. size_t logged_content_length = 0;
  8575. std::string logged_content_length_header;
  8576. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8577. logged_content_length = res.content_length_;
  8578. logged_content_length_header = res.get_header_value("Content-Length");
  8579. });
  8580. auto res = cli_.Get("/nocompress");
  8581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8582. EXPECT_EQ(StatusCode::OK_200, res->status);
  8583. EXPECT_EQ(res->body.size(), logged_content_length);
  8584. EXPECT_EQ(std::to_string(logged_content_length),
  8585. logged_content_length_header);
  8586. }
  8587. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8588. const std::string test_content =
  8589. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8590. "3456789012345678901234567890";
  8591. std::string pre_compression_body;
  8592. bool pre_logger_called = false;
  8593. // Set only pre-compression logger
  8594. svr_.set_pre_compression_logger(
  8595. [&](const Request & /*req*/, const Response &res) {
  8596. pre_compression_body = res.body;
  8597. pre_logger_called = true;
  8598. });
  8599. Headers headers;
  8600. headers.emplace("Accept-Encoding", "gzip");
  8601. auto res = cli_.Get("/compress", headers);
  8602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8603. EXPECT_EQ(StatusCode::OK_200, res->status);
  8604. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8605. // Verify pre-compression logger was called
  8606. EXPECT_TRUE(pre_logger_called);
  8607. EXPECT_EQ(test_content, pre_compression_body);
  8608. }
  8609. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8610. {
  8611. // Test with Expect: 100-continue header - success case
  8612. // Server returns 100 Continue, client sends body, server returns 200 OK
  8613. Request req;
  8614. req.method = "POST";
  8615. req.path = "/post-large";
  8616. req.set_header("Expect", "100-continue");
  8617. req.body = LARGE_DATA;
  8618. Response res;
  8619. auto error = Error::Success;
  8620. cli_.set_keep_alive(true);
  8621. auto ret = cli_.send(req, res, error);
  8622. EXPECT_TRUE(ret);
  8623. EXPECT_EQ(StatusCode::OK_200, res.status);
  8624. EXPECT_EQ(LARGE_DATA, res.body);
  8625. }
  8626. {
  8627. // Test with Expect: 100-continue header - error case
  8628. // Client should not send the body when server returns an error
  8629. Request req;
  8630. req.method = "POST";
  8631. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8632. req.set_header("Expect", "100-continue");
  8633. req.body = LARGE_DATA;
  8634. Response res;
  8635. auto error = Error::Success;
  8636. auto start = std::chrono::high_resolution_clock::now();
  8637. cli_.set_keep_alive(true);
  8638. auto ret = cli_.send(req, res, error);
  8639. auto end = std::chrono::high_resolution_clock::now();
  8640. auto elapsed =
  8641. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8642. .count();
  8643. // With Expect: 100-continue, request completes successfully but with error
  8644. EXPECT_TRUE(ret);
  8645. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8646. EXPECT_EQ("close", res.get_header_value("Connection"));
  8647. EXPECT_FALSE(cli_.is_socket_open());
  8648. EXPECT_LE(elapsed, 2000);
  8649. }
  8650. {
  8651. // Send an extra GET request to ensure error recovery without hanging
  8652. Request req;
  8653. req.method = "GET";
  8654. req.path = "/hi";
  8655. auto start = std::chrono::high_resolution_clock::now();
  8656. auto res = cli_.send(req);
  8657. auto end = std::chrono::high_resolution_clock::now();
  8658. auto elapsed =
  8659. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8660. .count();
  8661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8662. EXPECT_EQ(StatusCode::OK_200, res->status);
  8663. EXPECT_EQ("Hello World!", res->body);
  8664. EXPECT_LE(elapsed, 500);
  8665. }
  8666. }
  8667. TEST(ZstdDecompressor, ChunkedDecompression) {
  8668. std::string data;
  8669. for (size_t i = 0; i < 32 * 1024; ++i) {
  8670. data.push_back(static_cast<char>('a' + i % 26));
  8671. }
  8672. std::string compressed_data;
  8673. {
  8674. httplib::detail::zstd_compressor compressor;
  8675. bool result = compressor.compress(
  8676. data.data(), data.size(),
  8677. /*last=*/true,
  8678. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8679. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8680. compressed_data_size);
  8681. return true;
  8682. });
  8683. ASSERT_TRUE(result);
  8684. }
  8685. std::string decompressed_data;
  8686. {
  8687. httplib::detail::zstd_decompressor decompressor;
  8688. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8689. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8690. size_t chunk_size = 130;
  8691. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8692. chunk_begin += chunk_size) {
  8693. size_t current_chunk_size =
  8694. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8695. bool result = decompressor.decompress(
  8696. compressed_data.data() + chunk_begin, current_chunk_size,
  8697. [&](const char *decompressed_data_chunk,
  8698. size_t decompressed_data_chunk_size) {
  8699. decompressed_data.insert(decompressed_data.size(),
  8700. decompressed_data_chunk,
  8701. decompressed_data_chunk_size);
  8702. return true;
  8703. });
  8704. ASSERT_TRUE(result);
  8705. }
  8706. }
  8707. ASSERT_EQ(data, decompressed_data);
  8708. }
  8709. TEST(ZstdDecompressor, Decompress) {
  8710. std::string original_text = "Compressed with ZSTD";
  8711. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8712. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8713. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8714. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8715. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8716. std::string decompressed_data;
  8717. {
  8718. httplib::detail::zstd_decompressor decompressor;
  8719. bool result = decompressor.decompress(
  8720. compressed_data.data(), compressed_data.size(),
  8721. [&](const char *decompressed_data_chunk,
  8722. size_t decompressed_data_chunk_size) {
  8723. decompressed_data.insert(decompressed_data.size(),
  8724. decompressed_data_chunk,
  8725. decompressed_data_chunk_size);
  8726. return true;
  8727. });
  8728. ASSERT_TRUE(result);
  8729. }
  8730. ASSERT_EQ(original_text, decompressed_data);
  8731. }
  8732. #endif
  8733. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8734. // separate chunks so that the server sees each part in its own read(). Used to
  8735. // place a read boundary at a specific offset of a request body.
  8736. static bool send_request_in_parts(time_t read_timeout_sec,
  8737. const std::vector<std::string> &parts,
  8738. std::string *resp = nullptr,
  8739. int port = PORT) {
  8740. auto error = Error::Success;
  8741. auto client_sock = detail::create_client_socket(
  8742. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8743. /*connection_timeout_sec=*/5, 0,
  8744. /*read_timeout_sec=*/5, 0,
  8745. /*write_timeout_sec=*/5, 0, std::string(), error);
  8746. if (client_sock == INVALID_SOCKET) { return false; }
  8747. auto ret = detail::process_client_socket(
  8748. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8749. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8750. for (size_t i = 0; i < parts.size(); i++) {
  8751. const auto &part = parts[i];
  8752. if (part.size() !=
  8753. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8754. return false;
  8755. }
  8756. if (i + 1 < parts.size()) {
  8757. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8758. }
  8759. }
  8760. char buf[512];
  8761. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8762. while (line_reader.getline()) {
  8763. if (resp) { *resp += line_reader.ptr(); }
  8764. }
  8765. return true;
  8766. });
  8767. detail::close_socket(client_sock);
  8768. return ret;
  8769. }
  8770. // Sends a raw request to a server listening at HOST:PORT.
  8771. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8772. std::string *resp = nullptr, int port = PORT) {
  8773. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8774. }
  8775. #ifdef CPPHTTPLIB_SSL_ENABLED
  8776. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8777. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8778. ASSERT_TRUE(svr.is_valid());
  8779. svr.set_read_timeout(1, 0);
  8780. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8781. auto se = detail::scope_exit([&] {
  8782. svr.stop();
  8783. t.join();
  8784. ASSERT_FALSE(svr.is_running());
  8785. });
  8786. svr.wait_until_ready();
  8787. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8788. // keeps each wait well within the read timeout. The server gives up a
  8789. // second in, so the bytes sent after that fail.
  8790. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8791. parts.resize(26, std::string(1, '\0'));
  8792. EXPECT_FALSE(send_request_in_parts(5, parts));
  8793. }
  8794. #endif
  8795. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8796. Server svr;
  8797. std::string header_value;
  8798. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8799. header_value = req.get_header_value("foo");
  8800. res.set_content("ok", "text/plain");
  8801. });
  8802. thread t = thread([&] { svr.listen(HOST, PORT); });
  8803. auto se = detail::scope_exit([&] {
  8804. svr.stop();
  8805. t.join();
  8806. ASSERT_FALSE(svr.is_running());
  8807. });
  8808. svr.wait_until_ready();
  8809. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8810. // like characters are not treated the same - use vertical tab and escape.
  8811. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8812. "foo: \t \v bar \x1B\t \r\n"
  8813. "Connection: close\r\n"
  8814. "\r\n";
  8815. std::string res;
  8816. ASSERT_TRUE(send_request(5, req, &res));
  8817. EXPECT_EQ(header_value, "");
  8818. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8819. }
  8820. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8821. Server svr;
  8822. std::string received;
  8823. svr.Get("/order", [&](const Request &req, Response &res) {
  8824. received = entries_to_string(req.headers);
  8825. res.set_content("ok", "text/plain");
  8826. });
  8827. auto port = svr.bind_to_any_port(HOST);
  8828. thread t = thread([&] { svr.listen_after_bind(); });
  8829. auto se = detail::scope_exit([&] {
  8830. svr.stop();
  8831. t.join();
  8832. ASSERT_FALSE(svr.is_running());
  8833. });
  8834. svr.wait_until_ready();
  8835. const std::string req = "GET /order HTTP/1.1\r\n"
  8836. "Host: localhost\r\n"
  8837. "X-First: 1\r\n"
  8838. "X-Dup: a\r\n"
  8839. "X-Second: 2\r\n"
  8840. "X-Dup: b\r\n"
  8841. "Connection: close\r\n"
  8842. "\r\n";
  8843. std::string res;
  8844. ASSERT_TRUE(send_request(5, req, &res, port));
  8845. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8846. EXPECT_EQ(
  8847. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  8848. received);
  8849. }
  8850. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8851. Server svr;
  8852. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8853. res.set_header("Set-Cookie", "first=1");
  8854. res.set_header("X-Between", "y");
  8855. res.set_header("Set-Cookie", "second=2");
  8856. res.set_content("ok", "text/plain");
  8857. });
  8858. auto port = svr.bind_to_any_port(HOST);
  8859. thread t = thread([&] { svr.listen_after_bind(); });
  8860. auto se = detail::scope_exit([&] {
  8861. svr.stop();
  8862. t.join();
  8863. ASSERT_FALSE(svr.is_running());
  8864. });
  8865. svr.wait_until_ready();
  8866. Client cli(HOST, port);
  8867. auto res = cli.Get("/cookies");
  8868. ASSERT_TRUE(res);
  8869. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8870. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8871. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8872. }
  8873. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8874. Server svr;
  8875. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8876. auto i = new int(0);
  8877. res.set_header("Trailer", "X-Safe, X-Reflected");
  8878. res.set_chunked_content_provider(
  8879. "text/plain",
  8880. [i](size_t /*offset*/, DataSink &sink) {
  8881. if (*i == 0) {
  8882. sink.os << "body";
  8883. } else {
  8884. Headers trailer;
  8885. // A valid trailer that must survive.
  8886. trailer.emplace("X-Safe", "safe");
  8887. // Attacker-controlled value carrying CR/LF (response splitting).
  8888. trailer.emplace("X-Reflected",
  8889. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8890. // Attacker-controlled name carrying CR/LF.
  8891. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8892. sink.done_with_trailer(trailer);
  8893. }
  8894. (*i)++;
  8895. return true;
  8896. },
  8897. [i](bool /*success*/) { delete i; });
  8898. });
  8899. thread t = thread([&] { svr.listen(HOST, PORT); });
  8900. auto se = detail::scope_exit([&] {
  8901. svr.stop();
  8902. t.join();
  8903. ASSERT_FALSE(svr.is_running());
  8904. });
  8905. svr.wait_until_ready();
  8906. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8907. "Host: " + HOST +
  8908. "\r\n"
  8909. "Connection: close\r\n"
  8910. "\r\n";
  8911. std::string res;
  8912. ASSERT_TRUE(send_request(5, req, &res));
  8913. // The injected fields must not appear anywhere in the raw response.
  8914. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8915. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8916. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8917. // Invalid trailers are dropped entirely, matching set_header().
  8918. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8919. // The valid trailer still passes through.
  8920. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8921. }
  8922. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8923. Server svr;
  8924. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8925. // res.headers is a public field an application can populate directly,
  8926. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8927. // A valid header that must survive.
  8928. res.headers.emplace("X-Safe", "safe");
  8929. // Attacker-controlled value carrying CR/LF (response splitting).
  8930. res.headers.emplace("X-Reflected",
  8931. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8932. // Attacker-controlled name carrying CR/LF.
  8933. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8934. res.set_content("body", "text/plain");
  8935. });
  8936. thread t = thread([&] { svr.listen(HOST, PORT); });
  8937. auto se = detail::scope_exit([&] {
  8938. svr.stop();
  8939. t.join();
  8940. ASSERT_FALSE(svr.is_running());
  8941. });
  8942. svr.wait_until_ready();
  8943. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8944. "Host: " + HOST +
  8945. "\r\n"
  8946. "Connection: close\r\n"
  8947. "\r\n";
  8948. std::string res;
  8949. ASSERT_TRUE(send_request(5, req, &res));
  8950. // The injected fields must not appear anywhere in the raw response.
  8951. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8952. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8953. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8954. // Invalid headers are dropped entirely, matching set_header().
  8955. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8956. // The valid header still passes through.
  8957. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8958. }
  8959. // Forward declaration: in split builds split.py strips `inline` and moves the
  8960. // definition into httplib.cc, so detail::write_request_line is not visible from
  8961. // the public httplib.h. Re-declaring it here lets the tests link against the
  8962. // symbol in both header-only and split builds.
  8963. namespace httplib {
  8964. namespace detail {
  8965. ssize_t write_request_line(Stream &strm, const std::string &method,
  8966. const std::string &path);
  8967. } // namespace detail
  8968. } // namespace httplib
  8969. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8970. // A well-formed target is written verbatim.
  8971. {
  8972. detail::BufferStream strm;
  8973. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8974. EXPECT_GT(n, 0);
  8975. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8976. }
  8977. // A target carrying CR/LF, SP or other control octets must be rejected
  8978. // before anything reaches the wire, otherwise it splits the request line and
  8979. // injects a header or a whole request.
  8980. const std::string evil_targets[] = {
  8981. "/a\r\nInjected: pwned",
  8982. "/a\rInjected",
  8983. "/a\nInjected",
  8984. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8985. "/a b",
  8986. "/a\tb",
  8987. "/a\x7f",
  8988. };
  8989. for (const auto &evil : evil_targets) {
  8990. detail::BufferStream strm;
  8991. auto n = detail::write_request_line(strm, "GET", evil);
  8992. EXPECT_LT(n, 0);
  8993. EXPECT_TRUE(strm.get_buffer().empty());
  8994. }
  8995. }
  8996. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8997. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8998. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8999. // target reaches write_request. The client must fail cleanly with
  9000. // Error::Write instead of putting a request-line-less, header-injecting
  9001. // request on the wire.
  9002. Server svr;
  9003. svr.Get("/a", [](const Request &, Response &res) {
  9004. res.set_content("ok", "text/plain");
  9005. });
  9006. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9007. auto se = detail::scope_exit([&] {
  9008. svr.stop();
  9009. thread.join();
  9010. ASSERT_FALSE(svr.is_running());
  9011. });
  9012. svr.wait_until_ready();
  9013. {
  9014. Client cli(HOST, PORT);
  9015. cli.set_path_encode(false);
  9016. // The request is rejected before anything is written, so the connection
  9017. // stays silent and the subsequent response read would otherwise block for
  9018. // the full default read timeout. Shorten it -- the assertion is on the
  9019. // error, not the timeout.
  9020. cli.set_read_timeout(1, 0);
  9021. auto res = cli.Get("/a\r\nInjected: pwned");
  9022. EXPECT_FALSE(res);
  9023. EXPECT_EQ(Error::Write, res.error());
  9024. }
  9025. }
  9026. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9027. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9028. // including extension methods.
  9029. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9030. for (const auto &method : good_methods) {
  9031. detail::BufferStream strm;
  9032. auto n = detail::write_request_line(strm, method, "/");
  9033. EXPECT_GT(n, 0);
  9034. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9035. }
  9036. // A method carrying CR/LF would split the request line and smuggle a whole
  9037. // request ahead of the real one. A space or an empty method corrupts the
  9038. // request line. All must be rejected before anything reaches the wire.
  9039. const std::string evil_methods[] = {
  9040. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9041. "GET\r\nInjected: pwned",
  9042. "GET\r",
  9043. "GET\n",
  9044. "GE T",
  9045. "",
  9046. };
  9047. for (const auto &evil : evil_methods) {
  9048. detail::BufferStream strm;
  9049. auto n = detail::write_request_line(strm, evil, "/");
  9050. EXPECT_LT(n, 0);
  9051. EXPECT_TRUE(strm.get_buffer().empty());
  9052. }
  9053. }
  9054. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9055. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9056. // through Client::send must fail with Error::Write and no request, neither
  9057. // the smuggled one nor the real one, may reach the server.
  9058. Server svr;
  9059. std::atomic<int> request_count(0);
  9060. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9061. request_count++;
  9062. res.status = StatusCode::OK_200;
  9063. return Server::HandlerResponse::Handled;
  9064. });
  9065. auto port = svr.bind_to_any_port(HOST);
  9066. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9067. auto se = detail::scope_exit([&] {
  9068. svr.stop();
  9069. thread.join();
  9070. ASSERT_FALSE(svr.is_running());
  9071. });
  9072. svr.wait_until_ready();
  9073. {
  9074. Client cli(HOST, port);
  9075. const std::string evil_methods[] = {
  9076. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9077. "GE T",
  9078. "",
  9079. };
  9080. for (const auto &evil : evil_methods) {
  9081. Request req;
  9082. req.method = evil;
  9083. req.path = "/";
  9084. auto res = cli.send(req);
  9085. EXPECT_FALSE(res);
  9086. EXPECT_EQ(Error::Write, res.error());
  9087. }
  9088. auto handle =
  9089. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9090. EXPECT_FALSE(handle.is_valid());
  9091. EXPECT_EQ(Error::Write, handle.error);
  9092. // A valid request on the same client still goes through.
  9093. auto res = cli.Get("/");
  9094. ASSERT_TRUE(res);
  9095. EXPECT_EQ(StatusCode::OK_200, res->status);
  9096. }
  9097. EXPECT_EQ(1, request_count.load());
  9098. }
  9099. // Sends a raw request and verifies that there isn't a crash or exception.
  9100. static void test_raw_request(const std::string &req,
  9101. std::string *out = nullptr) {
  9102. Server svr;
  9103. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9104. res.set_content("ok", "text/plain");
  9105. });
  9106. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9107. res.set_content("ok", "text/plain");
  9108. });
  9109. svr.Get("/header_field_value_check",
  9110. [&](const Request & /*req*/, Response &res) {
  9111. res.set_content("ok", "text/plain");
  9112. });
  9113. svr.CustomRoute("PROPFIND", "/dav",
  9114. [&](const Request & /*req*/, Response &res) {
  9115. res.status = StatusCode::MultiStatus_207;
  9116. });
  9117. // Server read timeout must be longer than the client read timeout for the
  9118. // bug to reproduce, probably to force the server to process a request
  9119. // without a trailing blank line.
  9120. const time_t client_read_timeout_sec = 1;
  9121. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9122. bool listen_thread_ok = false;
  9123. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9124. auto se = detail::scope_exit([&] {
  9125. svr.stop();
  9126. t.join();
  9127. ASSERT_FALSE(svr.is_running());
  9128. EXPECT_TRUE(listen_thread_ok);
  9129. });
  9130. svr.wait_until_ready();
  9131. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9132. }
  9133. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9134. // A certain header line causes an exception if the header property is parsed
  9135. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9136. test_raw_request(
  9137. "GET /hi HTTP/1.1\r\n"
  9138. " : "
  9139. " "
  9140. " ");
  9141. }
  9142. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9143. // A certain header line causes an exception if the header property *name* is
  9144. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9145. // greedy matcher and requires backtracking when there are a lot of ":"
  9146. // characters.
  9147. // This occurs with libc++ but not libstdc++.
  9148. test_raw_request(
  9149. "GET /hi HTTP/1.1\r\n"
  9150. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9151. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9152. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9153. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9154. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9155. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9156. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9157. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9158. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9159. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9160. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9161. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9162. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9163. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9164. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9165. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9166. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9167. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9168. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9169. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9170. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9171. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9172. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9173. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9174. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9175. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9176. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9177. "&&&%%%");
  9178. }
  9179. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9180. // Make sure this doesn't crash the server.
  9181. // In a previous version of the header line regex, the "\r" rendered the line
  9182. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9183. // a new position where the leading white space ended and the field value
  9184. // began.
  9185. // The crash occurs with libc++ but not libstdc++.
  9186. test_raw_request("GET /hi HTTP/1.1\r\n"
  9187. "a:" +
  9188. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9189. "\r\n"
  9190. "\r\n");
  9191. }
  9192. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9193. const char *rejected[] = {
  9194. // RFC 9112 §3: one SP between the parts, and nothing else
  9195. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9196. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9197. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9198. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9199. // A request-target has no fragment
  9200. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9201. // An HTTP/1.1 request needs a Host
  9202. "GET /hi HTTP/1.1\r\n\r\n",
  9203. };
  9204. for (auto request : rejected) {
  9205. std::string out;
  9206. test_raw_request(request, &out);
  9207. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9208. }
  9209. std::string out;
  9210. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9211. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9212. }
  9213. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9214. // RFC 9112 §6.1
  9215. const char *requests[] = {
  9216. "PUT /put_hi HTTP/1.1\r\n"
  9217. "Host: localhost\r\n"
  9218. "Content-Length: 0\r\n"
  9219. "Transfer-Encoding: chunked\r\n"
  9220. "\r\n"
  9221. "0\r\n\r\n",
  9222. "PUT /put_hi HTTP/1.0\r\n"
  9223. "Connection: keep-alive\r\n"
  9224. "Transfer-Encoding: chunked\r\n"
  9225. "\r\n"
  9226. "0\r\n\r\n",
  9227. };
  9228. for (auto request : requests) {
  9229. std::string out;
  9230. test_raw_request(request, &out);
  9231. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9232. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9233. }
  9234. }
  9235. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9236. std::string out;
  9237. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9238. "Content-Type: text/plain\r\n"
  9239. "Transfer-Encoding: chunked\r\n"
  9240. "\r\n"
  9241. "nothex\r\n",
  9242. &out);
  9243. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9244. }
  9245. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9246. std::string out;
  9247. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9248. "Content-Type: text/plain\r\n"
  9249. "Transfer-Encoding: chunked\r\n"
  9250. "\r\n"
  9251. "3\r\n"
  9252. "xyz\r\n"
  9253. "NaN\r\n",
  9254. &out);
  9255. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9256. }
  9257. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9258. std::string out;
  9259. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9260. "Content-Type: text/plain\r\n"
  9261. "Transfer-Encoding: chunked\r\n"
  9262. "\r\n"
  9263. // Length is too large for 64 bits.
  9264. "1ffffffffffffffff\r\n"
  9265. "xyz\r\n",
  9266. &out);
  9267. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9268. }
  9269. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9270. test_raw_request("GET /hi HTTP/1.1\r\n"
  9271. "Content-Type: text/plain\r\n\r");
  9272. }
  9273. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9274. std::string out;
  9275. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9276. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9277. }
  9278. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9279. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9280. std::string out;
  9281. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9282. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9283. }
  9284. }
  9285. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9286. std::string out;
  9287. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9288. "Host: localhost\r\n"
  9289. "Connection: close\r\n\r\n",
  9290. &out);
  9291. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9292. }
  9293. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9294. Server svr;
  9295. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9296. EXPECT_TRUE(!req.remote_addr.empty());
  9297. });
  9298. thread t = thread([&] { svr.listen(HOST, PORT); });
  9299. auto se = detail::scope_exit([&] {
  9300. svr.stop();
  9301. t.join();
  9302. ASSERT_FALSE(svr.is_running());
  9303. });
  9304. svr.wait_until_ready();
  9305. // Send an invalid request line to trigger Bad Request
  9306. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9307. std::string out;
  9308. ASSERT_TRUE(send_request(5, bad_req, &out));
  9309. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9310. }
  9311. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9312. // answered right away rather than blocking on a read that waits for EOF.
  9313. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9314. std::string out;
  9315. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9316. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9317. }
  9318. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9319. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9320. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9321. for (const auto *method : methods) {
  9322. Server svr;
  9323. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9324. EXPECT_FALSE(svr.is_valid()) << method;
  9325. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9326. }
  9327. }
  9328. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9329. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9330. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9331. for (const auto *method : methods) {
  9332. Server svr;
  9333. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9334. EXPECT_FALSE(svr.is_valid()) << method;
  9335. }
  9336. }
  9337. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9338. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9339. "COPY", "MOVE", "LOCK",
  9340. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9341. Server svr;
  9342. for (const auto *method : methods) {
  9343. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9344. }
  9345. EXPECT_TRUE(svr.is_valid());
  9346. }
  9347. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9348. Server svr;
  9349. svr.CustomRoute("POST", "/x",
  9350. [](const Request &, Response &, const ContentReader &) {});
  9351. EXPECT_FALSE(svr.is_valid());
  9352. }
  9353. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9354. Server svr;
  9355. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9356. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9357. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9358. EXPECT_FALSE(svr.is_valid());
  9359. }
  9360. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9361. Server svr;
  9362. auto captured = Error::Success;
  9363. svr.set_error_logger(
  9364. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9365. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9366. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9367. }
  9368. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9369. std::string out;
  9370. std::string request(
  9371. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9372. test_raw_request(request, &out);
  9373. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9374. }
  9375. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9376. std::string out;
  9377. std::string request(
  9378. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9379. test_raw_request(request, &out);
  9380. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9381. }
  9382. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9383. std::string out;
  9384. std::string request(
  9385. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9386. test_raw_request(request, &out);
  9387. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9388. }
  9389. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9390. std::string out;
  9391. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9392. "Host: localhost\r\n"
  9393. "Test: \r\n\r\n",
  9394. &out);
  9395. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9396. }
  9397. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9398. Server svr;
  9399. std::string x_custom;
  9400. std::string cookie;
  9401. std::string xff;
  9402. std::string x_unicode;
  9403. std::string x_iis;
  9404. svr.Get("/check", [&](const Request &req, Response &res) {
  9405. x_custom = req.get_header_value("X-Custom");
  9406. cookie = req.get_header_value("Cookie");
  9407. xff = req.get_header_value("X-Forwarded-For");
  9408. x_unicode = req.get_header_value("X-Unicode");
  9409. x_iis = req.get_header_value("X-IIS");
  9410. res.set_content("ok", "text/plain");
  9411. });
  9412. thread t = thread([&] { svr.listen(HOST, PORT); });
  9413. auto se = detail::scope_exit([&] {
  9414. svr.stop();
  9415. t.join();
  9416. ASSERT_FALSE(svr.is_running());
  9417. });
  9418. svr.wait_until_ready();
  9419. const std::string req = "GET /check HTTP/1.1\r\n"
  9420. "Host: localhost\r\n"
  9421. "X-Custom: a%0D%0AInjected: b\r\n"
  9422. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9423. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9424. "X-Unicode: %E3%81%82\r\n"
  9425. "X-IIS: %u00E9\r\n"
  9426. "Connection: close\r\n"
  9427. "\r\n";
  9428. std::string res;
  9429. ASSERT_TRUE(send_request(5, req, &res));
  9430. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9431. // Every value must be returned verbatim (wire form), with no decoding.
  9432. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9433. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9434. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9435. EXPECT_EQ("%E3%81%82", x_unicode);
  9436. EXPECT_EQ("%u00E9", x_iis);
  9437. }
  9438. // Applications that previously relied on automatic percent-decoding can
  9439. // reproduce the old behavior by explicitly calling decode_path_component()
  9440. // or, for RFC 3986 conformance, decode_uri_component().
  9441. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9442. Server svr;
  9443. std::string decoded;
  9444. svr.Get("/check", [&](const Request &req, Response &res) {
  9445. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9446. res.set_content("ok", "text/plain");
  9447. });
  9448. thread t = thread([&] { svr.listen(HOST, PORT); });
  9449. auto se = detail::scope_exit([&] {
  9450. svr.stop();
  9451. t.join();
  9452. ASSERT_FALSE(svr.is_running());
  9453. });
  9454. svr.wait_until_ready();
  9455. const std::string req = "GET /check HTTP/1.1\r\n"
  9456. "Host: localhost\r\n"
  9457. "X-Custom: hello%20world\r\n"
  9458. "Connection: close\r\n"
  9459. "\r\n";
  9460. std::string res;
  9461. ASSERT_TRUE(send_request(5, req, &res));
  9462. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9463. EXPECT_EQ("hello world", decoded);
  9464. }
  9465. // Regression test for #2033. Browsers send Referer values that include
  9466. // percent-encoded characters such as %0A inside the URL. Decoding the
  9467. // header value would either trip the post-decode CR/LF/NUL guard (the
  9468. // original bug, returning 400) or, after that guard was relaxed, silently
  9469. // store a literal LF — both unacceptable. The wire form must round-trip.
  9470. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9471. Server svr;
  9472. std::string referer;
  9473. svr.Get("/check", [&](const Request &req, Response &res) {
  9474. referer = req.get_header_value("Referer");
  9475. res.set_content("ok", "text/plain");
  9476. });
  9477. thread t = thread([&] { svr.listen(HOST, PORT); });
  9478. auto se = detail::scope_exit([&] {
  9479. svr.stop();
  9480. t.join();
  9481. ASSERT_FALSE(svr.is_running());
  9482. });
  9483. svr.wait_until_ready();
  9484. const std::string req = "GET /check HTTP/1.1\r\n"
  9485. "Host: localhost\r\n"
  9486. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9487. "Connection: close\r\n"
  9488. "\r\n";
  9489. std::string res;
  9490. ASSERT_TRUE(send_request(5, req, &res));
  9491. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9492. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9493. }
  9494. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9495. Server svr;
  9496. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9497. res.set_header("Cache-Control", "no-cache");
  9498. res.set_chunked_content_provider(
  9499. "text/event-stream", [](size_t offset, DataSink &sink) {
  9500. std::string s = "data:";
  9501. s += std::to_string(offset);
  9502. s += "\n\n";
  9503. auto ret = sink.write(s.data(), s.size());
  9504. EXPECT_TRUE(ret);
  9505. std::this_thread::sleep_for(std::chrono::seconds(1));
  9506. return true;
  9507. });
  9508. });
  9509. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9510. svr.wait_until_ready();
  9511. Client client(HOST, PORT);
  9512. const Headers headers = {{"Accept", "text/event-stream"}};
  9513. auto get_thread = std::thread([&client, &headers]() {
  9514. auto res = client.Get(
  9515. "/events", headers,
  9516. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9517. });
  9518. auto se = detail::scope_exit([&] {
  9519. svr.stop();
  9520. get_thread.join();
  9521. listen_thread.join();
  9522. ASSERT_FALSE(svr.is_running());
  9523. });
  9524. // Give GET time to get a few messages.
  9525. std::this_thread::sleep_for(std::chrono::seconds(2));
  9526. }
  9527. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9528. httplib::Server svr;
  9529. svr.Post("/hi",
  9530. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9531. res.status = StatusCode::OK_200;
  9532. });
  9533. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9534. svr.wait_until_ready();
  9535. Client cli(HOST, PORT);
  9536. auto res = cli.Post("/hi", "data", "text/plain");
  9537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9538. EXPECT_EQ(StatusCode::OK_200, res->status);
  9539. svr.stop();
  9540. thread.join();
  9541. ASSERT_FALSE(svr.is_running());
  9542. res = cli.Post("/hi", "data", "text/plain");
  9543. ASSERT_FALSE(res);
  9544. }
  9545. TEST(ServerStopTest, ListenFailure) {
  9546. Server svr;
  9547. auto t = thread([&]() {
  9548. auto ret = svr.listen("????", PORT);
  9549. EXPECT_FALSE(ret);
  9550. });
  9551. svr.wait_until_ready();
  9552. svr.stop();
  9553. t.join();
  9554. }
  9555. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9556. TEST(ServerStopTest, Decommision) {
  9557. Server svr;
  9558. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9559. for (int i = 0; i < 4; i++) {
  9560. auto is_even = !(i % 2);
  9561. std::thread t{[&] {
  9562. try {
  9563. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9564. if (is_even) {
  9565. throw std::runtime_error("Some thing that happens to go wrong.");
  9566. }
  9567. svr.listen(HOST, PORT);
  9568. } catch (...) { svr.decommission(); }
  9569. }};
  9570. svr.wait_until_ready();
  9571. // Server is up
  9572. {
  9573. Client cli(HOST, PORT);
  9574. auto res = cli.Get("/hi");
  9575. if (is_even) {
  9576. EXPECT_FALSE(res);
  9577. } else {
  9578. EXPECT_TRUE(res);
  9579. EXPECT_EQ("hi...", res->body);
  9580. }
  9581. }
  9582. svr.stop();
  9583. t.join();
  9584. // Server is down...
  9585. {
  9586. Client cli(HOST, PORT);
  9587. auto res = cli.Get("/hi");
  9588. EXPECT_FALSE(res);
  9589. }
  9590. }
  9591. }
  9592. #endif
  9593. // Helper function for string body upload progress tests
  9594. template <typename SetupHandler, typename ClientCall>
  9595. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9596. ClientCall &&client_call,
  9597. const string &body) {
  9598. Server svr;
  9599. setup_handler(svr);
  9600. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9601. auto se = detail::scope_exit([&] {
  9602. svr.stop();
  9603. t.join();
  9604. });
  9605. svr.wait_until_ready();
  9606. Client cli(HOST, PORT);
  9607. vector<uint64_t> progress_values;
  9608. bool progress_called = false;
  9609. auto res =
  9610. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9611. progress_values.push_back(current);
  9612. progress_called = true;
  9613. return true;
  9614. });
  9615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9616. EXPECT_EQ(200, res->status);
  9617. EXPECT_TRUE(progress_called);
  9618. }
  9619. TEST(UploadProgressTest, PostStringBodyBasic) {
  9620. TestStringBodyUploadProgress(
  9621. [](Server &svr) {
  9622. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9623. res.set_content("received", "text/plain");
  9624. });
  9625. },
  9626. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9627. return cli.Post("/test", body, "text/plain", progress_callback);
  9628. },
  9629. "test data for upload progress");
  9630. }
  9631. TEST(UploadProgressTest, PutStringBodyBasic) {
  9632. TestStringBodyUploadProgress(
  9633. [](Server &svr) {
  9634. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9635. res.set_content("put received", "text/plain");
  9636. });
  9637. },
  9638. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9639. return cli.Put("/test", body, "text/plain", progress_callback);
  9640. },
  9641. "put test data for upload progress");
  9642. }
  9643. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9644. TestStringBodyUploadProgress(
  9645. [](Server &svr) {
  9646. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9647. res.set_content("patch received", "text/plain");
  9648. });
  9649. },
  9650. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9651. return cli.Patch("/test", body, "text/plain", progress_callback);
  9652. },
  9653. "patch test data for upload progress");
  9654. }
  9655. // Helper function for content provider upload progress tests
  9656. template <typename SetupHandler, typename ClientCall>
  9657. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9658. ClientCall &&client_call) {
  9659. Server svr;
  9660. setup_handler(svr);
  9661. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9662. auto se = detail::scope_exit([&] {
  9663. svr.stop();
  9664. t.join();
  9665. });
  9666. svr.wait_until_ready();
  9667. Client cli(HOST, PORT);
  9668. vector<uint64_t> progress_values;
  9669. auto res =
  9670. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9671. progress_values.push_back(current);
  9672. return true;
  9673. });
  9674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9675. EXPECT_EQ(200, res->status);
  9676. EXPECT_FALSE(progress_values.empty());
  9677. }
  9678. TEST(UploadProgressTest, PostContentProviderProgress) {
  9679. TestContentProviderUploadProgress(
  9680. [](Server &svr) {
  9681. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9682. res.set_content("provider received", "text/plain");
  9683. });
  9684. },
  9685. [](Client &cli, UploadProgress progress_callback) {
  9686. return cli.Post(
  9687. "/test", 10,
  9688. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9689. sink.os << "test data";
  9690. return true;
  9691. },
  9692. "text/plain", progress_callback);
  9693. });
  9694. }
  9695. // Helper function for multipart upload progress tests
  9696. template <typename SetupHandler, typename ClientCall>
  9697. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9698. ClientCall &&client_call,
  9699. const string &endpoint) {
  9700. Server svr;
  9701. setup_handler(svr);
  9702. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9703. auto se = detail::scope_exit([&] {
  9704. svr.stop();
  9705. t.join();
  9706. });
  9707. svr.wait_until_ready();
  9708. Client cli(HOST, PORT);
  9709. vector<uint64_t> progress_values;
  9710. UploadFormDataItems items = {
  9711. {"field1", "value1", "", ""},
  9712. {"field2", "longer value for progress tracking test", "", ""},
  9713. {"file1", "file content data for upload progress", "test.txt",
  9714. "text/plain"}};
  9715. auto res = client_call(cli, endpoint, items,
  9716. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9717. progress_values.push_back(current);
  9718. return true;
  9719. });
  9720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9721. EXPECT_EQ(200, res->status);
  9722. EXPECT_FALSE(progress_values.empty());
  9723. }
  9724. TEST(UploadProgressTest, PostMultipartProgress) {
  9725. TestMultipartUploadProgress(
  9726. [](Server &svr) {
  9727. svr.Post("/multipart", [](const Request &req, Response &res) {
  9728. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9729. res.set_content("multipart received", "text/plain");
  9730. });
  9731. },
  9732. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9733. UploadProgress progress_callback) {
  9734. return cli.Post(endpoint, items, progress_callback);
  9735. },
  9736. "/multipart");
  9737. }
  9738. // Helper function for basic download progress tests
  9739. template <typename SetupHandler, typename ClientCall>
  9740. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9741. ClientCall &&client_call, const string &endpoint,
  9742. size_t expected_content_size) {
  9743. Server svr;
  9744. setup_handler(svr);
  9745. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9746. auto se = detail::scope_exit([&] {
  9747. svr.stop();
  9748. t.join();
  9749. });
  9750. svr.wait_until_ready();
  9751. Client cli(HOST, PORT);
  9752. vector<uint64_t> progress_values;
  9753. auto res = client_call(cli, endpoint,
  9754. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9755. progress_values.push_back(current);
  9756. return true;
  9757. });
  9758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9759. EXPECT_EQ(200, res->status);
  9760. EXPECT_FALSE(progress_values.empty());
  9761. EXPECT_EQ(expected_content_size, res->body.size());
  9762. }
  9763. TEST(DownloadProgressTest, GetBasic) {
  9764. TestBasicDownloadProgress(
  9765. [](Server &svr) {
  9766. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9767. string content(1000, 'D');
  9768. res.set_content(content, "text/plain");
  9769. });
  9770. },
  9771. [](Client &cli, const string &endpoint,
  9772. DownloadProgress progress_callback) {
  9773. return cli.Get(endpoint, progress_callback);
  9774. },
  9775. "/download", 1000u);
  9776. }
  9777. // Helper function for content receiver download progress tests
  9778. template <typename SetupHandler, typename ClientCall>
  9779. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9780. ClientCall &&client_call,
  9781. const string &endpoint,
  9782. size_t expected_content_size) {
  9783. Server svr;
  9784. setup_handler(svr);
  9785. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9786. auto se = detail::scope_exit([&] {
  9787. svr.stop();
  9788. t.join();
  9789. });
  9790. svr.wait_until_ready();
  9791. Client cli(HOST, PORT);
  9792. vector<uint64_t> progress_values;
  9793. string received_body;
  9794. auto res = client_call(
  9795. cli, endpoint,
  9796. [&](const char *data, size_t data_length) -> bool {
  9797. received_body.append(data, data_length);
  9798. return true;
  9799. },
  9800. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9801. progress_values.push_back(current);
  9802. return true;
  9803. });
  9804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9805. EXPECT_EQ(200, res->status);
  9806. EXPECT_FALSE(progress_values.empty());
  9807. EXPECT_EQ(expected_content_size, received_body.size());
  9808. EXPECT_TRUE(res->body.empty());
  9809. }
  9810. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9811. TestContentReceiverDownloadProgress(
  9812. [](Server &svr) {
  9813. svr.Get("/download-receiver",
  9814. [](const Request & /*req*/, Response &res) {
  9815. string content(2000, 'R');
  9816. res.set_content(content, "text/plain");
  9817. });
  9818. },
  9819. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9820. DownloadProgress progress_callback) {
  9821. return cli.Get(endpoint, content_receiver, progress_callback);
  9822. },
  9823. "/download-receiver", 2000u);
  9824. }
  9825. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9826. // A provider reaching a pass with nothing to hand over - an empty buffer
  9827. // popped off a queue, say - must not be taken to mean the body is finished.
  9828. // It used to end the loop with the terminating chunk unwritten while the
  9829. // server still considered the response complete, so the peer waited for an
  9830. // end that never arrived.
  9831. Server svr;
  9832. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9833. auto step = std::make_shared<int>(0);
  9834. res.set_chunked_content_provider("text/plain",
  9835. [step](size_t /*offset*/, DataSink &sink) {
  9836. switch ((*step)++) {
  9837. case 0: sink.write("", 0); break;
  9838. case 1: sink.write("hello", 5); break;
  9839. default: sink.done(); break;
  9840. }
  9841. return true;
  9842. });
  9843. });
  9844. auto port = svr.bind_to_any_port(HOST);
  9845. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9846. auto listen_se = detail::scope_exit([&] {
  9847. svr.stop();
  9848. listen_thread.join();
  9849. ASSERT_FALSE(svr.is_running());
  9850. });
  9851. svr.wait_until_ready();
  9852. Client cli(HOST, port);
  9853. // Without the fix the body is never terminated, so bound the wait rather
  9854. // than letting the test hang on the default read timeout.
  9855. cli.set_read_timeout(5, 0);
  9856. auto res = cli.Get("/stream");
  9857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9858. EXPECT_EQ(StatusCode::OK_200, res->status);
  9859. EXPECT_EQ("hello", res->body);
  9860. }
  9861. TEST(StreamingTest, NoContentLengthStreaming) {
  9862. Server svr;
  9863. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9864. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9865. if (offset < 6) {
  9866. sink.os << (offset < 3 ? "a" : "b");
  9867. } else {
  9868. sink.done();
  9869. }
  9870. return true;
  9871. });
  9872. });
  9873. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9874. auto listen_se = detail::scope_exit([&] {
  9875. svr.stop();
  9876. listen_thread.join();
  9877. ASSERT_FALSE(svr.is_running());
  9878. });
  9879. svr.wait_until_ready();
  9880. Client client(HOST, PORT);
  9881. auto get_thread = std::thread([&client]() {
  9882. std::string s;
  9883. auto res =
  9884. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9885. s += std::string(data, len);
  9886. return true;
  9887. });
  9888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9889. EXPECT_EQ(StatusCode::OK_200, res->status);
  9890. EXPECT_EQ("aaabbb", s);
  9891. });
  9892. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9893. // Give GET time to get a few messages.
  9894. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9895. }
  9896. TEST(MountTest, Unmount) {
  9897. Server svr;
  9898. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9899. auto se = detail::scope_exit([&] {
  9900. svr.stop();
  9901. listen_thread.join();
  9902. ASSERT_FALSE(svr.is_running());
  9903. });
  9904. svr.wait_until_ready();
  9905. Client cli("localhost", PORT);
  9906. svr.set_mount_point("/mount2", "./www2");
  9907. auto res = cli.Get("/");
  9908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9909. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9910. res = cli.Get("/mount2/dir/test.html");
  9911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9912. EXPECT_EQ(StatusCode::OK_200, res->status);
  9913. svr.set_mount_point("/", "./www");
  9914. res = cli.Get("/dir/");
  9915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9916. EXPECT_EQ(StatusCode::OK_200, res->status);
  9917. svr.remove_mount_point("/");
  9918. res = cli.Get("/dir/");
  9919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9921. svr.remove_mount_point("/mount2");
  9922. res = cli.Get("/mount2/dir/test.html");
  9923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9924. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9925. }
  9926. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  9927. Server svr;
  9928. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  9929. svr.Get("/api/hello", [](const Request &, Response &res) {
  9930. res.set_content("api", "text/plain");
  9931. });
  9932. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9933. auto se = detail::scope_exit([&] {
  9934. svr.stop();
  9935. listen_thread.join();
  9936. ASSERT_FALSE(svr.is_running());
  9937. });
  9938. svr.wait_until_ready();
  9939. Client cli(HOST, PORT);
  9940. auto res = cli.Get("/dir/test.html");
  9941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9942. EXPECT_EQ(StatusCode::OK_200, res->status);
  9943. res = cli.Get("/api/hello");
  9944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9945. EXPECT_EQ(StatusCode::OK_200, res->status);
  9946. EXPECT_EQ("api", res->body);
  9947. }
  9948. TEST(MountTest, PathSegmentBoundary) {
  9949. Server svr;
  9950. svr.set_mount_point("/mount2", "./www2");
  9951. svr.set_mount_point("/", "./www");
  9952. auto port = svr.bind_to_any_port(HOST);
  9953. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9954. auto se = detail::scope_exit([&] {
  9955. svr.stop();
  9956. listen_thread.join();
  9957. ASSERT_FALSE(svr.is_running());
  9958. });
  9959. svr.wait_until_ready();
  9960. Client cli(HOST, port);
  9961. auto res = cli.Get("/mount2/dir/test.html");
  9962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9963. EXPECT_EQ(StatusCode::OK_200, res->status);
  9964. // "/mount2" must not match part-way through a path segment.
  9965. res = cli.Get("/mount2dir/test.html");
  9966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9967. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9968. // A mount point ending in '/' keeps matching every path below it.
  9969. res = cli.Get("/dir/test.html");
  9970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9971. EXPECT_EQ(StatusCode::OK_200, res->status);
  9972. }
  9973. TEST(MountTest, Redicect) {
  9974. Server svr;
  9975. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9976. auto se = detail::scope_exit([&] {
  9977. svr.stop();
  9978. listen_thread.join();
  9979. ASSERT_FALSE(svr.is_running());
  9980. });
  9981. svr.set_mount_point("/", "./www");
  9982. svr.wait_until_ready();
  9983. Client cli("localhost", PORT);
  9984. auto res = cli.Get("/dir/");
  9985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9986. EXPECT_EQ(StatusCode::OK_200, res->status);
  9987. res = cli.Get("/dir");
  9988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9989. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9990. res = cli.Get("/file");
  9991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9992. EXPECT_EQ(StatusCode::OK_200, res->status);
  9993. res = cli.Get("/file/");
  9994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9995. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9996. cli.set_follow_location(true);
  9997. res = cli.Get("/dir");
  9998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9999. EXPECT_EQ(StatusCode::OK_200, res->status);
  10000. }
  10001. TEST(MountTest, MultibytesPathName) {
  10002. Server svr;
  10003. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10004. auto se = detail::scope_exit([&] {
  10005. svr.stop();
  10006. listen_thread.join();
  10007. ASSERT_FALSE(svr.is_running());
  10008. });
  10009. svr.set_mount_point("/", "./www");
  10010. svr.wait_until_ready();
  10011. Client cli("localhost", PORT);
  10012. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10014. EXPECT_EQ(StatusCode::OK_200, res->status);
  10015. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10016. }
  10017. #ifdef _WIN32
  10018. // Issue #2435: mmap::open() must succeed even when another handle holds
  10019. // the file open for writing (e.g. an active log file).
  10020. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10021. const char *path = "mmap_concurrent_writer_test.txt";
  10022. const char *content = "hello";
  10023. {
  10024. std::ofstream f(path, std::ios::binary);
  10025. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10026. }
  10027. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10028. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10029. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10030. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10031. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10032. detail::mmap m(path);
  10033. ASSERT_TRUE(m.is_open());
  10034. EXPECT_EQ(strlen(content), m.size());
  10035. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  10036. }
  10037. #endif
  10038. #ifndef _WIN32
  10039. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  10040. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  10041. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  10042. TEST(MmapTest, FailedMappingIsNotOpen) {
  10043. const char *path = "./mmap_failed_mapping_test_dir";
  10044. ASSERT_EQ(0, ::mkdir(path, 0755));
  10045. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10046. detail::mmap m(path);
  10047. EXPECT_FALSE(m.is_open());
  10048. EXPECT_EQ(0U, m.size());
  10049. EXPECT_NE(static_cast<const void *>(m.data()),
  10050. static_cast<const void *>(MAP_FAILED));
  10051. }
  10052. #endif
  10053. TEST(KeepAliveTest, ReadTimeout) {
  10054. Server svr;
  10055. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10056. std::this_thread::sleep_for(std::chrono::seconds(2));
  10057. res.set_content("a", "text/plain");
  10058. });
  10059. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10060. res.set_content("b", "text/plain");
  10061. });
  10062. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10063. auto se = detail::scope_exit([&] {
  10064. svr.stop();
  10065. listen_thread.join();
  10066. ASSERT_FALSE(svr.is_running());
  10067. });
  10068. svr.wait_until_ready();
  10069. Client cli("localhost", PORT);
  10070. cli.set_keep_alive(true);
  10071. cli.set_read_timeout(std::chrono::seconds(1));
  10072. auto resa = cli.Get("/a");
  10073. ASSERT_FALSE(resa);
  10074. EXPECT_EQ(Error::Read, resa.error());
  10075. auto resb = cli.Get("/b");
  10076. ASSERT_TRUE(resb);
  10077. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10078. EXPECT_EQ("b", resb->body);
  10079. }
  10080. TEST(KeepAliveTest, MaxCount) {
  10081. size_t keep_alive_max_count = 3;
  10082. Server svr;
  10083. svr.set_keep_alive_max_count(keep_alive_max_count);
  10084. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10085. res.set_content("Hello World!", "text/plain");
  10086. });
  10087. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10088. auto se = detail::scope_exit([&] {
  10089. svr.stop();
  10090. listen_thread.join();
  10091. ASSERT_FALSE(svr.is_running());
  10092. });
  10093. svr.wait_until_ready();
  10094. Client cli(HOST, PORT);
  10095. cli.set_keep_alive(true);
  10096. for (size_t i = 0; i < 5; i++) {
  10097. auto result = cli.Get("/hi");
  10098. ASSERT_TRUE(result);
  10099. EXPECT_EQ(StatusCode::OK_200, result->status);
  10100. if (i == keep_alive_max_count - 1) {
  10101. EXPECT_EQ("close", result->get_header_value("Connection"));
  10102. } else {
  10103. EXPECT_FALSE(result->has_header("Connection"));
  10104. }
  10105. }
  10106. }
  10107. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10108. // can pull the next one into the server's buffer. The server must serve it
  10109. // without waiting for the socket to become readable again. The keep-alive
  10110. // timeout outlasts the client's read timeout, so a request left waiting for it
  10111. // shows up as a missing response.
  10112. static void serve_pipelining_routes(Server &svr,
  10113. const std::function<void(int)> &client) {
  10114. svr.set_keep_alive_timeout(5);
  10115. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10116. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10117. });
  10118. svr.Post("/echo", [](const Request &req, Response &res) {
  10119. res.set_content("echo " + req.body, "text/plain");
  10120. });
  10121. auto port = svr.bind_to_any_port(HOST);
  10122. thread t = thread([&] { svr.listen_after_bind(); });
  10123. auto se = detail::scope_exit([&] {
  10124. svr.stop();
  10125. t.join();
  10126. });
  10127. svr.wait_until_ready();
  10128. client(port);
  10129. }
  10130. static std::string
  10131. send_pipelined_requests(const std::vector<std::string> &parts) {
  10132. Server svr;
  10133. std::string res;
  10134. serve_pipelining_routes(svr, [&](int port) {
  10135. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10136. });
  10137. return res;
  10138. }
  10139. static void expect_in_order(const std::string &res,
  10140. const std::vector<std::string> &bodies) {
  10141. size_t pos = 0;
  10142. for (const auto &body : bodies) {
  10143. pos = res.find(body, pos);
  10144. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10145. pos += body.size();
  10146. }
  10147. }
  10148. TEST(KeepAliveTest, PipelinedRequests) {
  10149. auto res = send_pipelined_requests(
  10150. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10151. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10152. "Content-Length: 4\r\n\r\nbody"
  10153. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10154. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10155. }
  10156. // The second request starts in the server's buffer and ends on the socket.
  10157. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10158. auto res =
  10159. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10160. "GET /hi/2 HTTP/1.1\r\nHo",
  10161. "st: localhost\r\nConnection: close\r\n\r\n"});
  10162. expect_in_order(res, {"hi 1", "hi 2"});
  10163. }
  10164. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10165. // CRLF after a body does not turn into a 400 for the next request.
  10166. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10167. auto res = send_pipelined_requests(
  10168. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10169. "Content-Length: 4\r\n\r\nbody\r\n"
  10170. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10171. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10172. expect_in_order(res, {"echo body", "hi 2"});
  10173. }
  10174. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10175. // must not be served as the next request.
  10176. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10177. auto res = send_pipelined_requests(
  10178. {"INVALID REQUEST LINE\r\n\r\n"
  10179. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10180. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10181. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10182. }
  10183. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10184. // Over TLS, the next request is held by the TLS library as already decrypted
  10185. // data rather than on the socket.
  10186. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10187. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10188. std::string res;
  10189. serve_pipelining_routes(svr, [&](int port) {
  10190. auto error = Error::Success;
  10191. auto sock = detail::create_client_socket(
  10192. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10193. /*connection_timeout_sec=*/5, 0,
  10194. /*read_timeout_sec=*/2, 0,
  10195. /*write_timeout_sec=*/5, 0, std::string(), error);
  10196. ASSERT_NE(INVALID_SOCKET, sock);
  10197. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10198. auto ctx = SSL_CTX_new(TLS_client_method());
  10199. auto ssl = SSL_new(ctx);
  10200. auto ssl_se = detail::scope_exit([&] {
  10201. SSL_free(ssl);
  10202. SSL_CTX_free(ctx);
  10203. });
  10204. SSL_set_fd(ssl, static_cast<int>(sock));
  10205. ASSERT_EQ(1, SSL_connect(ssl));
  10206. // One write, so all three requests arrive in one TLS record
  10207. const std::string req =
  10208. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10209. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10210. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10211. ASSERT_EQ(static_cast<int>(req.size()),
  10212. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10213. char buf[512];
  10214. int n;
  10215. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10216. res.append(buf, static_cast<size_t>(n));
  10217. }
  10218. });
  10219. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10220. }
  10221. #endif
  10222. TEST(KeepAliveTest, Issue1041) {
  10223. Server svr;
  10224. svr.set_keep_alive_timeout(3);
  10225. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10226. res.set_content("Hello World!", "text/plain");
  10227. });
  10228. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10229. auto se = detail::scope_exit([&] {
  10230. svr.stop();
  10231. listen_thread.join();
  10232. ASSERT_FALSE(svr.is_running());
  10233. });
  10234. svr.wait_until_ready();
  10235. Client cli(HOST, PORT);
  10236. cli.set_keep_alive(true);
  10237. auto result = cli.Get("/hi");
  10238. ASSERT_TRUE(result);
  10239. EXPECT_EQ(StatusCode::OK_200, result->status);
  10240. std::this_thread::sleep_for(std::chrono::seconds(5));
  10241. result = cli.Get("/hi");
  10242. ASSERT_TRUE(result);
  10243. EXPECT_EQ(StatusCode::OK_200, result->status);
  10244. }
  10245. TEST(KeepAliveTest, Issue1959) {
  10246. Server svr;
  10247. svr.set_keep_alive_timeout(5);
  10248. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10249. res.set_content("a", "text/plain");
  10250. });
  10251. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10252. auto se = detail::scope_exit([&] {
  10253. if (!svr.is_running()) return;
  10254. svr.stop();
  10255. listen_thread.join();
  10256. ASSERT_FALSE(svr.is_running());
  10257. });
  10258. svr.wait_until_ready();
  10259. Client cli("localhost", PORT);
  10260. cli.set_keep_alive(true);
  10261. using namespace std::chrono;
  10262. auto start = steady_clock::now();
  10263. cli.Get("/a");
  10264. svr.stop();
  10265. listen_thread.join();
  10266. auto end = steady_clock::now();
  10267. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10268. EXPECT_LT(elapsed, 5000);
  10269. }
  10270. #ifdef CPPHTTPLIB_SSL_ENABLED
  10271. TEST(KeepAliveTest, SSLClientReconnection) {
  10272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10273. ASSERT_TRUE(svr.is_valid());
  10274. svr.set_keep_alive_timeout(1);
  10275. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10276. res.set_content("Hello World!", "text/plain");
  10277. });
  10278. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10279. auto se = detail::scope_exit([&] {
  10280. svr.stop();
  10281. listen_thread.join();
  10282. ASSERT_FALSE(svr.is_running());
  10283. });
  10284. svr.wait_until_ready();
  10285. SSLClient cli(HOST, PORT);
  10286. cli.enable_server_certificate_verification(false);
  10287. cli.set_keep_alive(true);
  10288. auto result = cli.Get("/hi");
  10289. ASSERT_TRUE(result);
  10290. EXPECT_EQ(StatusCode::OK_200, result->status);
  10291. result = cli.Get("/hi");
  10292. ASSERT_TRUE(result);
  10293. EXPECT_EQ(StatusCode::OK_200, result->status);
  10294. std::this_thread::sleep_for(std::chrono::seconds(2));
  10295. // Recoonect
  10296. result = cli.Get("/hi");
  10297. ASSERT_TRUE(result);
  10298. EXPECT_EQ(StatusCode::OK_200, result->status);
  10299. result = cli.Get("/hi");
  10300. ASSERT_TRUE(result);
  10301. EXPECT_EQ(StatusCode::OK_200, result->status);
  10302. }
  10303. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10305. ASSERT_TRUE(svr.is_valid());
  10306. svr.set_keep_alive_timeout(1);
  10307. std::string content = "reconnect";
  10308. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10309. res.set_content("Hello World!", "text/plain");
  10310. });
  10311. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10312. auto se = detail::scope_exit([&] {
  10313. svr.stop();
  10314. listen_thread.join();
  10315. ASSERT_FALSE(svr.is_running());
  10316. });
  10317. svr.wait_until_ready();
  10318. SSLClient cli(HOST, PORT);
  10319. cli.enable_server_certificate_verification(false);
  10320. cli.set_keep_alive(true);
  10321. auto result = cli.Post(
  10322. "/hi", content.size(),
  10323. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10324. sink.write(content.c_str(), content.size());
  10325. return true;
  10326. },
  10327. "text/plain");
  10328. ASSERT_TRUE(result);
  10329. EXPECT_EQ(200, result->status);
  10330. std::this_thread::sleep_for(std::chrono::seconds(2));
  10331. // Recoonect
  10332. result = cli.Post(
  10333. "/hi", content.size(),
  10334. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10335. sink.write(content.c_str(), content.size());
  10336. return true;
  10337. },
  10338. "text/plain");
  10339. ASSERT_TRUE(result);
  10340. EXPECT_EQ(200, result->status);
  10341. result = cli.Post(
  10342. "/hi", content.size(),
  10343. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10344. sink.write(content.c_str(), content.size());
  10345. return true;
  10346. },
  10347. "text/plain");
  10348. ASSERT_TRUE(result);
  10349. EXPECT_EQ(200, result->status);
  10350. }
  10351. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10352. using namespace httplib::tls;
  10353. {
  10354. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10355. ASSERT_TRUE(svr.is_valid());
  10356. svr.Get("/sni", [&](const Request &req, Response &res) {
  10357. std::string expected = req.sni();
  10358. EXPECT_EQ(expected, req.get_param_value("expected"));
  10359. res.set_content("ok", "text/plain");
  10360. });
  10361. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10362. auto se = detail::scope_exit([&] {
  10363. svr.stop();
  10364. listen_thread.join();
  10365. ASSERT_FALSE(svr.is_running());
  10366. });
  10367. svr.wait_until_ready();
  10368. {
  10369. SSLClient cli("localhost", PORT);
  10370. cli.enable_server_certificate_verification(false);
  10371. auto res = cli.Get("/sni?expected=localhost");
  10372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10373. }
  10374. {
  10375. SSLClient cli("::1", PORT);
  10376. cli.enable_server_certificate_verification(false);
  10377. auto res = cli.Get("/sni?expected=");
  10378. // NOTE: This may fail if the server is listening on IPv4 only
  10379. // (e.g., when localhost resolves to 127.0.0.1 only)
  10380. if (res) {
  10381. EXPECT_EQ(StatusCode::OK_200, res->status);
  10382. } else {
  10383. EXPECT_EQ(Error::Connection, res.error());
  10384. }
  10385. }
  10386. }
  10387. }
  10388. #endif
  10389. TEST(ClientProblemDetectionTest, ContentProvider) {
  10390. Server svr;
  10391. size_t content_length = 1024 * 1024;
  10392. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10393. res.set_content_provider(
  10394. content_length, "text/plain",
  10395. [&](size_t offset, size_t length, DataSink &sink) {
  10396. auto out_len = std::min(length, static_cast<size_t>(1024));
  10397. std::string out(out_len, '@');
  10398. sink.write(out.data(), out_len);
  10399. return offset < 4096;
  10400. },
  10401. [](bool success) { ASSERT_FALSE(success); });
  10402. });
  10403. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10404. res.set_content_provider(
  10405. 0, "text/plain",
  10406. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10407. EXPECT_TRUE(false);
  10408. return true;
  10409. },
  10410. [](bool success) { ASSERT_FALSE(success); });
  10411. });
  10412. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10413. auto se = detail::scope_exit([&] {
  10414. svr.stop();
  10415. listen_thread.join();
  10416. ASSERT_FALSE(svr.is_running());
  10417. });
  10418. svr.wait_until_ready();
  10419. Client cli("localhost", PORT);
  10420. {
  10421. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10422. size_t /*data_length*/) { return false; });
  10423. ASSERT_FALSE(res);
  10424. }
  10425. {
  10426. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10427. size_t /*data_length*/) { return false; });
  10428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10429. }
  10430. }
  10431. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10432. // A provider that reports success without writing anything and without
  10433. // calling done() used to be handed the same offset and length again on every
  10434. // pass, so it spun for as long as the peer stayed connected.
  10435. Server svr;
  10436. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10437. res.set_content("ok", "text/plain");
  10438. });
  10439. auto port = svr.bind_to_any_port(HOST);
  10440. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10441. auto se = detail::scope_exit([&] {
  10442. svr.stop();
  10443. listen_thread.join();
  10444. ASSERT_FALSE(svr.is_running());
  10445. });
  10446. svr.wait_until_ready();
  10447. std::atomic<int> call_count{0};
  10448. Client cli(HOST, port);
  10449. auto res = cli.Post(
  10450. "/", 1024,
  10451. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10452. // Give up after enough passes to show the spin, so that losing the
  10453. // check below fails this test instead of hanging it.
  10454. return ++call_count < 100;
  10455. },
  10456. "text/plain");
  10457. ASSERT_FALSE(res);
  10458. EXPECT_EQ(Error::Write, res.error());
  10459. EXPECT_EQ(1, call_count.load());
  10460. }
  10461. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10462. // A writer only has to assign `write`. The other three used to be left as
  10463. // empty std::functions, so a provider calling one threw
  10464. // std::bad_function_call out of the thread running it and took the whole
  10465. // process down.
  10466. DataSink sink;
  10467. std::string written;
  10468. sink.write = [&](const char *data, size_t data_len) {
  10469. written.append(data, data_len);
  10470. return true;
  10471. };
  10472. EXPECT_TRUE(sink.is_writable());
  10473. sink.done();
  10474. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10475. EXPECT_TRUE(written.empty());
  10476. }
  10477. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10478. // A sink that cannot carry trailers still has to finish.
  10479. DataSink sink;
  10480. auto done_count = 0;
  10481. sink.done = [&]() { done_count++; };
  10482. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10483. EXPECT_EQ(1, done_count);
  10484. }
  10485. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10486. Server svr;
  10487. const std::string body(4096, 'x');
  10488. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10489. res.set_content_provider(body.size(), "text/plain",
  10490. [&](size_t offset, size_t length, DataSink &sink) {
  10491. sink.write(body.data() + offset, length);
  10492. sink.done();
  10493. return true;
  10494. });
  10495. });
  10496. auto port = svr.bind_to_any_port(HOST);
  10497. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10498. auto se = detail::scope_exit([&] {
  10499. svr.stop();
  10500. listen_thread.join();
  10501. ASSERT_FALSE(svr.is_running());
  10502. });
  10503. svr.wait_until_ready();
  10504. Client cli(HOST, port);
  10505. auto res = cli.Get("/");
  10506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10507. EXPECT_EQ(StatusCode::OK_200, res->status);
  10508. EXPECT_EQ(body, res->body);
  10509. }
  10510. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10511. Server svr;
  10512. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10513. res.set_content_provider(
  10514. 1024, "text/plain",
  10515. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10516. sink.write("hello", 5);
  10517. sink.done(); // short of the 1024 bytes the response promised
  10518. return true;
  10519. });
  10520. });
  10521. auto port = svr.bind_to_any_port(HOST);
  10522. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10523. auto se = detail::scope_exit([&] {
  10524. svr.stop();
  10525. listen_thread.join();
  10526. ASSERT_FALSE(svr.is_running());
  10527. });
  10528. svr.wait_until_ready();
  10529. Client cli(HOST, port);
  10530. cli.set_read_timeout(5, 0);
  10531. // The response is short of its Content-Length, so the client cannot read a
  10532. // complete body. What matters is that this returns at all: a no-op done()
  10533. // would leave the writer looping over a provider that never makes progress.
  10534. auto res = cli.Get("/");
  10535. EXPECT_FALSE(res);
  10536. }
  10537. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10538. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10539. // The compressed path builds the whole body before connecting, so this
  10540. // fails client-side and never reaches a server.
  10541. Client cli(HOST, PORT);
  10542. cli.set_compress(true);
  10543. auto res = cli.Post(
  10544. "/", 1024,
  10545. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10546. sink.write("hello", 5);
  10547. sink.done(); // short of the 1024 bytes the request announced
  10548. return true;
  10549. },
  10550. "text/plain");
  10551. ASSERT_FALSE(res);
  10552. EXPECT_EQ(Error::Write, res.error());
  10553. }
  10554. #endif
  10555. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10556. Server svr;
  10557. svr.set_error_handler([](Request const &, Response &res) -> void {
  10558. res.set_chunked_content_provider(
  10559. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10560. sink.os << "hello";
  10561. sink.os << "world";
  10562. sink.done();
  10563. return true;
  10564. });
  10565. });
  10566. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10567. auto se = detail::scope_exit([&] {
  10568. svr.stop();
  10569. listen_thread.join();
  10570. ASSERT_FALSE(svr.is_running());
  10571. });
  10572. svr.wait_until_ready();
  10573. Client cli("localhost", PORT);
  10574. auto res = cli.Get("/");
  10575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10576. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10577. EXPECT_EQ("helloworld", res->body);
  10578. }
  10579. // A body set after a content provider must replace it, not be sent through it.
  10580. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10581. Server svr;
  10582. svr.set_mount_point("/", "./www");
  10583. svr.set_file_request_handler([](const Request &req, Response &res) {
  10584. if (req.path == "/dir/test.html") {
  10585. res.status = StatusCode::Forbidden_403;
  10586. res.set_content(std::string(5000, 'D'), "text/plain");
  10587. } else if (req.path == "/file") {
  10588. res.status = StatusCode::Forbidden_403;
  10589. res.body = "Denied";
  10590. }
  10591. });
  10592. auto port = svr.bind_to_any_port(HOST);
  10593. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10594. auto se = detail::scope_exit([&] {
  10595. svr.stop();
  10596. t.join();
  10597. ASSERT_FALSE(svr.is_running());
  10598. });
  10599. svr.wait_until_ready();
  10600. Client cli(HOST, port);
  10601. {
  10602. auto res = cli.Get("/dir/test.html");
  10603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10604. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10605. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10606. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10607. }
  10608. {
  10609. auto res = cli.Get("/file");
  10610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10611. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10612. EXPECT_EQ("Denied", res->body);
  10613. }
  10614. {
  10615. auto res = cli.Get("/dir/index.html");
  10616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10617. EXPECT_EQ(StatusCode::OK_200, res->status);
  10618. EXPECT_EQ(0U, res->body.find("<html>"));
  10619. }
  10620. }
  10621. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10622. Server svr;
  10623. std::vector<bool> released;
  10624. std::mutex released_mutex;
  10625. auto releaser = [&](bool success) {
  10626. std::lock_guard<std::mutex> guard(released_mutex);
  10627. released.push_back(success);
  10628. };
  10629. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10630. return sink.write(&"hello"[offset], length);
  10631. };
  10632. svr.Get("/sized", [&](const Request &, Response &res) {
  10633. res.status = StatusCode::NotFound_404;
  10634. res.set_content_provider(5, "text/plain", provider, releaser);
  10635. });
  10636. svr.Get("/chunked", [&](const Request &, Response &res) {
  10637. res.status = StatusCode::ServiceUnavailable_503;
  10638. res.set_chunked_content_provider(
  10639. "text/plain",
  10640. [](size_t, DataSink &sink) {
  10641. sink.os << "chunk";
  10642. sink.done();
  10643. return true;
  10644. },
  10645. releaser);
  10646. });
  10647. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10648. res.set_content_provider(5, "text/plain", provider, releaser);
  10649. throw std::runtime_error("after the provider");
  10650. });
  10651. svr.set_error_handler([](const Request &req, Response &res) {
  10652. // Leave the exception handler's content to it.
  10653. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10654. res.set_content(std::string(1000, 'E'), "text/html");
  10655. return Server::HandlerResponse::Handled;
  10656. });
  10657. svr.set_exception_handler(
  10658. [](const Request &, Response &res, std::exception_ptr) {
  10659. res.status = StatusCode::InternalServerError_500;
  10660. res.set_content(std::string(1000, 'X'), "text/html");
  10661. });
  10662. auto port = svr.bind_to_any_port(HOST);
  10663. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10664. auto se = detail::scope_exit([&] {
  10665. svr.stop();
  10666. t.join();
  10667. ASSERT_FALSE(svr.is_running());
  10668. });
  10669. svr.wait_until_ready();
  10670. Client cli(HOST, port);
  10671. {
  10672. auto res = cli.Get("/sized");
  10673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10674. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10675. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10676. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10677. }
  10678. {
  10679. auto res = cli.Get("/chunked");
  10680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10681. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10682. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10683. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10684. }
  10685. {
  10686. auto res = cli.Get("/throw");
  10687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10688. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10689. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10690. }
  10691. std::lock_guard<std::mutex> guard(released_mutex);
  10692. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10693. }
  10694. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10695. Server svr;
  10696. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10697. return sink.write(&"abc"[offset], length);
  10698. };
  10699. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10700. res.set_file_content("./www/dir/test.html");
  10701. res.set_content("body", "text/plain");
  10702. });
  10703. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10704. res.set_content(std::string(100, 'B'), "text/plain");
  10705. res.set_file_content("./www/dir/test.html");
  10706. });
  10707. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10708. res.set_content(std::string(100, 'B'), "text/plain");
  10709. res.set_content_provider(3, "text/plain", abc);
  10710. });
  10711. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10712. res.set_content_provider(3, "text/plain", abc);
  10713. res.set_content(std::string(100, 'B'), "text/plain");
  10714. });
  10715. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10716. res.set_content_provider(3, "text/plain", abc);
  10717. res.body = "direct";
  10718. });
  10719. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10720. res.set_file_content("./www/dir/test.html");
  10721. res.body = "direct";
  10722. });
  10723. auto port = svr.bind_to_any_port(HOST);
  10724. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10725. auto se = detail::scope_exit([&] {
  10726. svr.stop();
  10727. t.join();
  10728. ASSERT_FALSE(svr.is_running());
  10729. });
  10730. svr.wait_until_ready();
  10731. Client cli(HOST, port);
  10732. auto expect_body = [&](const char *path, const std::string &body) {
  10733. // Uncompressed, so Content-Length can be compared with the body.
  10734. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10735. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10736. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10737. EXPECT_EQ(body, res->body) << path;
  10738. EXPECT_EQ(std::to_string(body.size()),
  10739. res->get_header_value("Content-Length"))
  10740. << path;
  10741. };
  10742. expect_body("/file-then-body", "body");
  10743. expect_body("/body-then-file", "test.html");
  10744. expect_body("/body-then-provider", "abc");
  10745. expect_body("/provider-then-body", std::string(100, 'B'));
  10746. expect_body("/provider-then-direct-body", "direct");
  10747. expect_body("/file-then-direct-body", "direct");
  10748. // Ranges are checked against the body, not the dropped provider.
  10749. {
  10750. auto res = cli.Get("/provider-then-direct-body",
  10751. Headers{{make_range_header({{1, 2}})}});
  10752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10753. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10754. EXPECT_EQ("ir", res->body);
  10755. }
  10756. {
  10757. auto res = cli.Get("/file-then-direct-body",
  10758. Headers{{make_range_header({{7, 8}})}});
  10759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10760. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10761. }
  10762. }
  10763. // Forward declaration (see the base64_encode note).
  10764. namespace httplib {
  10765. namespace detail {
  10766. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10767. const std::string &content_type,
  10768. EncodingType encoding);
  10769. } // namespace detail
  10770. } // namespace httplib
  10771. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10772. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10773. ASSERT_TRUE(mm->is_open());
  10774. Response res;
  10775. detail::set_file_content_provider(res, mm, "text/html",
  10776. detail::EncodingType::None);
  10777. std::string out;
  10778. DataSink sink;
  10779. sink.write = [&](const char *d, size_t l) {
  10780. out.append(d, l);
  10781. return true;
  10782. };
  10783. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10784. EXPECT_EQ("test.html", out);
  10785. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10786. EXPECT_EQ("test.html", out);
  10787. }
  10788. TEST(LongPollingTest, ClientCloseDetection) {
  10789. Server svr;
  10790. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10791. res.set_chunked_content_provider(
  10792. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10793. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10794. sink.os << "hello";
  10795. auto count = 10;
  10796. while (count > 0 && sink.is_writable()) {
  10797. this_thread::sleep_for(chrono::milliseconds(10));
  10798. count--;
  10799. }
  10800. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10801. return true;
  10802. });
  10803. });
  10804. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10805. auto se = detail::scope_exit([&] {
  10806. svr.stop();
  10807. listen_thread.join();
  10808. ASSERT_FALSE(svr.is_running());
  10809. });
  10810. svr.wait_until_ready();
  10811. Client cli("localhost", PORT);
  10812. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10813. EXPECT_EQ("hello", string(data, data_length));
  10814. return false; // close the socket immediately.
  10815. });
  10816. ASSERT_FALSE(res);
  10817. }
  10818. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10819. Server svr;
  10820. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10821. res.set_chunked_content_provider(
  10822. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10823. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10824. sink.os << "hello";
  10825. EXPECT_TRUE(sink.os.good());
  10826. // Wait for the client to close the connection
  10827. auto count = 10;
  10828. while (count > 0 && sink.is_writable()) {
  10829. this_thread::sleep_for(chrono::milliseconds(10));
  10830. count--;
  10831. }
  10832. // After client disconnect, write repeatedly until the socket
  10833. // write actually fails (small writes may be absorbed by the
  10834. // kernel buffer)
  10835. std::string chunk(1024, 'x');
  10836. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10837. sink.os << chunk;
  10838. }
  10839. EXPECT_TRUE(sink.os.fail());
  10840. return true;
  10841. });
  10842. });
  10843. auto port = svr.bind_to_any_port("localhost");
  10844. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10845. auto se = detail::scope_exit([&] {
  10846. svr.stop();
  10847. listen_thread.join();
  10848. ASSERT_FALSE(svr.is_running());
  10849. });
  10850. svr.wait_until_ready();
  10851. Client cli("localhost", port);
  10852. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10853. EXPECT_EQ("hello", string(data, data_length));
  10854. return false; // close the socket immediately.
  10855. });
  10856. ASSERT_FALSE(res);
  10857. }
  10858. TEST(GetWithParametersTest, GetWithParameters) {
  10859. Server svr;
  10860. svr.Get("/", [&](const Request &req, Response &) {
  10861. EXPECT_EQ("world", req.get_param_value("hello"));
  10862. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10863. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10864. });
  10865. svr.Get("/params", [&](const Request &req, Response &) {
  10866. EXPECT_EQ("world", req.get_param_value("hello"));
  10867. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10868. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10869. });
  10870. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10871. EXPECT_EQ("resource-id", req.matches[1]);
  10872. EXPECT_EQ("foo", req.get_param_value("param1"));
  10873. EXPECT_EQ("bar", req.get_param_value("param2"));
  10874. });
  10875. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10876. EXPECT_EQ("user-id", req.path_params.at("id"));
  10877. EXPECT_EQ("foo", req.get_param_value("param1"));
  10878. EXPECT_EQ("bar", req.get_param_value("param2"));
  10879. });
  10880. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10881. auto se = detail::scope_exit([&] {
  10882. svr.stop();
  10883. listen_thread.join();
  10884. ASSERT_FALSE(svr.is_running());
  10885. });
  10886. svr.wait_until_ready();
  10887. {
  10888. Client cli(HOST, PORT);
  10889. Params params;
  10890. params.emplace("hello", "world");
  10891. params.emplace("hello2", "world2");
  10892. params.emplace("hello3", "world3");
  10893. auto res = cli.Get("/", params, Headers{});
  10894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10895. EXPECT_EQ(StatusCode::OK_200, res->status);
  10896. }
  10897. {
  10898. Client cli(HOST, PORT);
  10899. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10901. EXPECT_EQ(StatusCode::OK_200, res->status);
  10902. }
  10903. {
  10904. Client cli(HOST, PORT);
  10905. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10907. EXPECT_EQ(StatusCode::OK_200, res->status);
  10908. }
  10909. {
  10910. Client cli(HOST, PORT);
  10911. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10913. EXPECT_EQ(StatusCode::OK_200, res->status);
  10914. }
  10915. }
  10916. TEST(GetWithParametersTest, GetWithParameters2) {
  10917. Server svr;
  10918. svr.Get("/", [&](const Request &req, Response &res) {
  10919. auto text = req.get_param_value("hello");
  10920. res.set_content(text, "text/plain");
  10921. });
  10922. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10923. auto se = detail::scope_exit([&] {
  10924. svr.stop();
  10925. listen_thread.join();
  10926. ASSERT_FALSE(svr.is_running());
  10927. });
  10928. svr.wait_until_ready();
  10929. Client cli("localhost", PORT);
  10930. Params params;
  10931. params.emplace("hello", "world");
  10932. std::string body;
  10933. auto res = cli.Get("/", params, Headers{},
  10934. [&](const char *data, size_t data_length) {
  10935. body.append(data, data_length);
  10936. return true;
  10937. });
  10938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10939. EXPECT_EQ(StatusCode::OK_200, res->status);
  10940. EXPECT_EQ("world", body);
  10941. }
  10942. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10943. Server svr;
  10944. svr.Get("/search", [&](const Request &req, Response &res) {
  10945. auto q = req.get_param_value("q");
  10946. res.set_content(q, "text/plain");
  10947. });
  10948. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10949. auto se = detail::scope_exit([&] {
  10950. svr.stop();
  10951. listen_thread.join();
  10952. ASSERT_FALSE(svr.is_running());
  10953. });
  10954. svr.wait_until_ready();
  10955. Client cli("localhost", PORT);
  10956. // Verify that Get(path, params) works without requiring Headers argument
  10957. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10959. EXPECT_EQ(StatusCode::OK_200, res->status);
  10960. EXPECT_EQ("cpp-httplib", res->body);
  10961. }
  10962. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10963. auto host = "httpbingo.org";
  10964. auto path = std::string{"/range/32"};
  10965. #ifdef CPPHTTPLIB_SSL_ENABLED
  10966. SSLClient cli(host);
  10967. #else
  10968. Client cli(host);
  10969. #endif
  10970. cli.set_default_headers({make_range_header({{1, 10}})});
  10971. cli.set_connection_timeout(5);
  10972. {
  10973. auto res = cli.Get(path);
  10974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10975. EXPECT_EQ("bcdefghijk", res->body);
  10976. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10977. }
  10978. {
  10979. auto res = cli.Get(path);
  10980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10981. EXPECT_EQ("bcdefghijk", res->body);
  10982. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10983. }
  10984. }
  10985. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10986. Server svr;
  10987. svr.set_default_headers({{"Hello", "World"}});
  10988. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10989. res.set_content("ok", "text/plain");
  10990. });
  10991. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10992. auto se = detail::scope_exit([&] {
  10993. svr.stop();
  10994. listen_thread.join();
  10995. ASSERT_FALSE(svr.is_running());
  10996. });
  10997. svr.wait_until_ready();
  10998. Client cli("localhost", PORT);
  10999. auto res = cli.Get("/");
  11000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11001. EXPECT_EQ(StatusCode::OK_200, res->status);
  11002. EXPECT_EQ("ok", res->body);
  11003. EXPECT_EQ("World", res->get_header_value("Hello"));
  11004. }
  11005. #ifdef CPPHTTPLIB_SSL_ENABLED
  11006. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11008. ASSERT_TRUE(svr.is_valid());
  11009. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11010. std::this_thread::sleep_for(std::chrono::seconds(2));
  11011. res.set_content("a", "text/plain");
  11012. });
  11013. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11014. res.set_content("b", "text/plain");
  11015. });
  11016. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11017. auto se = detail::scope_exit([&] {
  11018. svr.stop();
  11019. listen_thread.join();
  11020. ASSERT_FALSE(svr.is_running());
  11021. });
  11022. svr.wait_until_ready();
  11023. SSLClient cli("localhost", PORT);
  11024. cli.enable_server_certificate_verification(false);
  11025. cli.set_keep_alive(true);
  11026. cli.set_read_timeout(std::chrono::seconds(1));
  11027. auto resa = cli.Get("/a");
  11028. ASSERT_TRUE(!resa);
  11029. EXPECT_EQ(Error::Read, resa.error());
  11030. auto resb = cli.Get("/b");
  11031. ASSERT_TRUE(resb);
  11032. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11033. EXPECT_EQ("b", resb->body);
  11034. }
  11035. // Closing an idle keep-alive connection sends close_notify and returns. The
  11036. // server must not wait for the client's close_notify: an idle client never
  11037. // sends one, so the worker would be held until the read timeout expires, and
  11038. // stop() would wait for it.
  11039. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11041. ASSERT_TRUE(svr.is_valid());
  11042. svr.set_keep_alive_timeout(1);
  11043. svr.set_read_timeout(10, 0);
  11044. svr.Get("/", [](const Request &, Response &res) {
  11045. res.set_content("ok", "text/plain");
  11046. });
  11047. auto port = svr.bind_to_any_port(HOST);
  11048. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11049. auto se = detail::scope_exit([&] {
  11050. if (listen_thread.joinable()) {
  11051. svr.stop();
  11052. listen_thread.join();
  11053. }
  11054. });
  11055. svr.wait_until_ready();
  11056. SSLClient cli(HOST, port);
  11057. cli.enable_server_certificate_verification(false);
  11058. cli.set_keep_alive(true);
  11059. auto res = cli.Get("/");
  11060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11061. EXPECT_EQ(StatusCode::OK_200, res->status);
  11062. // Stay idle past the keep-alive timeout so the server closes the connection.
  11063. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11064. auto start = std::chrono::steady_clock::now();
  11065. svr.stop();
  11066. listen_thread.join();
  11067. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11068. std::chrono::steady_clock::now() - start)
  11069. .count();
  11070. EXPECT_LT(elapsed, 3000);
  11071. }
  11072. #endif
  11073. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11074. protected:
  11075. ServerTestWithAI_PASSIVE()
  11076. : cli_(HOST, PORT)
  11077. #ifdef CPPHTTPLIB_SSL_ENABLED
  11078. ,
  11079. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11080. #endif
  11081. {
  11082. #ifdef CPPHTTPLIB_SSL_ENABLED
  11083. cli_.enable_server_certificate_verification(false);
  11084. #endif
  11085. }
  11086. virtual void SetUp() {
  11087. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11088. res.set_content("Hello World!", "text/plain");
  11089. });
  11090. t_ = thread(
  11091. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11092. svr_.wait_until_ready();
  11093. }
  11094. virtual void TearDown() {
  11095. svr_.stop();
  11096. t_.join();
  11097. }
  11098. #ifdef CPPHTTPLIB_SSL_ENABLED
  11099. SSLClient cli_;
  11100. SSLServer svr_;
  11101. #else
  11102. Client cli_;
  11103. Server svr_;
  11104. #endif
  11105. thread t_;
  11106. };
  11107. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11108. auto res = cli_.Get("/hi");
  11109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11110. EXPECT_EQ(StatusCode::OK_200, res->status);
  11111. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11112. EXPECT_EQ("Hello World!", res->body);
  11113. }
  11114. class ServerUpDownTest : public ::testing::Test {
  11115. protected:
  11116. ServerUpDownTest() : cli_(HOST, PORT) {}
  11117. virtual void SetUp() {
  11118. t_ = thread([&]() {
  11119. svr_.bind_to_any_port(HOST);
  11120. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11121. ASSERT_TRUE(svr_.listen_after_bind());
  11122. });
  11123. svr_.wait_until_ready();
  11124. }
  11125. virtual void TearDown() {
  11126. svr_.stop();
  11127. t_.join();
  11128. }
  11129. Client cli_;
  11130. Server svr_;
  11131. thread t_;
  11132. };
  11133. TEST_F(ServerUpDownTest, QuickStartStop) {
  11134. // Should not crash, especially when run with
  11135. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11136. }
  11137. class PayloadMaxLengthTest : public ::testing::Test {
  11138. protected:
  11139. PayloadMaxLengthTest()
  11140. : cli_(HOST, PORT)
  11141. #ifdef CPPHTTPLIB_SSL_ENABLED
  11142. ,
  11143. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11144. #endif
  11145. {
  11146. #ifdef CPPHTTPLIB_SSL_ENABLED
  11147. cli_.enable_server_certificate_verification(false);
  11148. #endif
  11149. }
  11150. virtual void SetUp() {
  11151. svr_.set_payload_max_length(8);
  11152. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11153. res.set_content("test", "text/plain");
  11154. });
  11155. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11156. svr_.wait_until_ready();
  11157. }
  11158. virtual void TearDown() {
  11159. svr_.stop();
  11160. t_.join();
  11161. }
  11162. #ifdef CPPHTTPLIB_SSL_ENABLED
  11163. SSLClient cli_;
  11164. SSLServer svr_;
  11165. #else
  11166. Client cli_;
  11167. Server svr_;
  11168. #endif
  11169. thread t_;
  11170. };
  11171. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11172. auto res = cli_.Post("/test", "123456789", "text/plain");
  11173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11174. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11175. res = cli_.Post("/test", "12345678", "text/plain");
  11176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11177. EXPECT_EQ(StatusCode::OK_200, res->status);
  11178. }
  11179. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11180. // Test chunked encoding with payload exceeding the 8-byte limit
  11181. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11182. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11184. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11185. }
  11186. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11187. // Test chunked encoding with payload within the 8-byte limit
  11188. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11189. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11191. EXPECT_EQ(StatusCode::OK_200, res->status);
  11192. }
  11193. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11194. // Test using send_request to send chunked data exceeding payload limit
  11195. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11196. "Host: " +
  11197. std::string(HOST) + ":" + std::to_string(PORT) +
  11198. "\r\n"
  11199. "Transfer-Encoding: chunked\r\n"
  11200. "Connection: close\r\n"
  11201. "\r\n"
  11202. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11203. "0123456789\r\n"
  11204. "0\r\n" // End chunk
  11205. "\r\n";
  11206. std::string response;
  11207. bool result = send_request(1, chunked_request, &response);
  11208. if (!result) {
  11209. // If send_request fails, it might be because the server closed the
  11210. // connection due to payload limit enforcement, which is acceptable
  11211. SUCCEED()
  11212. << "Server rejected oversized chunked request (connection closed)";
  11213. } else {
  11214. // If we got a response, check if it's an error response or connection was
  11215. // closed early Short response length indicates connection was closed due to
  11216. // payload limit
  11217. if (response.length() <= 10) {
  11218. SUCCEED() << "Server closed connection for oversized chunked request";
  11219. } else {
  11220. // Check for error status codes
  11221. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11222. response.find("Payload Too Large") != std::string::npos ||
  11223. response.find("400") != std::string::npos);
  11224. }
  11225. }
  11226. }
  11227. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11228. // Test request without Content-Length header exceeding payload limit
  11229. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11230. "Host: " +
  11231. std::string(HOST) + ":" +
  11232. std::to_string(PORT) +
  11233. "\r\n"
  11234. "Connection: close\r\n"
  11235. "\r\n";
  11236. // Add payload exceeding the 8-byte limit
  11237. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11238. request_without_content_length += large_payload;
  11239. std::string response;
  11240. bool result = send_request(1, request_without_content_length, &response);
  11241. if (!result) {
  11242. // If send_request fails, server likely closed connection due to payload
  11243. // limit
  11244. SUCCEED() << "Server rejected oversized request without Content-Length "
  11245. "(connection closed)";
  11246. } else {
  11247. // Check if server responded with error or closed connection early
  11248. if (response.length() <= 10) {
  11249. SUCCEED() << "Server closed connection for oversized request without "
  11250. "Content-Length";
  11251. } else {
  11252. // Check for error status codes
  11253. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11254. response.find("Payload Too Large") != std::string::npos ||
  11255. response.find("400") != std::string::npos);
  11256. }
  11257. }
  11258. }
  11259. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11260. // Test request without Content-Length header within payload limit
  11261. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11262. "Host: " +
  11263. std::string(HOST) + ":" +
  11264. std::to_string(PORT) +
  11265. "\r\n"
  11266. "Connection: close\r\n"
  11267. "\r\n";
  11268. // Add payload within the 8-byte limit
  11269. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11270. request_without_content_length += small_payload;
  11271. std::string response;
  11272. bool result = send_request(1, request_without_content_length, &response);
  11273. // For requests without Content-Length, the server may have different behavior
  11274. // The key is that it should not reject due to payload limit for small
  11275. // payloads
  11276. if (result) {
  11277. // Check for any HTTP response (success or error, but not connection closed)
  11278. if (response.length() > 10) {
  11279. SUCCEED()
  11280. << "Server processed request without Content-Length within limit";
  11281. } else {
  11282. // Short response might indicate connection closed, which is acceptable
  11283. SUCCEED() << "Server closed connection for request without "
  11284. "Content-Length (acceptable behavior)";
  11285. }
  11286. } else {
  11287. // Connection failure might be due to protocol requirements
  11288. SUCCEED() << "Connection issue with request without Content-Length "
  11289. "(environment-specific)";
  11290. }
  11291. }
  11292. class LargePayloadMaxLengthTest : public ::testing::Test {
  11293. protected:
  11294. LargePayloadMaxLengthTest()
  11295. : cli_(HOST, PORT)
  11296. #ifdef CPPHTTPLIB_SSL_ENABLED
  11297. ,
  11298. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11299. #endif
  11300. {
  11301. #ifdef CPPHTTPLIB_SSL_ENABLED
  11302. cli_.enable_server_certificate_verification(false);
  11303. #endif
  11304. }
  11305. virtual void SetUp() {
  11306. // Set 10MB payload limit
  11307. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11308. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11309. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11310. res.set_content("Large payload test", "text/plain");
  11311. });
  11312. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11313. svr_.wait_until_ready();
  11314. }
  11315. virtual void TearDown() {
  11316. svr_.stop();
  11317. t_.join();
  11318. }
  11319. #ifdef CPPHTTPLIB_SSL_ENABLED
  11320. SSLClient cli_;
  11321. SSLServer svr_;
  11322. #else
  11323. Client cli_;
  11324. Server svr_;
  11325. #endif
  11326. thread t_;
  11327. };
  11328. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11329. // Test chunked encoding with payload within 10MB limit
  11330. std::string medium_payload(5 * 1024 * 1024,
  11331. 'A'); // 5MB payload, within 10MB limit
  11332. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11334. EXPECT_EQ(StatusCode::OK_200, res->status);
  11335. }
  11336. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11337. // Test chunked encoding with payload exceeding 10MB limit
  11338. std::string large_payload(12 * 1024 * 1024,
  11339. 'B'); // 12MB payload, exceeds 10MB limit
  11340. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11341. // Server may either return 413 or close the connection
  11342. if (res) {
  11343. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11344. } else {
  11345. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11346. }
  11347. }
  11348. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11349. // Test request without Content-Length header within 10MB limit
  11350. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11351. "Host: " +
  11352. std::string(HOST) + ":" +
  11353. std::to_string(PORT) +
  11354. "\r\n"
  11355. "Connection: close\r\n"
  11356. "\r\n";
  11357. // Add 1MB payload (within 10MB limit)
  11358. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11359. request_without_content_length += medium_payload;
  11360. std::string response;
  11361. bool result = send_request(5, request_without_content_length, &response);
  11362. if (result) {
  11363. // Should get a proper HTTP response for payloads within limit
  11364. if (response.length() > 10) {
  11365. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11366. "10MB limit";
  11367. } else {
  11368. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11369. "Content-Length)";
  11370. }
  11371. } else {
  11372. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11373. }
  11374. }
  11375. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11376. // Test request without Content-Length header exceeding 10MB limit
  11377. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11378. "Host: " +
  11379. std::string(HOST) + ":" +
  11380. std::to_string(PORT) +
  11381. "\r\n"
  11382. "Connection: close\r\n"
  11383. "\r\n";
  11384. // Add 12MB payload (exceeds 10MB limit)
  11385. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11386. request_without_content_length += large_payload;
  11387. std::string response;
  11388. bool result = send_request(10, request_without_content_length, &response);
  11389. if (!result) {
  11390. // Server should close connection due to payload limit
  11391. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11392. "(connection closed)";
  11393. } else {
  11394. // Check for error response
  11395. if (response.length() <= 10) {
  11396. SUCCEED()
  11397. << "Server closed connection for 12MB request exceeding 10MB limit";
  11398. } else {
  11399. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11400. response.find("Payload Too Large") != std::string::npos ||
  11401. response.find("400") != std::string::npos);
  11402. }
  11403. }
  11404. }
  11405. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11406. Server svr;
  11407. svr.Get("/", [](const Request &, Response &res) {
  11408. // Claims far more than it sends, then drops the connection.
  11409. res.set_content_provider(size_t(1) << 41, "text/plain",
  11410. [](size_t, size_t, DataSink &sink) {
  11411. sink.write("abc", 3);
  11412. return false;
  11413. });
  11414. });
  11415. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11416. auto se = detail::scope_exit([&] {
  11417. svr.stop();
  11418. thread.join();
  11419. ASSERT_FALSE(svr.is_running());
  11420. });
  11421. svr.wait_until_ready();
  11422. Client cli(HOST, PORT);
  11423. cli.set_payload_max_length(0);
  11424. EXPECT_FALSE(cli.Get("/"));
  11425. }
  11426. // Accepts one connection on 127.0.0.1:port, reads the request head and sends
  11427. // back the given bytes, which httplib::Server could not be made to send.
  11428. static void serve_raw_once(int port, const std::string &response) {
  11429. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11430. default_socket_options(srv);
  11431. sockaddr_in addr{};
  11432. addr.sin_family = AF_INET;
  11433. addr.sin_port = htons(static_cast<uint16_t>(port));
  11434. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11435. int opt = 1;
  11436. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11437. #ifdef _WIN32
  11438. reinterpret_cast<const char *>(&opt),
  11439. #else
  11440. &opt,
  11441. #endif
  11442. sizeof(opt));
  11443. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11444. ::listen(srv, 1);
  11445. auto cli = ::accept(srv, nullptr, nullptr);
  11446. if (cli != INVALID_SOCKET) {
  11447. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11448. std::string head;
  11449. char c;
  11450. while (head.find("\r\n\r\n") == std::string::npos &&
  11451. ::recv(cli, &c, 1, 0) == 1) {
  11452. head += c;
  11453. }
  11454. ::send(cli, response.data(), static_cast<int>(response.size()), 0);
  11455. detail::close_socket(cli);
  11456. }
  11457. detail::close_socket(srv);
  11458. }
  11459. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  11460. const char *responses[] = {
  11461. "HTTP/1.1 103 Early Hints\r\n"
  11462. "Link: </style.css>; rel=preload\r\n"
  11463. "\r\n"
  11464. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11465. "HTTP/1.1 100 Continue\r\n"
  11466. "X-Note: interim\r\n"
  11467. "\r\n"
  11468. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11469. };
  11470. for (auto response : responses) {
  11471. std::thread t([&]() { serve_raw_once(PORT, response); });
  11472. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11473. Client cli("127.0.0.1", PORT);
  11474. auto res = cli.Get("/");
  11475. t.join();
  11476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11477. EXPECT_EQ(StatusCode::OK_200, res->status);
  11478. EXPECT_EQ("ok", res->body);
  11479. }
  11480. }
  11481. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  11482. std::atomic<bool> closed_by_client{false};
  11483. auto server_thread = std::thread([&] {
  11484. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11485. default_socket_options(srv);
  11486. sockaddr_in addr{};
  11487. addr.sin_family = AF_INET;
  11488. addr.sin_port = htons(static_cast<uint16_t>(PORT));
  11489. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11490. int opt = 1;
  11491. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11492. #ifdef _WIN32
  11493. reinterpret_cast<const char *>(&opt),
  11494. #else
  11495. &opt,
  11496. #endif
  11497. sizeof(opt));
  11498. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11499. ::listen(srv, 1);
  11500. auto cli = ::accept(srv, nullptr, nullptr);
  11501. if (cli != INVALID_SOCKET) {
  11502. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11503. // Answer the head without asking for the body, and keep the connection.
  11504. std::string head;
  11505. char c;
  11506. while (head.find("\r\n\r\n") == std::string::npos &&
  11507. ::recv(cli, &c, 1, 0) == 1) {
  11508. head += c;
  11509. }
  11510. std::string res =
  11511. "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n";
  11512. ::send(cli, res.data(), static_cast<int>(res.size()), 0);
  11513. // Bytes here would be read as the body the first request declared.
  11514. char buf[256];
  11515. closed_by_client = ::recv(cli, buf, sizeof(buf), 0) == 0;
  11516. detail::close_socket(cli);
  11517. }
  11518. detail::close_socket(srv);
  11519. });
  11520. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11521. Client cli("127.0.0.1", PORT);
  11522. cli.set_keep_alive(true);
  11523. cli.set_read_timeout(1, 0);
  11524. // Long enough for the client to send Expect: 100-continue.
  11525. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  11526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11527. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  11528. cli.Get("/second");
  11529. server_thread.join();
  11530. EXPECT_TRUE(closed_by_client);
  11531. }
  11532. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11533. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11534. // path.
  11535. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11536. Server svr;
  11537. const size_t LIMIT = 64 * 1024; // 64KB
  11538. svr.set_payload_max_length(LIMIT);
  11539. size_t total = 0;
  11540. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11541. const ContentReader &content_reader) {
  11542. content_reader([&](const char * /*data*/, size_t len) {
  11543. total += len;
  11544. return true;
  11545. });
  11546. res.status = 200;
  11547. res.set_content("stream_ok", "text/plain");
  11548. });
  11549. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11550. auto se = detail::scope_exit([&] {
  11551. svr.stop();
  11552. thread.join();
  11553. ASSERT_FALSE(svr.is_running());
  11554. });
  11555. svr.wait_until_ready();
  11556. // Prepare 256KB raw data and gzip-compress it
  11557. std::string raw(256 * 1024, 'A');
  11558. std::string gz;
  11559. {
  11560. z_stream zs{};
  11561. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11562. Z_DEFAULT_STRATEGY);
  11563. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11564. zs.avail_in = static_cast<uInt>(raw.size());
  11565. char outbuf[4096];
  11566. int ret;
  11567. do {
  11568. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11569. zs.avail_out = sizeof(outbuf);
  11570. ret = deflate(&zs, Z_FINISH);
  11571. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11572. } while (ret != Z_STREAM_END);
  11573. deflateEnd(&zs);
  11574. }
  11575. Client cli(HOST, PORT);
  11576. cli.set_connection_timeout(std::chrono::seconds(5));
  11577. Headers headers = {{"Content-Encoding", "gzip"}};
  11578. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11579. "application/octet-stream");
  11580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11581. // Server must reject oversized decompressed payloads with 413.
  11582. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11583. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11584. EXPECT_LE(total, LIMIT);
  11585. }
  11586. #ifndef CPPHTTPLIB_SSL_ENABLED
  11587. // For a request with neither Content-Length nor Transfer-Encoding, the
  11588. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11589. // compressed wire bytes straight to the ContentReader without ever routing
  11590. // them through the decompressor, so payload_max_length_ only bounded the
  11591. // compressed size on the wire, not the decompressed size.
  11592. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11593. Server svr;
  11594. const size_t LIMIT = 64 * 1024; // 64KB
  11595. svr.set_payload_max_length(LIMIT);
  11596. size_t total = 0;
  11597. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11598. const ContentReader &content_reader) {
  11599. content_reader([&](const char * /*data*/, size_t len) {
  11600. total += len;
  11601. return true;
  11602. });
  11603. res.status = 200;
  11604. res.set_content("stream_ok", "text/plain");
  11605. });
  11606. auto port = svr.bind_to_any_port(HOST);
  11607. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11608. auto se = detail::scope_exit([&] {
  11609. svr.stop();
  11610. thread.join();
  11611. ASSERT_FALSE(svr.is_running());
  11612. });
  11613. svr.wait_until_ready();
  11614. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11615. // StreamingGzipDecompression test above.
  11616. std::string raw(256 * 1024, 'A');
  11617. std::string gz;
  11618. {
  11619. httplib::detail::gzip_compressor compressor;
  11620. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11621. [&](const char *chunk, size_t len) {
  11622. gz.append(chunk, len);
  11623. return true;
  11624. });
  11625. ASSERT_TRUE(result);
  11626. }
  11627. // Send the gzip body over raw TCP with neither Content-Length nor
  11628. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11629. // kicks in.
  11630. std::string req = "POST /stream HTTP/1.1\r\n"
  11631. "Host: " +
  11632. std::string(HOST) + ":" + std::to_string(port) +
  11633. "\r\n"
  11634. "Content-Encoding: gzip\r\n"
  11635. "Connection: close\r\n"
  11636. "\r\n" +
  11637. gz;
  11638. std::string response;
  11639. ASSERT_TRUE(send_request(5, req, &response, port));
  11640. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11641. EXPECT_LE(total, LIMIT);
  11642. }
  11643. #endif
  11644. #endif
  11645. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11646. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11647. // the payload must be passed through untouched instead of being rejected.
  11648. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11649. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11650. Server svr;
  11651. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11652. res.set_content(body, "image/jpeg");
  11653. res.set_header("Content-Encoding", "UTF-8");
  11654. });
  11655. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11656. res.set_content(body, "image/jpeg");
  11657. res.set_header("Content-Encoding", "identity");
  11658. });
  11659. svr.Post("/echo", [](const Request &req, Response &res) {
  11660. res.set_content(req.body, "image/jpeg");
  11661. });
  11662. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11663. auto se = detail::scope_exit([&] {
  11664. svr.stop();
  11665. t.join();
  11666. ASSERT_FALSE(svr.is_running());
  11667. });
  11668. svr.wait_until_ready();
  11669. Client cli(HOST, PORT);
  11670. {
  11671. auto res = cli.Get("/image");
  11672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11673. EXPECT_EQ(StatusCode::OK_200, res->status);
  11674. EXPECT_EQ(body, res->body);
  11675. }
  11676. {
  11677. auto res = cli.Get("/identity");
  11678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11679. EXPECT_EQ(StatusCode::OK_200, res->status);
  11680. EXPECT_EQ(body, res->body);
  11681. }
  11682. {
  11683. // The same applies to a request body reaching the server.
  11684. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11685. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11687. EXPECT_EQ(StatusCode::OK_200, res->status);
  11688. EXPECT_EQ(body, res->body);
  11689. }
  11690. }
  11691. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11692. // gzip-encoded response even when the build has no zlib support.
  11693. static const char GZIPPED_HELLO_WORLD[] = {
  11694. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11695. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11696. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11697. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11698. // A content coding is a whole token, not something the field value merely
  11699. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11700. // as "fibre" look like Brotli, and turned a multi-coding value like
  11701. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11702. // it was never meant to see.
  11703. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11704. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11705. Server svr;
  11706. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11707. res.set_content(body, "image/jpeg");
  11708. res.set_header("Content-Encoding", "fibre");
  11709. });
  11710. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11711. res.set_content(body, "image/jpeg");
  11712. res.set_header("Content-Encoding", "gzip, br");
  11713. });
  11714. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11715. res.set_content(body, "image/jpeg");
  11716. res.set_header("Content-Encoding", "x-zstd-ish");
  11717. });
  11718. auto port = svr.bind_to_any_port(HOST);
  11719. thread t = thread([&]() { svr.listen_after_bind(); });
  11720. auto se = detail::scope_exit([&] {
  11721. svr.stop();
  11722. t.join();
  11723. ASSERT_FALSE(svr.is_running());
  11724. });
  11725. svr.wait_until_ready();
  11726. Client cli(HOST, port);
  11727. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11728. auto res = cli.Get(path);
  11729. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11730. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11731. // Not a coding we recognize, so the payload comes back untouched
  11732. EXPECT_EQ(body, res->body) << path;
  11733. }
  11734. }
  11735. // A content coding cpp-httplib recognizes but was not built with must be
  11736. // reported as such. Handing the still-compressed payload back to the caller
  11737. // would silently corrupt it.
  11738. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11739. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11740. Server svr;
  11741. // "image/jpeg" keeps the server from applying a content coding of its own,
  11742. // so the hand-crafted Content-Encoding below survives.
  11743. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11744. res.set_content(gzipped, "image/jpeg");
  11745. res.set_header("Content-Encoding", "gzip");
  11746. });
  11747. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11748. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11749. res.set_content(gzipped, "image/jpeg");
  11750. res.set_header("Content-Encoding", "GZIP");
  11751. });
  11752. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11753. auto se = detail::scope_exit([&] {
  11754. svr.stop();
  11755. t.join();
  11756. ASSERT_FALSE(svr.is_running());
  11757. });
  11758. svr.wait_until_ready();
  11759. Client cli(HOST, PORT);
  11760. {
  11761. auto res = cli.Get("/gzipped");
  11762. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11764. EXPECT_EQ("Hello World!", res->body);
  11765. #else
  11766. ASSERT_FALSE(res);
  11767. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11768. #endif
  11769. }
  11770. {
  11771. // open_stream() must behave the same way.
  11772. auto handle = cli.open_stream("GET", "/gzipped");
  11773. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11774. ASSERT_TRUE(handle.is_valid());
  11775. std::string received;
  11776. char buf[256];
  11777. ssize_t n;
  11778. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11779. received.append(buf, static_cast<size_t>(n));
  11780. }
  11781. EXPECT_EQ("Hello World!", received);
  11782. #else
  11783. EXPECT_FALSE(handle.is_valid());
  11784. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11785. #endif
  11786. }
  11787. {
  11788. // A differently-cased coding must not be mistaken for an unknown one, or
  11789. // the body would be handed back still compressed.
  11790. auto res = cli.Get("/gzipped-uppercase");
  11791. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11793. EXPECT_EQ("Hello World!", res->body);
  11794. #else
  11795. ASSERT_FALSE(res);
  11796. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11797. #endif
  11798. }
  11799. }
  11800. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11801. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11802. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11803. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11804. // body a second time and appending a second Content-Encoding field line, so
  11805. // clients that decode one coding per listed value handed back raw gzip bytes.
  11806. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11807. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11808. Server svr;
  11809. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11810. // keeps the server from applying a coding of its own.
  11811. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11812. res.set_content(gzipped, "text/plain");
  11813. res.set_header("Content-Encoding", "gzip");
  11814. });
  11815. auto port = svr.bind_to_any_port(HOST);
  11816. thread t = thread([&]() { svr.listen_after_bind(); });
  11817. auto se = detail::scope_exit([&] {
  11818. svr.stop();
  11819. t.join();
  11820. ASSERT_FALSE(svr.is_running());
  11821. });
  11822. svr.wait_until_ready();
  11823. Client cli(HOST, port);
  11824. Headers headers = {{"Accept-Encoding", "gzip"}};
  11825. auto res = cli.Get("/pre-gzipped", headers);
  11826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11827. EXPECT_EQ(StatusCode::OK_200, res->status);
  11828. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11829. EXPECT_EQ("Hello World!", res->body);
  11830. }
  11831. // A chunked provider settles its coding where the headers are written and
  11832. // reuses it at write time. Both ends of that have to hold: a handler's own
  11833. // Content-Encoding suppresses the coding, and a response without one is still
  11834. // compressed as it always was.
  11835. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11836. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11837. const std::string plain = "Hello World! Hello World! Hello World!";
  11838. Server svr;
  11839. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11840. res.set_header("Content-Encoding", "gzip");
  11841. res.set_chunked_content_provider(
  11842. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11843. sink.write(gzipped.data(), gzipped.size());
  11844. sink.done();
  11845. return true;
  11846. });
  11847. });
  11848. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11849. res.set_chunked_content_provider(
  11850. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11851. sink.write(plain.data(), plain.size());
  11852. sink.done();
  11853. return true;
  11854. });
  11855. });
  11856. auto port = svr.bind_to_any_port(HOST);
  11857. thread t = thread([&]() { svr.listen_after_bind(); });
  11858. auto se = detail::scope_exit([&] {
  11859. svr.stop();
  11860. t.join();
  11861. ASSERT_FALSE(svr.is_running());
  11862. });
  11863. svr.wait_until_ready();
  11864. Client cli(HOST, port);
  11865. Headers headers = {{"Accept-Encoding", "gzip"}};
  11866. {
  11867. auto res = cli.Get("/pre-gzipped", headers);
  11868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11869. EXPECT_EQ(StatusCode::OK_200, res->status);
  11870. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11871. EXPECT_EQ("Hello World!", res->body);
  11872. }
  11873. {
  11874. auto res = cli.Get("/negotiated", headers);
  11875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11876. EXPECT_EQ(StatusCode::OK_200, res->status);
  11877. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11878. EXPECT_EQ(plain, res->body);
  11879. }
  11880. }
  11881. #endif
  11882. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11883. // the same message as the comma-joined one, so both have to be read the same
  11884. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11885. // single gzip coding, and a body the sender says was encoded twice was handed
  11886. // back after one pass, still compressed but presented as decoded.
  11887. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11888. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11889. Server svr;
  11890. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11891. res.set_content(body, "image/jpeg");
  11892. res.headers.emplace("Content-Encoding", "gzip");
  11893. res.headers.emplace("Content-Encoding", "gzip");
  11894. });
  11895. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11896. res.set_content(body, "image/jpeg");
  11897. res.set_header("Content-Encoding", "gzip, gzip");
  11898. });
  11899. auto port = svr.bind_to_any_port(HOST);
  11900. thread t = thread([&]() { svr.listen_after_bind(); });
  11901. auto se = detail::scope_exit([&] {
  11902. svr.stop();
  11903. t.join();
  11904. ASSERT_FALSE(svr.is_running());
  11905. });
  11906. svr.wait_until_ready();
  11907. Client cli(HOST, port);
  11908. // Two codings is not something cpp-httplib decodes, so both representations
  11909. // take the pass-through path rather than one of them being gunzipped once.
  11910. for (const char *path : {"/split", "/joined"}) {
  11911. auto res = cli.Get(path);
  11912. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11913. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11914. EXPECT_EQ(body, res->body) << path;
  11915. }
  11916. }
  11917. // Regression test for DoS vulnerability: a malicious server sending a response
  11918. // without Content-Length header must not cause unbounded memory consumption on
  11919. // the client side. The client should stop reading after a reasonable limit,
  11920. // similar to the server-side set_payload_max_length protection.
  11921. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11922. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11923. #ifndef _WIN32
  11924. signal(SIGPIPE, SIG_IGN);
  11925. #endif
  11926. auto server_thread = std::thread([] {
  11927. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11928. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11929. default_socket_options(srv);
  11930. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11931. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11932. sockaddr_in addr{};
  11933. addr.sin_family = AF_INET;
  11934. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11935. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11936. int opt = 1;
  11937. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11938. #ifdef _WIN32
  11939. reinterpret_cast<const char *>(&opt),
  11940. #else
  11941. &opt,
  11942. #endif
  11943. sizeof(opt));
  11944. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11945. ::listen(srv, 1);
  11946. sockaddr_in cli_addr{};
  11947. socklen_t cli_len = sizeof(cli_addr);
  11948. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11949. if (cli != INVALID_SOCKET) {
  11950. char buf[4096];
  11951. ::recv(cli, buf, sizeof(buf), 0);
  11952. // Malicious response: no Content-Length, no chunked encoding
  11953. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11954. "Connection: close\r\n"
  11955. "\r\n";
  11956. ::send(cli,
  11957. #ifdef _WIN32
  11958. static_cast<const char *>(response_header.c_str()),
  11959. static_cast<int>(response_header.size()),
  11960. #else
  11961. response_header.c_str(), response_header.size(),
  11962. #endif
  11963. 0);
  11964. // Send 10MB of data
  11965. std::string chunk(64 * 1024, 'A');
  11966. size_t total_sent = 0;
  11967. while (total_sent < MALICIOUS_DATA_SIZE) {
  11968. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11969. auto sent = ::send(cli,
  11970. #ifdef _WIN32
  11971. static_cast<const char *>(chunk.c_str()),
  11972. static_cast<int>(to_send),
  11973. #else
  11974. chunk.c_str(), to_send,
  11975. #endif
  11976. 0);
  11977. if (sent <= 0) break;
  11978. total_sent += static_cast<size_t>(sent);
  11979. }
  11980. detail::close_socket(cli);
  11981. }
  11982. detail::close_socket(srv);
  11983. });
  11984. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11985. size_t total_read = 0;
  11986. {
  11987. Client cli("127.0.0.1", PORT + 2);
  11988. cli.set_read_timeout(5, 0);
  11989. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11990. auto stream = cli.open_stream("GET", "/malicious");
  11991. ASSERT_TRUE(stream.is_valid());
  11992. char buffer[64 * 1024];
  11993. ssize_t n;
  11994. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11995. total_read += static_cast<size_t>(n);
  11996. }
  11997. } // StreamHandle and Client destroyed here, closing the socket
  11998. server_thread.join();
  11999. // With set_payload_max_length, the client must stop reading before consuming
  12000. // all 10MB. The read loop should be cut off at or near the configured limit.
  12001. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12002. << "Client read " << total_read << " bytes, exceeding the configured "
  12003. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12004. }
  12005. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12006. // the entire response body without truncation.
  12007. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12008. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12009. #ifndef _WIN32
  12010. signal(SIGPIPE, SIG_IGN);
  12011. #endif
  12012. auto server_thread = std::thread([] {
  12013. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12014. default_socket_options(srv);
  12015. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12016. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12017. sockaddr_in addr{};
  12018. addr.sin_family = AF_INET;
  12019. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12020. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12021. int opt = 1;
  12022. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12023. #ifdef _WIN32
  12024. reinterpret_cast<const char *>(&opt),
  12025. #else
  12026. &opt,
  12027. #endif
  12028. sizeof(opt));
  12029. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12030. ::listen(srv, 1);
  12031. sockaddr_in cli_addr{};
  12032. socklen_t cli_len = sizeof(cli_addr);
  12033. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12034. if (cli != INVALID_SOCKET) {
  12035. char buf[4096];
  12036. ::recv(cli, buf, sizeof(buf), 0);
  12037. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12038. "Connection: close\r\n"
  12039. "\r\n";
  12040. ::send(cli,
  12041. #ifdef _WIN32
  12042. static_cast<const char *>(response_header.c_str()),
  12043. static_cast<int>(response_header.size()),
  12044. #else
  12045. response_header.c_str(), response_header.size(),
  12046. #endif
  12047. 0);
  12048. std::string chunk(64 * 1024, 'A');
  12049. size_t total_sent = 0;
  12050. while (total_sent < DATA_SIZE) {
  12051. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12052. auto sent = ::send(cli,
  12053. #ifdef _WIN32
  12054. static_cast<const char *>(chunk.c_str()),
  12055. static_cast<int>(to_send),
  12056. #else
  12057. chunk.c_str(), to_send,
  12058. #endif
  12059. 0);
  12060. if (sent <= 0) break;
  12061. total_sent += static_cast<size_t>(sent);
  12062. }
  12063. #ifdef _WIN32
  12064. ::shutdown(cli, SD_SEND);
  12065. #else
  12066. ::shutdown(cli, SHUT_WR);
  12067. #endif
  12068. // Drain until the client closes its end, ensuring all data is delivered
  12069. char drain[1024];
  12070. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12071. detail::close_socket(cli);
  12072. }
  12073. detail::close_socket(srv);
  12074. });
  12075. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12076. size_t total_read = 0;
  12077. {
  12078. Client cli("127.0.0.1", PORT + 2);
  12079. cli.set_read_timeout(5, 0);
  12080. cli.set_payload_max_length(0); // 0 means no limit
  12081. auto stream = cli.open_stream("GET", "/data");
  12082. ASSERT_TRUE(stream.is_valid());
  12083. char buffer[64 * 1024];
  12084. ssize_t n;
  12085. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12086. total_read += static_cast<size_t>(n);
  12087. }
  12088. }
  12089. server_thread.join();
  12090. EXPECT_EQ(total_read, DATA_SIZE)
  12091. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12092. << " bytes without truncation, but only read " << total_read << " bytes.";
  12093. }
  12094. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12095. // enormous Content-Length must not cause the client to pre-allocate a huge
  12096. // response body buffer. The reservation is capped at payload_max_length_, and
  12097. // the read itself fails when the body exceeds the limit.
  12098. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12099. #ifndef _WIN32
  12100. signal(SIGPIPE, SIG_IGN);
  12101. #endif
  12102. auto server_thread = std::thread([] {
  12103. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12104. default_socket_options(srv);
  12105. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12106. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12107. sockaddr_in addr{};
  12108. addr.sin_family = AF_INET;
  12109. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12110. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12111. int opt = 1;
  12112. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12113. #ifdef _WIN32
  12114. reinterpret_cast<const char *>(&opt),
  12115. #else
  12116. &opt,
  12117. #endif
  12118. sizeof(opt));
  12119. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12120. ::listen(srv, 1);
  12121. sockaddr_in cli_addr{};
  12122. socklen_t cli_len = sizeof(cli_addr);
  12123. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12124. if (cli != INVALID_SOCKET) {
  12125. char buf[4096];
  12126. ::recv(cli, buf, sizeof(buf), 0);
  12127. // Malicious response: claim a 20GB body but send only a tiny payload.
  12128. std::string response = "HTTP/1.1 200 OK\r\n"
  12129. "Content-Length: 20000000000\r\n"
  12130. "\r\n"
  12131. "abc";
  12132. ::send(cli,
  12133. #ifdef _WIN32
  12134. static_cast<const char *>(response.c_str()),
  12135. static_cast<int>(response.size()),
  12136. #else
  12137. response.c_str(), response.size(),
  12138. #endif
  12139. 0);
  12140. detail::close_socket(cli);
  12141. }
  12142. detail::close_socket(srv);
  12143. });
  12144. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12145. {
  12146. Client cli("127.0.0.1", PORT + 2);
  12147. cli.set_read_timeout(5, 0);
  12148. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12149. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12150. // (server claims more bytes than payload_max_length permits), but it must
  12151. // not exhaust memory before getting there.
  12152. auto res = cli.Get("/malicious");
  12153. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12154. }
  12155. server_thread.join();
  12156. }
  12157. // Verify that content_receiver bypasses the default payload_max_length,
  12158. // allowing streaming downloads larger than 100MB without requiring an explicit
  12159. // set_payload_max_length call.
  12160. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12161. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12162. #ifndef _WIN32
  12163. signal(SIGPIPE, SIG_IGN);
  12164. #endif
  12165. auto server_thread = std::thread([] {
  12166. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12167. default_socket_options(srv);
  12168. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12169. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12170. sockaddr_in addr{};
  12171. addr.sin_family = AF_INET;
  12172. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12173. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12174. int opt = 1;
  12175. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12176. #ifdef _WIN32
  12177. reinterpret_cast<const char *>(&opt),
  12178. #else
  12179. &opt,
  12180. #endif
  12181. sizeof(opt));
  12182. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12183. ::listen(srv, 1);
  12184. sockaddr_in cli_addr{};
  12185. socklen_t cli_len = sizeof(cli_addr);
  12186. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12187. if (cli != INVALID_SOCKET) {
  12188. char buf[4096];
  12189. ::recv(cli, buf, sizeof(buf), 0);
  12190. // Response with Content-Length larger than default 100MB limit
  12191. auto content_length = std::to_string(DATA_SIZE);
  12192. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12193. "Content-Length: " +
  12194. content_length +
  12195. "\r\n"
  12196. "Connection: close\r\n"
  12197. "\r\n";
  12198. ::send(cli,
  12199. #ifdef _WIN32
  12200. static_cast<const char *>(response_header.c_str()),
  12201. static_cast<int>(response_header.size()),
  12202. #else
  12203. response_header.c_str(), response_header.size(),
  12204. #endif
  12205. 0);
  12206. std::string chunk(64 * 1024, 'A');
  12207. size_t total_sent = 0;
  12208. while (total_sent < DATA_SIZE) {
  12209. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12210. auto sent = ::send(cli,
  12211. #ifdef _WIN32
  12212. static_cast<const char *>(chunk.c_str()),
  12213. static_cast<int>(to_send),
  12214. #else
  12215. chunk.c_str(), to_send,
  12216. #endif
  12217. 0);
  12218. if (sent <= 0) break;
  12219. total_sent += static_cast<size_t>(sent);
  12220. }
  12221. detail::close_socket(cli);
  12222. }
  12223. detail::close_socket(srv);
  12224. });
  12225. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12226. size_t total_received = 0;
  12227. {
  12228. Client cli("127.0.0.1", PORT + 2);
  12229. cli.set_read_timeout(10, 0);
  12230. // Do NOT call set_payload_max_length — use the default 100MB limit
  12231. auto res =
  12232. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12233. total_received += data_length;
  12234. return true;
  12235. });
  12236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12237. EXPECT_EQ(StatusCode::OK_200, res->status);
  12238. }
  12239. server_thread.join();
  12240. EXPECT_EQ(total_received, DATA_SIZE)
  12241. << "With content_receiver, the client should read all " << DATA_SIZE
  12242. << " bytes despite the default 100MB payload_max_length, but only read "
  12243. << total_received << " bytes.";
  12244. }
  12245. // Verify that an explicit set_payload_max_length smaller than the response is
  12246. // enforced even when a content_receiver is used.
  12247. TEST(ClientVulnerabilityTest,
  12248. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12249. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12250. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12251. #ifndef _WIN32
  12252. signal(SIGPIPE, SIG_IGN);
  12253. #endif
  12254. auto server_thread = std::thread([] {
  12255. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12256. default_socket_options(srv);
  12257. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12258. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12259. sockaddr_in addr{};
  12260. addr.sin_family = AF_INET;
  12261. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12262. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12263. int opt = 1;
  12264. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12265. #ifdef _WIN32
  12266. reinterpret_cast<const char *>(&opt),
  12267. #else
  12268. &opt,
  12269. #endif
  12270. sizeof(opt));
  12271. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12272. ::listen(srv, 1);
  12273. sockaddr_in cli_addr{};
  12274. socklen_t cli_len = sizeof(cli_addr);
  12275. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12276. if (cli != INVALID_SOCKET) {
  12277. char buf[4096];
  12278. ::recv(cli, buf, sizeof(buf), 0);
  12279. auto content_length = std::to_string(DATA_SIZE);
  12280. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12281. "Content-Length: " +
  12282. content_length +
  12283. "\r\n"
  12284. "Connection: close\r\n"
  12285. "\r\n";
  12286. ::send(cli,
  12287. #ifdef _WIN32
  12288. static_cast<const char *>(response_header.c_str()),
  12289. static_cast<int>(response_header.size()),
  12290. #else
  12291. response_header.c_str(), response_header.size(),
  12292. #endif
  12293. 0);
  12294. std::string chunk(64 * 1024, 'A');
  12295. size_t total_sent = 0;
  12296. while (total_sent < DATA_SIZE) {
  12297. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12298. auto sent = ::send(cli,
  12299. #ifdef _WIN32
  12300. static_cast<const char *>(chunk.c_str()),
  12301. static_cast<int>(to_send),
  12302. #else
  12303. chunk.c_str(), to_send,
  12304. #endif
  12305. 0);
  12306. if (sent <= 0) break;
  12307. total_sent += static_cast<size_t>(sent);
  12308. }
  12309. detail::close_socket(cli);
  12310. }
  12311. detail::close_socket(srv);
  12312. });
  12313. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12314. size_t total_received = 0;
  12315. {
  12316. Client cli("127.0.0.1", PORT + 2);
  12317. cli.set_read_timeout(10, 0);
  12318. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12319. auto res =
  12320. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12321. total_received += data_length;
  12322. return true;
  12323. });
  12324. // Should fail because 200MB exceeds the explicit 150MB limit
  12325. EXPECT_FALSE(res);
  12326. }
  12327. server_thread.join();
  12328. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12329. << "Client with content_receiver should respect the explicit "
  12330. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12331. << total_received << " bytes.";
  12332. }
  12333. // Verify that an explicit set_payload_max_length larger than the response
  12334. // allows the content_receiver to read all data successfully.
  12335. TEST(ClientVulnerabilityTest,
  12336. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12337. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12338. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12339. #ifndef _WIN32
  12340. signal(SIGPIPE, SIG_IGN);
  12341. #endif
  12342. auto server_thread = std::thread([] {
  12343. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12344. default_socket_options(srv);
  12345. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12346. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12347. sockaddr_in addr{};
  12348. addr.sin_family = AF_INET;
  12349. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12350. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12351. int opt = 1;
  12352. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12353. #ifdef _WIN32
  12354. reinterpret_cast<const char *>(&opt),
  12355. #else
  12356. &opt,
  12357. #endif
  12358. sizeof(opt));
  12359. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12360. ::listen(srv, 1);
  12361. sockaddr_in cli_addr{};
  12362. socklen_t cli_len = sizeof(cli_addr);
  12363. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12364. if (cli != INVALID_SOCKET) {
  12365. char buf[4096];
  12366. ::recv(cli, buf, sizeof(buf), 0);
  12367. auto content_length = std::to_string(DATA_SIZE);
  12368. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12369. "Content-Length: " +
  12370. content_length +
  12371. "\r\n"
  12372. "Connection: close\r\n"
  12373. "\r\n";
  12374. ::send(cli,
  12375. #ifdef _WIN32
  12376. static_cast<const char *>(response_header.c_str()),
  12377. static_cast<int>(response_header.size()),
  12378. #else
  12379. response_header.c_str(), response_header.size(),
  12380. #endif
  12381. 0);
  12382. std::string chunk(64 * 1024, 'A');
  12383. size_t total_sent = 0;
  12384. while (total_sent < DATA_SIZE) {
  12385. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12386. auto sent = ::send(cli,
  12387. #ifdef _WIN32
  12388. static_cast<const char *>(chunk.c_str()),
  12389. static_cast<int>(to_send),
  12390. #else
  12391. chunk.c_str(), to_send,
  12392. #endif
  12393. 0);
  12394. if (sent <= 0) break;
  12395. total_sent += static_cast<size_t>(sent);
  12396. }
  12397. #ifdef _WIN32
  12398. ::shutdown(cli, SD_SEND);
  12399. #else
  12400. ::shutdown(cli, SHUT_WR);
  12401. #endif
  12402. char drain[1024];
  12403. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12404. detail::close_socket(cli);
  12405. }
  12406. detail::close_socket(srv);
  12407. });
  12408. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12409. size_t total_received = 0;
  12410. {
  12411. Client cli("127.0.0.1", PORT + 2);
  12412. cli.set_read_timeout(10, 0);
  12413. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12414. auto res =
  12415. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12416. total_received += data_length;
  12417. return true;
  12418. });
  12419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12420. EXPECT_EQ(StatusCode::OK_200, res->status);
  12421. }
  12422. server_thread.join();
  12423. EXPECT_EQ(total_received, DATA_SIZE)
  12424. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12425. << " bytes (larger than " << DATA_SIZE
  12426. << " bytes response), content_receiver should read all data, but only "
  12427. "read "
  12428. << total_received << " bytes.";
  12429. }
  12430. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12431. // Regression test for "zip bomb" attack on the client side: a malicious server
  12432. // sends a small gzip-compressed response that decompresses to a huge payload.
  12433. // The client must enforce payload_max_length on the decompressed size.
  12434. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12435. constexpr size_t DECOMPRESSED_SIZE =
  12436. 10 * 1024 * 1024; // 10MB after decompression
  12437. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12438. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12439. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12440. std::string compressed;
  12441. {
  12442. httplib::detail::gzip_compressor compressor;
  12443. bool ok =
  12444. compressor.compress(uncompressed.data(), uncompressed.size(),
  12445. /*last=*/true, [&](const char *buf, size_t len) {
  12446. compressed.append(buf, len);
  12447. return true;
  12448. });
  12449. ASSERT_TRUE(ok);
  12450. }
  12451. // Sanity: compressed data should be much smaller than the decompressed size
  12452. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12453. #ifndef _WIN32
  12454. signal(SIGPIPE, SIG_IGN);
  12455. #endif
  12456. // Set up the listening socket in the main thread so the server is guaranteed
  12457. // to be ready before the client connects (eliminates race condition).
  12458. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12459. default_socket_options(srv);
  12460. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12461. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12462. sockaddr_in addr{};
  12463. addr.sin_family = AF_INET;
  12464. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12465. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12466. int opt = 1;
  12467. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12468. #ifdef _WIN32
  12469. reinterpret_cast<const char *>(&opt),
  12470. #else
  12471. &opt,
  12472. #endif
  12473. sizeof(opt));
  12474. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12475. ASSERT_EQ(0, ::listen(srv, 1));
  12476. auto server_thread = std::thread([&compressed, srv] {
  12477. sockaddr_in cli_addr{};
  12478. socklen_t cli_len = sizeof(cli_addr);
  12479. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12480. if (cli != INVALID_SOCKET) {
  12481. // Read the full HTTP request (until \r\n\r\n)
  12482. char buf[4096];
  12483. size_t total = 0;
  12484. while (total < sizeof(buf)) {
  12485. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12486. if (n <= 0) break;
  12487. total += static_cast<size_t>(n);
  12488. // Check for end of headers
  12489. if (total >= 4) {
  12490. std::string req(buf, total);
  12491. if (req.find("\r\n\r\n") != std::string::npos) break;
  12492. }
  12493. }
  12494. // Malicious response: gzip-compressed body, no Content-Length
  12495. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12496. "Content-Encoding: gzip\r\n"
  12497. "Connection: close\r\n"
  12498. "\r\n";
  12499. ::send(cli,
  12500. #ifdef _WIN32
  12501. static_cast<const char *>(response_header.c_str()),
  12502. static_cast<int>(response_header.size()),
  12503. #else
  12504. response_header.c_str(), response_header.size(),
  12505. #endif
  12506. 0);
  12507. // Send the compressed payload (small on the wire, huge when decompressed)
  12508. size_t total_sent = 0;
  12509. while (total_sent < compressed.size()) {
  12510. auto to_send = std::min(compressed.size() - total_sent,
  12511. static_cast<size_t>(64 * 1024));
  12512. auto sent =
  12513. ::send(cli,
  12514. #ifdef _WIN32
  12515. static_cast<const char *>(compressed.c_str() + total_sent),
  12516. static_cast<int>(to_send),
  12517. #else
  12518. compressed.c_str() + total_sent, to_send,
  12519. #endif
  12520. 0);
  12521. if (sent <= 0) break;
  12522. total_sent += static_cast<size_t>(sent);
  12523. }
  12524. detail::close_socket(cli);
  12525. }
  12526. });
  12527. auto se = detail::scope_exit([&] {
  12528. detail::close_socket(srv);
  12529. server_thread.join();
  12530. });
  12531. size_t total_decompressed = 0;
  12532. {
  12533. Client cli("127.0.0.1", PORT + 3);
  12534. cli.set_read_timeout(5, 0);
  12535. cli.set_decompress(true);
  12536. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12537. auto stream = cli.open_stream("GET", "/zipbomb");
  12538. ASSERT_TRUE(stream.is_valid());
  12539. char buffer[64 * 1024];
  12540. ssize_t n;
  12541. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12542. total_decompressed += static_cast<size_t>(n);
  12543. }
  12544. }
  12545. // The decompressed size must be capped by payload_max_length. Without
  12546. // protection, the client would decompress the full 10MB from a tiny
  12547. // compressed payload, enabling a zip bomb DoS attack.
  12548. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12549. << "Client decompressed " << total_decompressed
  12550. << " bytes from a gzip response. The decompressed size should be "
  12551. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12552. }
  12553. #endif
  12554. TEST(HostAndPortPropertiesTest, NoSSL) {
  12555. httplib::Client cli("www.google.com", 1234);
  12556. ASSERT_EQ("www.google.com", cli.host());
  12557. ASSERT_EQ(1234, cli.port());
  12558. }
  12559. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12560. httplib::Client cli("www.google.com:1234");
  12561. ASSERT_EQ("www.google.com", cli.host());
  12562. ASSERT_EQ(1234, cli.port());
  12563. }
  12564. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12565. // Port number that overflows int — should not crash, client becomes invalid
  12566. httplib::Client cli("http://www.google.com:99999999999999999999");
  12567. ASSERT_FALSE(cli.is_valid());
  12568. }
  12569. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12570. // Port 99999 exceeds valid range (1-65535) — should not crash
  12571. httplib::Client cli("http://www.google.com:99999");
  12572. ASSERT_FALSE(cli.is_valid());
  12573. auto res = cli.Get("/");
  12574. EXPECT_FALSE(res);
  12575. EXPECT_EQ(Error::Connection, res.error());
  12576. }
  12577. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12578. httplib::Client cli("http://www.google.com:80abc");
  12579. ASSERT_FALSE(cli.is_valid());
  12580. }
  12581. #ifdef CPPHTTPLIB_SSL_ENABLED
  12582. TEST(HostAndPortPropertiesTest, SSL) {
  12583. httplib::SSLClient cli("www.google.com");
  12584. ASSERT_EQ("www.google.com", cli.host());
  12585. ASSERT_EQ(443, cli.port());
  12586. }
  12587. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12588. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12589. std::string cert;
  12590. read_file(CA_CERT_FILE, cert);
  12591. httplib::SSLClient httplib_client("www.google.com");
  12592. // Load CA store first time
  12593. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12594. // Load CA store second time (update)
  12595. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12596. // Verify client is still valid and can make connections
  12597. httplib_client.enable_server_certificate_verification(true);
  12598. auto res = httplib_client.Get("/");
  12599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12600. // Google may return 200 or 301 depending on various factors
  12601. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12602. res->status == StatusCode::MovedPermanently_301);
  12603. }
  12604. TEST(SSLClientTest, ServerNameIndication_Online) {
  12605. auto host = "httpbingo.org";
  12606. auto path = std::string{"/get"};
  12607. SSLClient cli(host, 443);
  12608. auto res = cli.Get(path);
  12609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12610. ASSERT_EQ(StatusCode::OK_200, res->status);
  12611. }
  12612. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12613. // Use a site that will cause SSL verification failure due to self-signed cert
  12614. SSLClient cli("self-signed.badssl.com", 443);
  12615. cli.enable_server_certificate_verification(true);
  12616. auto res = cli.Get("/");
  12617. ASSERT_TRUE(!res);
  12618. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12619. // Verify backend error is captured for SSLServerVerification
  12620. // This occurs when certificate verification fails
  12621. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12622. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12623. EXPECT_NE(0UL, res.ssl_backend_error());
  12624. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12625. // For OpenSSL, ssl_error is 0 for verification errors
  12626. EXPECT_EQ(0, res.ssl_error());
  12627. #if !defined(_WIN32) || \
  12628. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12629. // On non-Windows or when Windows Schannel is disabled, the error comes
  12630. // from OpenSSL's verification
  12631. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12632. res.ssl_backend_error());
  12633. #endif
  12634. #endif
  12635. }
  12636. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12637. // Use a site where hostname doesn't match the certificate
  12638. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12639. SSLClient cli("wrong.host.badssl.com", 443);
  12640. cli.enable_server_certificate_verification(true);
  12641. cli.enable_server_hostname_verification(true);
  12642. auto res = cli.Get("/");
  12643. ASSERT_TRUE(!res);
  12644. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12645. // Verify backend error is captured for hostname verification failure
  12646. EXPECT_NE(0UL, res.ssl_backend_error());
  12647. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12648. // For OpenSSL, ssl_error is 0 for verification errors
  12649. EXPECT_EQ(0, res.ssl_error());
  12650. #if !defined(_WIN32) || \
  12651. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12652. // On non-Windows or when Windows Schannel is disabled, the error comes
  12653. // from OpenSSL's hostname verification
  12654. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12655. res.ssl_backend_error());
  12656. #endif
  12657. #endif
  12658. }
  12659. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12660. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12661. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12662. SSLClient cli("www.google.com", 443);
  12663. cli.enable_server_certificate_verification(true);
  12664. auto res = cli.Get("/");
  12665. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12666. }
  12667. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12668. SSLClient cli("www.google.com", 443);
  12669. cli.enable_server_certificate_verification(true);
  12670. cli.enable_windows_certificate_verification(false);
  12671. auto res = cli.Get("/");
  12672. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12673. }
  12674. // The server sends an intermediate cross-signed by a root Windows trusts,
  12675. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12676. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12677. SSLClient cli("accounts.spotify.com", 443);
  12678. auto res = cli.Get("/");
  12679. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12680. << " ssl_backend_error=" << res.ssl_backend_error();
  12681. }
  12682. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12683. // policy status, which no backend reports for a self-signed certificate.
  12684. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12685. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12686. ASSERT_TRUE(svr.is_valid());
  12687. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12688. auto se = detail::scope_exit([&] {
  12689. svr.stop();
  12690. t.join();
  12691. ASSERT_FALSE(svr.is_running());
  12692. });
  12693. svr.wait_until_ready();
  12694. SSLClient cli("127.0.0.1", PORT);
  12695. cli.set_connection_timeout(30);
  12696. auto res = cli.Get("/");
  12697. ASSERT_FALSE(res);
  12698. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12699. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12700. }
  12701. #endif
  12702. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12703. Client cli("https://google.com");
  12704. auto res = cli.Get("/");
  12705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12706. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12707. }
  12708. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12709. SSLClient cli("google.com");
  12710. cli.set_ca_cert_path(CA_CERT_FILE);
  12711. auto res = cli.Get("/");
  12712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12713. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12714. }
  12715. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12716. SSLClient cli("google.com");
  12717. cli.enable_server_certificate_verification(true);
  12718. cli.set_ca_cert_path("hello");
  12719. auto res = cli.Get("/");
  12720. ASSERT_TRUE(!res);
  12721. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12722. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12723. // should be set
  12724. EXPECT_EQ(0, res.ssl_error());
  12725. // Verify backend error is captured for SSLLoadingCerts
  12726. // This error occurs when loading CA certificates fails
  12727. EXPECT_NE(0UL, res.ssl_backend_error());
  12728. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12729. // OpenSSL specific error codes:
  12730. // > openssl errstr 0x80000002
  12731. // error:80000002:system library::No such file or directory
  12732. // > openssl errstr 0xA000126
  12733. // error:0A000126:SSL routines::unexpected eof while reading
  12734. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12735. res.ssl_backend_error() == 0xA000126);
  12736. #endif
  12737. }
  12738. TEST(SSLClientTest, ServerCertificateVerification4) {
  12739. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12740. ASSERT_TRUE(svr.is_valid());
  12741. svr.Get("/test", [&](const Request &, Response &res) {
  12742. res.set_content("test", "text/plain");
  12743. svr.stop();
  12744. ASSERT_TRUE(true);
  12745. });
  12746. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12747. auto se = detail::scope_exit([&] {
  12748. t.join();
  12749. ASSERT_FALSE(svr.is_running());
  12750. });
  12751. svr.wait_until_ready();
  12752. SSLClient cli("127.0.0.1", PORT);
  12753. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12754. cli.enable_server_certificate_verification(true);
  12755. cli.set_connection_timeout(30);
  12756. auto res = cli.Get("/test");
  12757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12758. ASSERT_EQ(StatusCode::OK_200, res->status);
  12759. }
  12760. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12761. std::string cert;
  12762. read_file(CA_CERT_FILE, cert);
  12763. SSLClient cli("google.com");
  12764. cli.load_ca_cert_store(cert.data(), cert.size());
  12765. const auto res = cli.Get("/");
  12766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12767. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12768. }
  12769. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12770. // clang-format off
  12771. static constexpr char cert[] =
  12772. "GlobalSign Root CA\n"
  12773. "==================\n"
  12774. "-----BEGIN CERTIFICATE-----\n"
  12775. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12776. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12777. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12778. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12779. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12780. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12781. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12782. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12783. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12784. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12785. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12786. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12787. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12788. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12789. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12790. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12791. "-----END CERTIFICATE-----\n";
  12792. // clang-format on
  12793. SSLClient cli("google.com");
  12794. cli.load_ca_cert_store(cert, sizeof(cert));
  12795. const auto res = cli.Get("/");
  12796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12797. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12798. }
  12799. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12800. SSLClient cli("www.youtube.com");
  12801. cli.set_ca_cert_path(CA_CERT_FILE);
  12802. cli.enable_server_certificate_verification(true);
  12803. cli.set_follow_location(true);
  12804. auto res = cli.Get("/");
  12805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12806. ASSERT_EQ(StatusCode::OK_200, res->status);
  12807. }
  12808. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12809. SSLClient cli("wWw.YouTube.Com");
  12810. cli.set_ca_cert_path(CA_CERT_FILE);
  12811. cli.enable_server_certificate_verification(true);
  12812. cli.enable_server_hostname_verification(true);
  12813. cli.set_follow_location(true);
  12814. auto res = cli.Get("/");
  12815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12816. ASSERT_EQ(StatusCode::OK_200, res->status);
  12817. }
  12818. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12819. SSLClient cli("gOoGlE.COm");
  12820. cli.enable_server_certificate_verification(true);
  12821. cli.enable_server_hostname_verification(true);
  12822. cli.set_follow_location(true);
  12823. auto res = cli.Get("/");
  12824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12825. ASSERT_EQ(StatusCode::OK_200, res->status);
  12826. }
  12827. TEST(SSLClientTest, Issue2004_Online) {
  12828. Client client("https://google.com");
  12829. client.set_follow_location(true);
  12830. auto res = client.Get("/");
  12831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12832. ASSERT_EQ(StatusCode::OK_200, res->status);
  12833. auto body = res->body;
  12834. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12835. }
  12836. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12837. // Create SSLClient with invalid cert/key to make is_valid() return false
  12838. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12839. "nonexistent_key.pem");
  12840. // is_valid() should be false due to cert loading failure
  12841. ASSERT_FALSE(cli.is_valid());
  12842. auto res = cli.Get("/");
  12843. ASSERT_FALSE(res);
  12844. EXPECT_EQ(Error::SSLConnection, res.error());
  12845. }
  12846. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12847. // Test for Issue #2251: SSL error not properly reported when client cert
  12848. // and key paths are swapped or mismatched
  12849. // This simulates the scenario where user accidentally swaps the cert and key
  12850. // files
  12851. // Using client cert file as private key and vice versa (completely wrong)
  12852. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12853. // Should fail validation due to cert/key mismatch
  12854. ASSERT_FALSE(cli.is_valid());
  12855. // Attempt to make a request should fail with proper error
  12856. auto res = cli.Get("/");
  12857. ASSERT_FALSE(res);
  12858. EXPECT_EQ(Error::SSLConnection, res.error());
  12859. // SSL error should be recorded in the Result object (this is the key fix for
  12860. // Issue #2251)
  12861. auto backend_error = res.ssl_backend_error();
  12862. EXPECT_NE(0u, backend_error);
  12863. }
  12864. // Tests cert/key mismatch detection at the TLS context level
  12865. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12866. // Test that using mismatched cert/key causes connection failure.
  12867. // We verify this at the SSLClient level rather than through internal
  12868. // TLS API functions.
  12869. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12870. cli.enable_server_certificate_verification(false);
  12871. cli.set_connection_timeout(2);
  12872. // The mismatch should cause a connection or handshake error
  12873. auto res = cli.Get("/test");
  12874. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12875. // Either way, the request should fail
  12876. EXPECT_FALSE(res);
  12877. }
  12878. #endif
  12879. #if 0
  12880. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12881. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12882. ASSERT_TRUE(cli != nullptr);
  12883. cli->set_address_family(AF_INET6);
  12884. cli->set_interface("en0");
  12885. auto res = cli->Get("/get");
  12886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12887. ASSERT_EQ(StatusCode::OK_200, res->status);
  12888. }
  12889. #endif
  12890. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12891. #ifdef CPPHTTPLIB_SSL_ENABLED
  12892. void ClientCertPresent(
  12893. const std::string &client_cert_file,
  12894. const std::string &client_private_key_file,
  12895. const std::string &client_encrypted_private_key_pass = std::string()) {
  12896. using namespace httplib::tls;
  12897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12898. CLIENT_CA_CERT_DIR);
  12899. ASSERT_TRUE(svr.is_valid());
  12900. svr.Get("/test", [&](const Request &req, Response &res) {
  12901. res.set_content("test", "text/plain");
  12902. auto cert = req.peer_cert();
  12903. ASSERT_TRUE(static_cast<bool>(cert));
  12904. std::string common_name = cert.subject_cn();
  12905. EXPECT_EQ("Common Name", common_name);
  12906. });
  12907. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12908. auto se = detail::scope_exit([&] {
  12909. svr.stop();
  12910. t.join();
  12911. ASSERT_FALSE(svr.is_running());
  12912. });
  12913. svr.wait_until_ready();
  12914. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12915. client_encrypted_private_key_pass);
  12916. cli.enable_server_certificate_verification(false);
  12917. cli.set_connection_timeout(30);
  12918. auto res = cli.Get("/test");
  12919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12920. ASSERT_EQ(StatusCode::OK_200, res->status);
  12921. }
  12922. TEST(SSLClientServerTest, ClientCertPresent) {
  12923. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12924. }
  12925. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12926. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12927. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12928. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12929. }
  12930. // PEM memory-based constructor tests (works with all TLS backends)
  12931. void PemMemoryClientCertPresent(
  12932. const std::string &client_cert_file,
  12933. const std::string &client_private_key_file,
  12934. const std::string &client_encrypted_private_key_pass = std::string()) {
  12935. // Read PEM files into memory
  12936. std::string server_cert_pem, server_key_pem;
  12937. std::string client_ca_pem;
  12938. std::string client_cert_pem, client_key_pem;
  12939. read_file(SERVER_CERT_FILE, server_cert_pem);
  12940. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12941. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12942. read_file(client_cert_file, client_cert_pem);
  12943. read_file(client_private_key_file, client_key_pem);
  12944. // Create server with PEM memory
  12945. SSLServer::PemMemory server_pem = {
  12946. server_cert_pem.c_str(),
  12947. server_cert_pem.size(),
  12948. server_key_pem.c_str(),
  12949. server_key_pem.size(),
  12950. client_ca_pem.c_str(),
  12951. client_ca_pem.size(),
  12952. nullptr // no password for server key
  12953. };
  12954. SSLServer svr(server_pem);
  12955. ASSERT_TRUE(svr.is_valid());
  12956. svr.Get("/test", [&](const Request &, Response &res) {
  12957. res.set_content("test", "text/plain");
  12958. });
  12959. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12960. auto se = detail::scope_exit([&] {
  12961. svr.stop();
  12962. t.join();
  12963. ASSERT_FALSE(svr.is_running());
  12964. });
  12965. svr.wait_until_ready();
  12966. // Create client with PEM memory
  12967. const char *password = client_encrypted_private_key_pass.empty()
  12968. ? nullptr
  12969. : client_encrypted_private_key_pass.c_str();
  12970. SSLClient::PemMemory client_pem = {
  12971. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12972. client_key_pem.size(), password};
  12973. SSLClient cli(HOST, PORT, client_pem);
  12974. cli.enable_server_certificate_verification(false);
  12975. cli.set_connection_timeout(30);
  12976. auto res = cli.Get("/test");
  12977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12978. ASSERT_EQ(StatusCode::OK_200, res->status);
  12979. }
  12980. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12981. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12982. }
  12983. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12984. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12985. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12986. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12987. }
  12988. TEST(SSLClientServerTest, ClientCertMissing) {
  12989. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12990. CLIENT_CA_CERT_DIR);
  12991. ASSERT_TRUE(svr.is_valid());
  12992. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12993. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12994. auto se = detail::scope_exit([&] {
  12995. svr.stop();
  12996. t.join();
  12997. ASSERT_FALSE(svr.is_running());
  12998. });
  12999. svr.wait_until_ready();
  13000. SSLClient cli(HOST, PORT);
  13001. cli.set_connection_timeout(30);
  13002. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13003. // the chain check on Windows, so the result does not depend on the order.
  13004. cli.enable_server_hostname_verification(false);
  13005. auto res = cli.Get("/test");
  13006. ASSERT_TRUE(!res);
  13007. // When client cert is missing and server requires it, connection fails
  13008. // Error type depends on backend implementation
  13009. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13010. res.error() == Error::SSLConnection);
  13011. // Verify backend error is captured
  13012. // Note: This test may have different error codes depending on the exact
  13013. // verification failure
  13014. EXPECT_NE(0UL, res.ssl_backend_error());
  13015. }
  13016. TEST(SSLClientServerTest, TrustDirOptional) {
  13017. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13018. ASSERT_TRUE(svr.is_valid());
  13019. svr.Get("/test", [&](const Request &, Response &res) {
  13020. res.set_content("test", "text/plain");
  13021. });
  13022. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13023. auto se = detail::scope_exit([&] {
  13024. svr.stop();
  13025. t.join();
  13026. ASSERT_FALSE(svr.is_running());
  13027. });
  13028. svr.wait_until_ready();
  13029. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13030. cli.enable_server_certificate_verification(false);
  13031. cli.set_connection_timeout(30);
  13032. auto res = cli.Get("/test");
  13033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13034. ASSERT_EQ(StatusCode::OK_200, res->status);
  13035. }
  13036. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13037. class NoListenSSLServer : public SSLServer {
  13038. public:
  13039. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13040. const char *client_ca_cert_file_path,
  13041. const char *client_ca_cert_dir_path = nullptr)
  13042. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13043. client_ca_cert_dir_path),
  13044. stop_(false) {}
  13045. std::atomic_bool stop_;
  13046. private:
  13047. bool process_and_close_socket(socket_t /*sock*/) override {
  13048. // Don't create SSL context
  13049. while (!stop_.load()) {
  13050. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13051. }
  13052. return true;
  13053. }
  13054. };
  13055. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13056. CLIENT_CA_CERT_FILE);
  13057. ASSERT_TRUE(svr.is_valid());
  13058. svr.Get("/test", [&](const Request &, Response &res) {
  13059. res.set_content("test", "text/plain");
  13060. });
  13061. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13062. auto se = detail::scope_exit([&] {
  13063. svr.stop_ = true;
  13064. svr.stop();
  13065. t.join();
  13066. ASSERT_FALSE(svr.is_running());
  13067. });
  13068. svr.wait_until_ready();
  13069. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13070. cli.enable_server_certificate_verification(false);
  13071. cli.set_connection_timeout(1);
  13072. auto res = cli.Get("/test");
  13073. ASSERT_TRUE(!res);
  13074. EXPECT_EQ(Error::SSLConnection, res.error());
  13075. // Timeout results in WantRead error code (maps to backend-specific value)
  13076. EXPECT_NE(0, res.ssl_error());
  13077. }
  13078. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13079. // Test SSLServer with client certificate verification using the standard
  13080. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13082. CLIENT_CA_CERT_DIR);
  13083. ASSERT_TRUE(svr.is_valid());
  13084. svr.Get("/test", [&](const Request &req, Response &res) {
  13085. res.set_content("test", "text/plain");
  13086. auto cert = req.peer_cert();
  13087. ASSERT_TRUE(static_cast<bool>(cert));
  13088. auto common_name = cert.subject_cn();
  13089. EXPECT_EQ("Common Name", common_name);
  13090. });
  13091. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13092. auto se = detail::scope_exit([&] {
  13093. svr.stop();
  13094. t.join();
  13095. ASSERT_FALSE(svr.is_running());
  13096. });
  13097. svr.wait_until_ready();
  13098. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13099. cli.enable_server_certificate_verification(false);
  13100. cli.set_connection_timeout(30);
  13101. auto res = cli.Get("/test");
  13102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13103. ASSERT_EQ(StatusCode::OK_200, res->status);
  13104. }
  13105. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13106. // Verifies that wildcard matching and exact matching work consistently
  13107. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13108. using namespace httplib::tls;
  13109. // We need a running server to test against
  13110. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13111. ASSERT_TRUE(svr.is_valid());
  13112. svr.Get("/test", [](const Request &, Response &res) {
  13113. res.set_content("ok", "text/plain");
  13114. });
  13115. thread t([&]() { svr.listen(HOST, PORT); });
  13116. auto se = detail::scope_exit([&] {
  13117. svr.stop();
  13118. t.join();
  13119. });
  13120. svr.wait_until_ready();
  13121. bool verify_callback_called = false;
  13122. bool verify_result_wrong = false;
  13123. SSLClient cli(HOST, PORT);
  13124. cli.enable_server_certificate_verification(true);
  13125. cli.set_ca_cert_path(CA_CERT_FILE);
  13126. cli.set_connection_timeout(5);
  13127. // Note: Test certificate has CN="Common Name", not "localhost"
  13128. bool verify_result_cn = false;
  13129. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13130. verify_callback_called = true;
  13131. if (!ctx.cert) return false;
  13132. // Test 1: "Common Name" should match (our test server cert CN)
  13133. verify_result_cn = ctx.check_hostname("Common Name");
  13134. // Test 2: wrong hostname should not match
  13135. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13136. return true; // Accept for the purpose of this test
  13137. });
  13138. auto res = cli.Get("/test");
  13139. // The request may succeed or fail depending on cert configuration
  13140. // but the callback should have been called
  13141. ASSERT_TRUE(verify_callback_called)
  13142. << "Verify callback should have been called";
  13143. // CN="Common Name" should match our test certificate
  13144. //
  13145. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13146. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13147. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13148. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13149. // <openssl/base.h>, which is included transitively when
  13150. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13151. #if defined(OPENSSL_IS_BORINGSSL)
  13152. EXPECT_FALSE(verify_result_cn)
  13153. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13154. #else
  13155. EXPECT_TRUE(verify_result_cn)
  13156. << "verify_hostname should match 'Common Name' (certificate CN)";
  13157. #endif
  13158. // Wrong hostname should not match
  13159. EXPECT_FALSE(verify_result_wrong)
  13160. << "verify_hostname should not match 'wronghost.example.com'";
  13161. }
  13162. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13163. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13164. // X509_check_ip behavior and must hold for every backend.
  13165. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13166. using namespace httplib::tls;
  13167. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13168. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13169. ASSERT_TRUE(svr.is_valid());
  13170. svr.Get("/test", [](const Request &, Response &res) {
  13171. res.set_content("ok", "text/plain");
  13172. });
  13173. thread t([&]() { svr.listen(HOST, PORT); });
  13174. auto se = detail::scope_exit([&] {
  13175. svr.stop();
  13176. t.join();
  13177. });
  13178. svr.wait_until_ready();
  13179. bool verify_callback_called = false;
  13180. bool ip_matched_via_cn = true;
  13181. SSLClient cli(HOST, PORT);
  13182. cli.enable_server_certificate_verification(true);
  13183. cli.set_ca_cert_path(CA_CERT_FILE);
  13184. cli.set_connection_timeout(5);
  13185. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13186. verify_callback_called = true;
  13187. if (!ctx.cert) return false;
  13188. // The IP appears only in the CN, so it must NOT be accepted.
  13189. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13190. return true; // Accept for the purpose of this test
  13191. });
  13192. cli.Get("/test");
  13193. ASSERT_TRUE(verify_callback_called)
  13194. << "Verify callback should have been called";
  13195. EXPECT_FALSE(ip_matched_via_cn)
  13196. << "An IP host must not be authenticated via the certificate CN";
  13197. }
  13198. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13199. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13200. using namespace httplib::tls;
  13201. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13202. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13203. ASSERT_TRUE(svr.is_valid());
  13204. svr.Get("/test", [](const Request &, Response &res) {
  13205. res.set_content("ok", "text/plain");
  13206. });
  13207. thread t([&]() { svr.listen(HOST, PORT); });
  13208. auto se = detail::scope_exit([&] {
  13209. svr.stop();
  13210. t.join();
  13211. });
  13212. svr.wait_until_ready();
  13213. bool verify_callback_called = false;
  13214. bool san_matched = false;
  13215. bool wrong_ipv6_matched = true;
  13216. bool cn_ipv6_matched = true;
  13217. SSLClient cli(HOST, PORT);
  13218. cli.enable_server_certificate_verification(true);
  13219. cli.set_ca_cert_path(CA_CERT_FILE);
  13220. cli.set_connection_timeout(5);
  13221. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13222. verify_callback_called = true;
  13223. if (!ctx.cert) return false;
  13224. // Matches the IPv6 iPAddress SAN.
  13225. san_matched = ctx.check_hostname("2001:db8::1");
  13226. // A different IPv6 address must not match.
  13227. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13228. // "::1" lives only in the CN, so it must not be accepted.
  13229. cn_ipv6_matched = ctx.check_hostname("::1");
  13230. return true; // Accept for the purpose of this test
  13231. });
  13232. cli.Get("/test");
  13233. ASSERT_TRUE(verify_callback_called)
  13234. << "Verify callback should have been called";
  13235. EXPECT_TRUE(san_matched)
  13236. << "verify_hostname should match an IPv6 iPAddress SAN";
  13237. EXPECT_FALSE(wrong_ipv6_matched)
  13238. << "verify_hostname should not match a non-matching IPv6 address";
  13239. EXPECT_FALSE(cn_ipv6_matched)
  13240. << "An IPv6 host must not be authenticated via the certificate CN";
  13241. }
  13242. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13243. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13244. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13245. using namespace httplib::tls;
  13246. // SANs: DNS:a.zz, IP:42.46.122.122
  13247. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13248. ASSERT_TRUE(svr.is_valid());
  13249. svr.Get("/test", [](const Request &, Response &res) {
  13250. res.set_content("ok", "text/plain");
  13251. });
  13252. auto port = svr.bind_to_any_port(HOST);
  13253. thread t([&]() { svr.listen_after_bind(); });
  13254. auto se = detail::scope_exit([&] {
  13255. svr.stop();
  13256. t.join();
  13257. });
  13258. svr.wait_until_ready();
  13259. bool verify_callback_called = false;
  13260. bool dns_san_matched = false;
  13261. bool ip_san_matched = false;
  13262. bool ip_matched_via_dns_san = true;
  13263. bool dns_matched_via_ip_san = true;
  13264. SSLClient cli(HOST, port);
  13265. cli.enable_server_certificate_verification(true);
  13266. cli.set_ca_cert_path(CA_CERT_FILE);
  13267. cli.set_connection_timeout(5);
  13268. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13269. verify_callback_called = true;
  13270. if (!ctx.cert) return false;
  13271. dns_san_matched = ctx.check_hostname("a.zz");
  13272. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13273. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13274. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13275. return true; // Accept for the purpose of this test
  13276. });
  13277. cli.Get("/test");
  13278. ASSERT_TRUE(verify_callback_called)
  13279. << "Verify callback should have been called";
  13280. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13281. EXPECT_TRUE(ip_san_matched)
  13282. << "verify_hostname should match an iPAddress SAN";
  13283. EXPECT_FALSE(ip_matched_via_dns_san)
  13284. << "An IP host must not be authenticated via a dNSName SAN";
  13285. EXPECT_FALSE(dns_matched_via_ip_san)
  13286. << "A DNS host must not be authenticated via an iPAddress SAN";
  13287. }
  13288. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13289. // "www.*.example.test" names one host and not every host under example.test.
  13290. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13291. using namespace httplib::tls;
  13292. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13293. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13294. ASSERT_TRUE(svr.is_valid());
  13295. svr.Get("/test", [](const Request &, Response &res) {
  13296. res.set_content("ok", "text/plain");
  13297. });
  13298. auto port = svr.bind_to_any_port(HOST);
  13299. thread t([&]() { svr.listen_after_bind(); });
  13300. auto se = detail::scope_exit([&] {
  13301. svr.stop();
  13302. t.join();
  13303. });
  13304. svr.wait_until_ready();
  13305. bool verify_callback_called = false;
  13306. bool leftmost_wildcard_matched = false;
  13307. bool wildcard_spanned_labels = true;
  13308. bool inner_wildcard_matched = true;
  13309. SSLClient cli(HOST, port);
  13310. cli.enable_server_certificate_verification(true);
  13311. cli.set_ca_cert_path(CA_CERT_FILE);
  13312. cli.set_connection_timeout(5);
  13313. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13314. verify_callback_called = true;
  13315. if (!ctx.cert) return false;
  13316. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13317. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13318. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13319. return true; // Accept for the purpose of this test
  13320. });
  13321. cli.Get("/test");
  13322. ASSERT_TRUE(verify_callback_called)
  13323. << "Verify callback should have been called";
  13324. EXPECT_TRUE(leftmost_wildcard_matched)
  13325. << "A leftmost wildcard should match a single label";
  13326. EXPECT_FALSE(wildcard_spanned_labels)
  13327. << "A wildcard label must not match more than one label";
  13328. EXPECT_FALSE(inner_wildcard_matched)
  13329. << "A wildcard outside the leftmost label must not be honoured";
  13330. }
  13331. // sans() must report each SAN entry under its own type.
  13332. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13333. using namespace httplib::tls;
  13334. // SANs: DNS:a.zz, IP:42.46.122.122
  13335. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13336. ASSERT_TRUE(svr.is_valid());
  13337. svr.Get("/test", [](const Request &, Response &res) {
  13338. res.set_content("ok", "text/plain");
  13339. });
  13340. auto port = svr.bind_to_any_port(HOST);
  13341. thread t([&]() { svr.listen_after_bind(); });
  13342. auto se = detail::scope_exit([&] {
  13343. svr.stop();
  13344. t.join();
  13345. });
  13346. svr.wait_until_ready();
  13347. bool verify_callback_called = false;
  13348. std::vector<SanEntry> sans;
  13349. SSLClient cli(HOST, port);
  13350. cli.enable_server_certificate_verification(true);
  13351. cli.set_ca_cert_path(CA_CERT_FILE);
  13352. cli.set_connection_timeout(5);
  13353. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13354. verify_callback_called = true;
  13355. if (!ctx.cert) return false;
  13356. sans = ctx.sans();
  13357. return true; // Accept for the purpose of this test
  13358. });
  13359. cli.Get("/test");
  13360. ASSERT_TRUE(verify_callback_called)
  13361. << "Verify callback should have been called";
  13362. auto has_san = [&](SanType type, const std::string &value) {
  13363. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13364. return san.type == type && san.value == value;
  13365. });
  13366. };
  13367. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13368. << "sans() should report the dNSName SAN";
  13369. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13370. << "sans() should report the iPAddress SAN";
  13371. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13372. << "sans() must not report the dNSName SAN as an address";
  13373. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13374. << "sans() must not report the iPAddress SAN as a DNS name";
  13375. }
  13376. #endif
  13377. // mbedTLS-specific callback constructor test
  13378. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13379. #ifdef CPPHTTPLIB_SSL_ENABLED
  13380. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13381. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13382. ASSERT_TRUE(svr.is_valid());
  13383. // Set up a handler to verify client certificate is present
  13384. bool client_cert_verified = false;
  13385. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13386. // Verify that client certificate was provided
  13387. client_cert_verified = true;
  13388. res.set_content("success", "text/plain");
  13389. });
  13390. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13391. auto se = detail::scope_exit([&] {
  13392. svr.stop();
  13393. t.join();
  13394. ASSERT_FALSE(svr.is_running());
  13395. });
  13396. svr.wait_until_ready();
  13397. // Client with certificate
  13398. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13399. cli.enable_server_certificate_verification(false);
  13400. cli.set_connection_timeout(30);
  13401. auto res = cli.Get("/test");
  13402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13403. ASSERT_EQ(StatusCode::OK_200, res->status);
  13404. ASSERT_TRUE(client_cert_verified);
  13405. EXPECT_EQ("success", res->body);
  13406. }
  13407. #endif
  13408. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13409. // backends
  13410. #ifdef CPPHTTPLIB_SSL_ENABLED
  13411. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13412. using namespace httplib::tls;
  13413. // Test that when client CA cert file is provided,
  13414. // the server properly requests and validates client certificates
  13415. // Create a server with client authentication
  13416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13417. ASSERT_TRUE(svr.is_valid());
  13418. bool handler_called = false;
  13419. svr.Get("/test", [&](const Request &req, Response &res) {
  13420. handler_called = true;
  13421. // Verify that a client certificate was provided
  13422. auto cert = req.peer_cert();
  13423. ASSERT_TRUE(static_cast<bool>(cert));
  13424. // Get the issuer name
  13425. std::string issuer_str = cert.issuer_name();
  13426. ASSERT_FALSE(issuer_str.empty());
  13427. // The client certificate should be issued by our test CA
  13428. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13429. res.set_content("authenticated", "text/plain");
  13430. });
  13431. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13432. auto se = detail::scope_exit([&] {
  13433. svr.stop();
  13434. t.join();
  13435. ASSERT_FALSE(svr.is_running());
  13436. });
  13437. svr.wait_until_ready();
  13438. // Connect with a client certificate issued by the CA
  13439. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13440. cli.enable_server_certificate_verification(false);
  13441. cli.set_connection_timeout(30);
  13442. auto res = cli.Get("/test");
  13443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13444. ASSERT_EQ(StatusCode::OK_200, res->status);
  13445. ASSERT_TRUE(handler_called);
  13446. EXPECT_EQ("authenticated", res->body);
  13447. }
  13448. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13449. using namespace httplib::tls;
  13450. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13451. ASSERT_TRUE(svr.is_valid());
  13452. svr.Get("/test", [](const Request &, Response &res) {
  13453. res.set_content("ok", "text/plain");
  13454. });
  13455. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13456. auto se = detail::scope_exit([&] {
  13457. svr.stop();
  13458. t.join();
  13459. });
  13460. svr.wait_until_ready();
  13461. SSLClient cli(HOST, PORT);
  13462. cli.enable_server_certificate_verification(false);
  13463. cli.set_connection_timeout(30);
  13464. bool cert_checked = false;
  13465. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13466. if (ctx.cert) {
  13467. auto sans = ctx.sans();
  13468. // Test certificate may or may not have SANs - just verify the API
  13469. // works If SANs exist, verify the types are valid
  13470. for (const auto &san : sans) {
  13471. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13472. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13473. san.type == SanType::OTHER);
  13474. EXPECT_FALSE(san.value.empty());
  13475. }
  13476. cert_checked = true;
  13477. }
  13478. return true;
  13479. });
  13480. auto res = cli.Get("/test");
  13481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13482. EXPECT_TRUE(cert_checked);
  13483. }
  13484. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13485. using namespace httplib::tls;
  13486. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13487. ASSERT_TRUE(svr.is_valid());
  13488. svr.Get("/test", [](const Request &, Response &res) {
  13489. res.set_content("ok", "text/plain");
  13490. });
  13491. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13492. auto se = detail::scope_exit([&] {
  13493. svr.stop();
  13494. t.join();
  13495. });
  13496. svr.wait_until_ready();
  13497. SSLClient cli(HOST, PORT);
  13498. cli.enable_server_certificate_verification(false);
  13499. cli.set_connection_timeout(30);
  13500. bool validity_checked = false;
  13501. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13502. if (ctx.cert) {
  13503. time_t not_before = 0, not_after = 0;
  13504. bool result = ctx.validity(not_before, not_after);
  13505. EXPECT_TRUE(result);
  13506. // Verify that not_before < now < not_after for a valid cert
  13507. time_t now = time(nullptr);
  13508. EXPECT_LT(not_before, now);
  13509. EXPECT_GT(not_after, now);
  13510. validity_checked = true;
  13511. }
  13512. return true;
  13513. });
  13514. auto res = cli.Get("/test");
  13515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13516. EXPECT_TRUE(validity_checked);
  13517. }
  13518. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13519. using namespace httplib::tls;
  13520. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13521. ASSERT_TRUE(svr.is_valid());
  13522. svr.Get("/test", [](const Request &, Response &res) {
  13523. res.set_content("ok", "text/plain");
  13524. });
  13525. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13526. auto se = detail::scope_exit([&] {
  13527. svr.stop();
  13528. t.join();
  13529. });
  13530. svr.wait_until_ready();
  13531. SSLClient cli(HOST, PORT);
  13532. cli.enable_server_certificate_verification(false);
  13533. cli.set_connection_timeout(30);
  13534. bool serial_checked = false;
  13535. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13536. if (ctx.cert) {
  13537. std::string serial = ctx.serial();
  13538. EXPECT_FALSE(serial.empty());
  13539. // Serial should be a hex string
  13540. for (char c : serial) {
  13541. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13542. (c >= 'a' && c <= 'f'));
  13543. }
  13544. serial_checked = true;
  13545. }
  13546. return true;
  13547. });
  13548. auto res = cli.Get("/test");
  13549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13550. EXPECT_TRUE(serial_checked);
  13551. }
  13552. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13553. // Test 1: Valid CA file - no error should be recorded
  13554. {
  13555. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13556. CLIENT_CA_CERT_FILE);
  13557. ASSERT_TRUE(svr.is_valid());
  13558. // With valid setup, last_ssl_error should be 0
  13559. EXPECT_EQ(0, svr.ssl_last_error());
  13560. }
  13561. // Test 2: Invalid CA file content
  13562. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13563. {
  13564. // Create a temporary file with completely invalid content
  13565. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13566. {
  13567. std::ofstream ofs(temp_invalid_ca);
  13568. ofs << "This is not a certificate file at all\n";
  13569. ofs << "Just plain text content\n";
  13570. }
  13571. // Create server with invalid CA file
  13572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13573. // Clean up temporary file
  13574. std::remove(temp_invalid_ca);
  13575. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13576. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13577. // Note: SSL_CTX_load_verify_locations typically fails first,
  13578. // but our error handling code path is still exercised
  13579. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13580. }
  13581. }
  13582. TEST(VerifyCallbackTest, VerifyContextFields) {
  13583. using namespace httplib::tls;
  13584. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13585. ASSERT_TRUE(svr.is_valid());
  13586. svr.Get("/test", [](const Request &, Response &res) {
  13587. res.set_content("ok", "text/plain");
  13588. });
  13589. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13590. auto se = detail::scope_exit([&] {
  13591. svr.stop();
  13592. t.join();
  13593. });
  13594. svr.wait_until_ready();
  13595. SSLClient cli(HOST, PORT);
  13596. cli.enable_server_certificate_verification(false);
  13597. cli.set_connection_timeout(30);
  13598. int callback_count = 0;
  13599. bool saw_leaf_cert = false;
  13600. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13601. if (ctx.cert) {
  13602. callback_count++;
  13603. // We should see at least one certificate (the leaf)
  13604. std::string cn = ctx.subject_cn();
  13605. if (!cn.empty()) { saw_leaf_cert = true; }
  13606. // Verify context fields are populated
  13607. EXPECT_NE(ctx.session, nullptr);
  13608. EXPECT_GE(ctx.depth, 0);
  13609. }
  13610. return true;
  13611. });
  13612. auto res = cli.Get("/test");
  13613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13614. EXPECT_GT(callback_count, 0);
  13615. EXPECT_TRUE(saw_leaf_cert);
  13616. }
  13617. // A verifier belongs to the client that set it, not to the thread that set it.
  13618. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13619. using namespace httplib::tls;
  13620. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13621. ASSERT_TRUE(svr.is_valid());
  13622. svr.Get("/test", [](const Request &, Response &res) {
  13623. res.set_content("ok", "text/plain");
  13624. });
  13625. auto port = svr.bind_to_any_port(HOST);
  13626. thread t([&]() { svr.listen_after_bind(); });
  13627. auto se = detail::scope_exit([&] {
  13628. svr.stop();
  13629. t.join();
  13630. });
  13631. svr.wait_until_ready();
  13632. auto rejecting_calls = 0;
  13633. SSLClient rejecting(HOST, port);
  13634. rejecting.enable_server_certificate_verification(false);
  13635. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13636. rejecting_calls++;
  13637. return false;
  13638. });
  13639. auto accepting_calls = 0;
  13640. SSLClient accepting(HOST, port);
  13641. accepting.enable_server_certificate_verification(false);
  13642. // Set on another thread than the requests below.
  13643. thread([&]() {
  13644. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13645. accepting_calls++;
  13646. return true;
  13647. });
  13648. }).join();
  13649. // Requested on another thread than the verifier was set on.
  13650. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13651. EXPECT_GT(rejecting_calls, 0);
  13652. auto res = accepting.Get("/test");
  13653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13654. EXPECT_GT(accepting_calls, 0);
  13655. }
  13656. // VerifyContext::session is the same handle the other tls:: functions take.
  13657. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13658. using namespace httplib::tls;
  13659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13660. ASSERT_TRUE(svr.is_valid());
  13661. svr.Get("/test", [](const Request &, Response &res) {
  13662. res.set_content("ok", "text/plain");
  13663. });
  13664. auto port = svr.bind_to_any_port(HOST);
  13665. thread t([&]() { svr.listen_after_bind(); });
  13666. auto se = detail::scope_exit([&] {
  13667. svr.stop();
  13668. t.join();
  13669. });
  13670. svr.wait_until_ready();
  13671. SSLClient cli(HOST, port);
  13672. cli.enable_server_certificate_verification(false);
  13673. session_t verifier_session = nullptr;
  13674. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13675. verifier_session = ctx.session;
  13676. return true;
  13677. });
  13678. session_t session_verifier_session = nullptr;
  13679. cli.set_session_verifier([&](session_t session) {
  13680. session_verifier_session = session;
  13681. return SSLVerifierResponse::NoDecisionMade;
  13682. });
  13683. auto res = cli.Get("/test");
  13684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13685. EXPECT_NE(nullptr, verifier_session);
  13686. EXPECT_EQ(session_verifier_session, verifier_session);
  13687. }
  13688. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13689. using httplib::tls::TlsError;
  13690. // Test that verify_error_to_string returns empty for success
  13691. std::string success_str = TlsError::verify_error_to_string(0);
  13692. EXPECT_TRUE(success_str.empty());
  13693. // Test that verify_error_to_string returns non-empty for error codes
  13694. // Using a common error code (certificate expired)
  13695. std::string error_str =
  13696. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13697. EXPECT_FALSE(error_str.empty());
  13698. }
  13699. TEST(SessionVerifierTest, CertificateAccepted) {
  13700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13701. ASSERT_TRUE(svr.is_valid());
  13702. svr.Get("/test", [](const Request &, Response &res) {
  13703. res.set_content("ok", "text/plain");
  13704. });
  13705. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13706. auto se = detail::scope_exit([&] {
  13707. svr.stop();
  13708. t.join();
  13709. });
  13710. svr.wait_until_ready();
  13711. SSLClient cli(HOST, PORT);
  13712. cli.enable_server_certificate_verification(false);
  13713. cli.set_connection_timeout(30);
  13714. bool callback_called = false;
  13715. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13716. EXPECT_NE(session, nullptr);
  13717. callback_called = true;
  13718. return SSLVerifierResponse::CertificateAccepted;
  13719. });
  13720. auto res = cli.Get("/test");
  13721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13722. EXPECT_EQ(200, res->status);
  13723. EXPECT_TRUE(callback_called);
  13724. }
  13725. TEST(SessionVerifierTest, CertificateRejected) {
  13726. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13727. ASSERT_TRUE(svr.is_valid());
  13728. svr.Get("/test", [](const Request &, Response &res) {
  13729. res.set_content("ok", "text/plain");
  13730. });
  13731. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13732. auto se = detail::scope_exit([&] {
  13733. svr.stop();
  13734. t.join();
  13735. });
  13736. svr.wait_until_ready();
  13737. SSLClient cli(HOST, PORT);
  13738. cli.enable_server_certificate_verification(false);
  13739. cli.set_connection_timeout(30);
  13740. bool callback_called = false;
  13741. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13742. EXPECT_NE(session, nullptr);
  13743. callback_called = true;
  13744. return SSLVerifierResponse::CertificateRejected;
  13745. });
  13746. auto res = cli.Get("/test");
  13747. EXPECT_FALSE(res);
  13748. EXPECT_TRUE(callback_called);
  13749. }
  13750. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13751. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13752. ASSERT_TRUE(svr.is_valid());
  13753. svr.Get("/test", [](const Request &, Response &res) {
  13754. res.set_content("ok", "text/plain");
  13755. });
  13756. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13757. auto se = detail::scope_exit([&] {
  13758. svr.stop();
  13759. t.join();
  13760. });
  13761. svr.wait_until_ready();
  13762. // NoDecisionMade with verification disabled should succeed (no default check)
  13763. SSLClient cli(HOST, PORT);
  13764. cli.enable_server_certificate_verification(false);
  13765. cli.set_connection_timeout(30);
  13766. bool callback_called = false;
  13767. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13768. EXPECT_NE(session, nullptr);
  13769. callback_called = true;
  13770. return SSLVerifierResponse::NoDecisionMade;
  13771. });
  13772. auto res = cli.Get("/test");
  13773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13774. EXPECT_EQ(200, res->status);
  13775. EXPECT_TRUE(callback_called);
  13776. }
  13777. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13778. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13779. ASSERT_TRUE(svr.is_valid());
  13780. svr.Get("/test", [](const Request &, Response &res) {
  13781. res.set_content("ok", "text/plain");
  13782. });
  13783. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13784. auto se = detail::scope_exit([&] {
  13785. svr.stop();
  13786. t.join();
  13787. });
  13788. svr.wait_until_ready();
  13789. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13790. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13791. // so we only check that the request fails, not whether the callback was
  13792. // called.
  13793. SSLClient cli(HOST, PORT);
  13794. cli.enable_server_certificate_verification(true);
  13795. cli.set_connection_timeout(30);
  13796. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13797. EXPECT_NE(session, nullptr);
  13798. return SSLVerifierResponse::NoDecisionMade;
  13799. });
  13800. auto res = cli.Get("/test");
  13801. EXPECT_FALSE(res);
  13802. }
  13803. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13804. // Test SSL server using PemMemory constructor with client CA certificates
  13805. // Read PEM files
  13806. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13807. read_file(SERVER_CERT_FILE, server_cert_pem);
  13808. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13809. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13810. // Create SSLServer with PemMemory constructor including client CA
  13811. SSLServer::PemMemory server_pem = {
  13812. server_cert_pem.c_str(),
  13813. server_cert_pem.size(),
  13814. server_key_pem.c_str(),
  13815. server_key_pem.size(),
  13816. client_ca_pem.c_str(),
  13817. client_ca_pem.size(),
  13818. nullptr // no password for server key
  13819. };
  13820. SSLServer svr(server_pem);
  13821. ASSERT_TRUE(svr.is_valid());
  13822. // No SSL error should be recorded for valid setup
  13823. EXPECT_EQ(0, svr.ssl_last_error());
  13824. // Set up server endpoints
  13825. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13826. res.set_content("ok", "text/plain");
  13827. });
  13828. // Start server in a thread
  13829. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13830. svr.wait_until_ready();
  13831. // Connect with client certificate (using constructor with paths)
  13832. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13833. cli.enable_server_certificate_verification(false);
  13834. auto res = cli.Get("/test-pem-ca");
  13835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13836. EXPECT_EQ(200, res->status);
  13837. EXPECT_EQ("ok", res->body);
  13838. svr.stop();
  13839. server_thread.join();
  13840. }
  13841. #endif
  13842. #ifdef _WIN32
  13843. TEST(CleanupTest, WSACleanup) {
  13844. int ret = WSACleanup();
  13845. ASSERT_EQ(0, ret);
  13846. }
  13847. #endif
  13848. #ifndef CPPHTTPLIB_SSL_ENABLED
  13849. TEST(NoSSLSupport, SimpleInterface) {
  13850. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13851. }
  13852. #endif
  13853. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13854. TEST(InvalidScheme, SimpleInterface) {
  13855. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13856. }
  13857. #endif
  13858. TEST(NoScheme, SimpleInterface) {
  13859. Client cli("yahoo.com:80");
  13860. ASSERT_TRUE(cli.is_valid());
  13861. }
  13862. TEST(SendAPI, SimpleInterface_Online) {
  13863. Client cli("http://yahoo.com");
  13864. Request req;
  13865. req.method = "GET";
  13866. req.path = "/";
  13867. auto res = cli.send(req);
  13868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13869. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13870. }
  13871. TEST(SendAPI, WithParamsInRequest) {
  13872. Server svr;
  13873. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13874. EXPECT_TRUE(req.has_param("test"));
  13875. EXPECT_EQ("test_value", req.get_param_value("test"));
  13876. });
  13877. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13878. auto se = detail::scope_exit([&] {
  13879. svr.stop();
  13880. t.join();
  13881. ASSERT_FALSE(svr.is_running());
  13882. });
  13883. svr.wait_until_ready();
  13884. Client cli(HOST, PORT);
  13885. {
  13886. Request req;
  13887. req.method = "GET";
  13888. req.path = "/";
  13889. req.params.emplace("test", "test_value");
  13890. auto res = cli.send(req);
  13891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13892. }
  13893. {
  13894. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13896. }
  13897. }
  13898. TEST(ClientImplMethods, GetSocketTest) {
  13899. httplib::Server svr;
  13900. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13901. res.status = StatusCode::OK_200;
  13902. });
  13903. auto port = svr.bind_to_any_port("127.0.0.1");
  13904. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13905. auto se = detail::scope_exit([&] {
  13906. svr.stop();
  13907. thread.join();
  13908. ASSERT_FALSE(svr.is_running());
  13909. });
  13910. svr.wait_until_ready();
  13911. {
  13912. httplib::Client cli("127.0.0.1", port);
  13913. cli.set_keep_alive(true);
  13914. // Use the behavior of cpp-httplib of opening the connection
  13915. // only when the first request happens. If that changes,
  13916. // this test would be obsolete.
  13917. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13918. // This also implicitly tests the server. But other tests would fail much
  13919. // earlier than this one to be considered.
  13920. auto res = cli.Get("/");
  13921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13922. EXPECT_EQ(StatusCode::OK_200, res->status);
  13923. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13924. }
  13925. }
  13926. #ifdef CPPHTTPLIB_SSL_ENABLED
  13927. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13928. Client cli("http://yahoo.com");
  13929. auto res = cli.Get("/");
  13930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13931. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13932. cli.set_follow_location(true);
  13933. res = cli.Get("/");
  13934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13935. EXPECT_EQ(StatusCode::OK_200, res->status);
  13936. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13937. }
  13938. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13939. Client cli("https://yahoo.com");
  13940. auto res = cli.Get("/");
  13941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13942. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13943. cli.set_follow_location(true);
  13944. res = cli.Get("/");
  13945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13946. EXPECT_EQ(StatusCode::OK_200, res->status);
  13947. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13948. }
  13949. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13950. Client cli("https://yahoo.com");
  13951. auto res = cli.Get("/");
  13952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13953. ASSERT_FALSE(!res);
  13954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13955. ASSERT_FALSE(res == nullptr);
  13956. ASSERT_TRUE(res != nullptr);
  13957. EXPECT_EQ(Error::Success, res.error());
  13958. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13959. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13960. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13961. cli.set_follow_location(true);
  13962. res = cli.Get("/");
  13963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13964. EXPECT_EQ(Error::Success, res.error());
  13965. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13966. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13967. EXPECT_EQ(StatusCode::OK_200, res->status);
  13968. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13969. }
  13970. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13971. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13972. Client cli("https://cdnjs.cloudflare.com");
  13973. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13974. Headers{{"Accept-Encoding", "br"}});
  13975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13976. EXPECT_EQ(StatusCode::OK_200, res->status);
  13977. EXPECT_EQ(287630U, res->body.size());
  13978. EXPECT_EQ("application/javascript; charset=utf-8",
  13979. res->get_header_value("Content-Type"));
  13980. }
  13981. #endif
  13982. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13983. #undef REDIR_HOST // Silence compiler warning
  13984. #define REDIR_HOST "https://httpbingo.org"
  13985. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13986. Client cli(REDIR_HOST);
  13987. cli.set_follow_location(true);
  13988. auto res =
  13989. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13991. EXPECT_EQ(StatusCode::OK_200, res->status);
  13992. }
  13993. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13994. Client cli(REDIR_HOST);
  13995. cli.set_follow_location(true);
  13996. Params params;
  13997. params.emplace("url", "http://example.com");
  13998. params.emplace("status_code", "302");
  13999. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14001. EXPECT_EQ(StatusCode::OK_200, res->status);
  14002. }
  14003. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14004. Client cli(REDIR_HOST);
  14005. cli.set_follow_location(true);
  14006. Params params;
  14007. params.emplace("url", "http://example.com");
  14008. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14010. EXPECT_EQ(StatusCode::OK_200, res->status);
  14011. }
  14012. TEST(HttpToHttpsRedirectTest, CertFile) {
  14013. auto ssl_port = PORT + 1;
  14014. Server svr;
  14015. ASSERT_TRUE(svr.is_valid());
  14016. svr.Get("/index", [&](const Request &, Response &res) {
  14017. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14018. "/index");
  14019. svr.stop();
  14020. });
  14021. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14022. ASSERT_TRUE(ssl_svr.is_valid());
  14023. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14024. res.set_content("test", "text/plain");
  14025. ssl_svr.stop();
  14026. });
  14027. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14028. thread t2 =
  14029. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14030. auto se = detail::scope_exit([&] {
  14031. t2.join();
  14032. t.join();
  14033. ASSERT_FALSE(svr.is_running());
  14034. });
  14035. svr.wait_until_ready();
  14036. ssl_svr.wait_until_ready();
  14037. Client cli("127.0.0.1", PORT);
  14038. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14039. cli.enable_server_certificate_verification(true);
  14040. cli.set_follow_location(true);
  14041. cli.set_connection_timeout(30);
  14042. auto res = cli.Get("/index");
  14043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14044. ASSERT_EQ(StatusCode::OK_200, res->status);
  14045. }
  14046. TEST(SSLClientRedirectTest, CertFile) {
  14047. auto ssl_port = PORT + 1;
  14048. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14049. ASSERT_TRUE(ssl_svr1.is_valid());
  14050. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14051. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14052. "/index");
  14053. ssl_svr1.stop();
  14054. });
  14055. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14056. ASSERT_TRUE(ssl_svr2.is_valid());
  14057. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14058. res.set_content("test", "text/plain");
  14059. ssl_svr2.stop();
  14060. });
  14061. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14062. thread t2 =
  14063. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14064. auto se = detail::scope_exit([&] {
  14065. t2.join();
  14066. t.join();
  14067. ASSERT_FALSE(ssl_svr1.is_running());
  14068. });
  14069. ssl_svr1.wait_until_ready();
  14070. ssl_svr2.wait_until_ready();
  14071. SSLClient cli("127.0.0.1", PORT);
  14072. std::string cert;
  14073. read_file(SERVER_CERT2_FILE, cert);
  14074. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14075. cli.enable_server_certificate_verification(true);
  14076. cli.set_follow_location(true);
  14077. cli.set_connection_timeout(30);
  14078. auto res = cli.Get("/index");
  14079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14080. ASSERT_EQ(StatusCode::OK_200, res->status);
  14081. }
  14082. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14083. // another port, so the client follows it with a new client.
  14084. static Result GetThroughTlsRedirectToDifferentPort(
  14085. const std::function<void(SSLClient &)> &setup,
  14086. const char *target_cert = SERVER_CERT2_FILE) {
  14087. auto ssl_port = PORT + 1;
  14088. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14089. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14090. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14091. "/index");
  14092. });
  14093. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14094. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14095. res.set_content("test", "text/plain");
  14096. });
  14097. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14098. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14099. auto se = detail::scope_exit([&] {
  14100. ssl_svr2.stop();
  14101. ssl_svr1.stop();
  14102. t2.join();
  14103. t.join();
  14104. });
  14105. ssl_svr1.wait_until_ready();
  14106. ssl_svr2.wait_until_ready();
  14107. SSLClient cli("127.0.0.1", PORT);
  14108. cli.set_follow_location(true);
  14109. cli.set_connection_timeout(30);
  14110. setup(cli);
  14111. return cli.Get("/index");
  14112. }
  14113. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14114. auto calls = 0;
  14115. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14116. cli.enable_server_certificate_verification(false);
  14117. // Accept the first server only.
  14118. cli.set_session_verifier([&](tls::session_t) {
  14119. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14120. : SSLVerifierResponse::CertificateRejected;
  14121. });
  14122. });
  14123. EXPECT_FALSE(res);
  14124. EXPECT_EQ(2, calls);
  14125. }
  14126. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14127. std::string pinned;
  14128. auto res = GetThroughTlsRedirectToDifferentPort(
  14129. [&](SSLClient &cli) {
  14130. cli.enable_server_certificate_verification(false);
  14131. // Pin the first certificate seen.
  14132. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14133. if (pinned.empty()) { pinned = ctx.serial(); }
  14134. return ctx.serial() == pinned;
  14135. });
  14136. },
  14137. // A certificate other than the first server's.
  14138. SERVER_CERT_FILE);
  14139. EXPECT_FALSE(res);
  14140. EXPECT_FALSE(pinned.empty());
  14141. }
  14142. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14143. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14144. std::string cert;
  14145. read_file(SERVER_CERT2_FILE, cert);
  14146. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14147. });
  14148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14149. EXPECT_EQ(StatusCode::OK_200, res->status);
  14150. }
  14151. #endif
  14152. #ifdef CPPHTTPLIB_SSL_ENABLED
  14153. // Test that set_ca_cert_store() skips system certs (consistent with
  14154. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14155. // should be trusted - system certs should NOT be loaded.
  14156. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14157. // Load a specific cert that is NOT a system CA cert
  14158. std::string cert;
  14159. read_file(SERVER_CERT2_FILE, cert);
  14160. SSLClient cli("google.com");
  14161. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14162. cli.enable_server_certificate_verification(true);
  14163. // This should FAIL because:
  14164. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14165. // 2. System certs should NOT be loaded when custom store is set
  14166. // If system certs WERE loaded, this would succeed
  14167. auto res = cli.Get("/");
  14168. ASSERT_FALSE(res);
  14169. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14170. }
  14171. // Same as above, but through the native store handle path. Regression test:
  14172. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14173. // merged system certs into the user-provided store.
  14174. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14175. std::string cert;
  14176. read_file(SERVER_CERT2_FILE, cert);
  14177. SSLClient cli("google.com");
  14178. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14179. cli.enable_server_certificate_verification(true);
  14180. auto res = cli.Get("/");
  14181. ASSERT_FALSE(res);
  14182. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14183. }
  14184. // A custom store set via the native handle must still verify a server whose
  14185. // cert it does contain.
  14186. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14187. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14188. ASSERT_TRUE(svr.is_valid());
  14189. svr.Get("/test", [&](const Request &, Response &res) {
  14190. res.set_content("test", "text/plain");
  14191. });
  14192. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14193. auto se = detail::scope_exit([&] {
  14194. svr.stop();
  14195. t.join();
  14196. ASSERT_FALSE(svr.is_running());
  14197. });
  14198. svr.wait_until_ready();
  14199. SSLClient cli("127.0.0.1", PORT);
  14200. std::string cert;
  14201. read_file(SERVER_CERT2_FILE, cert);
  14202. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14203. cli.enable_server_certificate_verification(true);
  14204. cli.set_connection_timeout(30);
  14205. auto res = cli.Get("/test");
  14206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14207. ASSERT_EQ(StatusCode::OK_200, res->status);
  14208. }
  14209. // CA certs loaded through the universal Client must be transferred to the
  14210. // client created internally for following an HTTPS redirect. Regression test:
  14211. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14212. // the CA data for redirect transfer.
  14213. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14214. auto ssl_port = PORT + 1;
  14215. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14216. ASSERT_TRUE(ssl_svr1.is_valid());
  14217. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14218. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14219. "/index");
  14220. });
  14221. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14222. ASSERT_TRUE(ssl_svr2.is_valid());
  14223. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14224. res.set_content("test", "text/plain");
  14225. });
  14226. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14227. thread t2 =
  14228. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14229. auto se = detail::scope_exit([&] {
  14230. ssl_svr2.stop();
  14231. ssl_svr1.stop();
  14232. t2.join();
  14233. t.join();
  14234. ASSERT_FALSE(ssl_svr1.is_running());
  14235. });
  14236. ssl_svr1.wait_until_ready();
  14237. ssl_svr2.wait_until_ready();
  14238. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14239. std::string cert;
  14240. read_file(SERVER_CERT2_FILE, cert);
  14241. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14242. cli.enable_server_certificate_verification(true);
  14243. cli.set_follow_location(true);
  14244. cli.set_connection_timeout(30);
  14245. auto res = cli.Get("/index");
  14246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14247. ASSERT_EQ(StatusCode::OK_200, res->status);
  14248. }
  14249. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14250. // so a host signed by a system CA verifies even though a custom CA is set
  14251. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14252. std::string cert;
  14253. read_file(SERVER_CERT2_FILE, cert);
  14254. SSLClient cli("google.com");
  14255. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14256. cli.enable_system_ca(true);
  14257. cli.enable_server_certificate_verification(true);
  14258. auto res = cli.Get("/");
  14259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14260. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14261. }
  14262. // The custom CA remains effective when combined with the system CA
  14263. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14264. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14265. ASSERT_TRUE(svr.is_valid());
  14266. svr.Get("/test", [&](const Request &, Response &res) {
  14267. res.set_content("test", "text/plain");
  14268. });
  14269. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14270. auto se = detail::scope_exit([&] {
  14271. svr.stop();
  14272. t.join();
  14273. ASSERT_FALSE(svr.is_running());
  14274. });
  14275. svr.wait_until_ready();
  14276. SSLClient cli("127.0.0.1", PORT);
  14277. std::string cert;
  14278. read_file(SERVER_CERT2_FILE, cert);
  14279. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14280. cli.enable_system_ca(true);
  14281. cli.enable_server_certificate_verification(true);
  14282. cli.set_connection_timeout(30);
  14283. auto res = cli.Get("/test");
  14284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14285. ASSERT_EQ(StatusCode::OK_200, res->status);
  14286. }
  14287. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14288. // skip chain verification entirely (only the certificate identity was
  14289. // checked), so a server presenting an untrusted certificate with a matching
  14290. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14291. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14292. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14293. ASSERT_TRUE(svr.is_valid());
  14294. svr.Get("/test", [&](const Request &, Response &res) {
  14295. res.set_content("test", "text/plain");
  14296. });
  14297. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14298. auto se = detail::scope_exit([&] {
  14299. svr.stop();
  14300. t.join();
  14301. ASSERT_FALSE(svr.is_running());
  14302. });
  14303. svr.wait_until_ready();
  14304. SSLClient cli("127.0.0.1", PORT);
  14305. std::string cert;
  14306. // A trusted CA that did not sign the server certificate. The server cert
  14307. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14308. // this connection.
  14309. read_file(CLIENT_CA_CERT_FILE, cert);
  14310. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14311. cli.enable_server_certificate_verification(true);
  14312. cli.set_connection_timeout(30);
  14313. auto res = cli.Get("/test");
  14314. ASSERT_FALSE(res);
  14315. }
  14316. // enable_system_ca(false) prevents system CA loading entirely
  14317. TEST(SSLClientTest, DisableSystemCa_Online) {
  14318. SSLClient cli("google.com");
  14319. cli.enable_system_ca(false);
  14320. cli.enable_server_certificate_verification(true);
  14321. auto res = cli.Get("/");
  14322. ASSERT_FALSE(res);
  14323. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14324. // itself when the CA chain is empty
  14325. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14326. res.error() == Error::SSLConnection);
  14327. }
  14328. // The universal Client forwards enable_system_ca()
  14329. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14330. std::string cert;
  14331. read_file(SERVER_CERT2_FILE, cert);
  14332. Client cli("https://google.com");
  14333. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14334. cli.enable_system_ca(true);
  14335. cli.enable_server_certificate_verification(true);
  14336. auto res = cli.Get("/");
  14337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14338. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14339. }
  14340. // The system CA policy must carry over to the client created internally for
  14341. // following a cross-host HTTPS redirect
  14342. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14343. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14344. ASSERT_TRUE(svr.is_valid());
  14345. svr.Get("/index", [&](const Request &, Response &res) {
  14346. res.set_redirect("https://www.google.com/");
  14347. });
  14348. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14349. auto se = detail::scope_exit([&] {
  14350. svr.stop();
  14351. t.join();
  14352. ASSERT_FALSE(svr.is_running());
  14353. });
  14354. svr.wait_until_ready();
  14355. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14356. std::string cert;
  14357. read_file(SERVER_CERT2_FILE, cert);
  14358. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14359. cli.enable_system_ca(true);
  14360. cli.enable_server_certificate_verification(true);
  14361. cli.set_follow_location(true);
  14362. cli.set_connection_timeout(30);
  14363. // Receiving any response proves the redirect client completed the TLS
  14364. // handshake with a system-CA-signed host
  14365. auto res = cli.Get("/index");
  14366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14367. }
  14368. TEST(MultipartFormDataTest, LargeData) {
  14369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14370. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14371. const ContentReader &content_reader) {
  14372. if (req.is_multipart_form_data()) {
  14373. std::vector<FormData> items;
  14374. content_reader(
  14375. [&](const FormData &file) {
  14376. items.push_back(file);
  14377. return true;
  14378. },
  14379. [&](const char *data, size_t data_length) {
  14380. items.back().content.append(data, data_length);
  14381. return true;
  14382. });
  14383. EXPECT_TRUE(std::string(items[0].name) == "document");
  14384. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14385. EXPECT_TRUE(items[0].filename == "2MB_data");
  14386. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14387. EXPECT_TRUE(items[1].name == "hello");
  14388. EXPECT_TRUE(items[1].content == "world");
  14389. EXPECT_TRUE(items[1].filename == "");
  14390. EXPECT_TRUE(items[1].content_type == "");
  14391. } else {
  14392. std::string body;
  14393. content_reader([&](const char *data, size_t data_length) {
  14394. body.append(data, data_length);
  14395. return true;
  14396. });
  14397. }
  14398. });
  14399. auto port = svr.bind_to_any_port(HOST);
  14400. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14401. auto se = detail::scope_exit([&] {
  14402. svr.stop();
  14403. t.join();
  14404. ASSERT_FALSE(svr.is_running());
  14405. });
  14406. svr.wait_until_ready();
  14407. {
  14408. std::string data(1024 * 1024 * 2, '.');
  14409. std::stringstream buffer;
  14410. buffer << data;
  14411. SSLClient cli(HOST, port);
  14412. cli.enable_server_certificate_verification(false);
  14413. UploadFormDataItems items{
  14414. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14415. {"hello", "world", "", ""},
  14416. };
  14417. auto res = cli.Post("/post", items);
  14418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14419. ASSERT_EQ(StatusCode::OK_200, res->status);
  14420. }
  14421. }
  14422. TEST(MultipartFormDataTest, DataProviderItems) {
  14423. std::random_device seed_gen;
  14424. std::mt19937 random(seed_gen());
  14425. std::string rand1;
  14426. rand1.resize(1000);
  14427. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14428. std::string rand2;
  14429. rand2.resize(3000);
  14430. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14431. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14432. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14433. const ContentReader &content_reader) {
  14434. ASSERT_FALSE(req.is_multipart_form_data());
  14435. std::string body;
  14436. content_reader([&](const char *data, size_t data_length) {
  14437. body.append(data, data_length);
  14438. return true;
  14439. });
  14440. EXPECT_EQ(body, "");
  14441. });
  14442. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14443. const ContentReader &content_reader) {
  14444. ASSERT_TRUE(req.is_multipart_form_data());
  14445. std::vector<FormData> items;
  14446. content_reader(
  14447. [&](const FormData &file) {
  14448. items.push_back(file);
  14449. return true;
  14450. },
  14451. [&](const char *data, size_t data_length) {
  14452. items.back().content.append(data, data_length);
  14453. return true;
  14454. });
  14455. ASSERT_TRUE(items.size() == 2);
  14456. EXPECT_EQ(std::string(items[0].name), "name1");
  14457. EXPECT_EQ(items[0].content, "Testing123");
  14458. EXPECT_EQ(items[0].filename, "filename1");
  14459. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14460. EXPECT_EQ(items[1].name, "name2");
  14461. EXPECT_EQ(items[1].content, "Testing456");
  14462. EXPECT_EQ(items[1].filename, "");
  14463. EXPECT_EQ(items[1].content_type, "");
  14464. });
  14465. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14466. const ContentReader &content_reader) {
  14467. ASSERT_TRUE(req.is_multipart_form_data());
  14468. std::vector<FormData> items;
  14469. content_reader(
  14470. [&](const FormData &file) {
  14471. items.push_back(file);
  14472. return true;
  14473. },
  14474. [&](const char *data, size_t data_length) {
  14475. items.back().content.append(data, data_length);
  14476. return true;
  14477. });
  14478. ASSERT_TRUE(items.size() == 2);
  14479. EXPECT_EQ(items[0].name, "name3");
  14480. EXPECT_EQ(items[0].content, rand1);
  14481. EXPECT_EQ(items[0].filename, "filename3");
  14482. EXPECT_EQ(items[0].content_type, "");
  14483. EXPECT_EQ(items[1].name, "name4");
  14484. EXPECT_EQ(items[1].content, rand2);
  14485. EXPECT_EQ(items[1].filename, "filename4");
  14486. EXPECT_EQ(items[1].content_type, "");
  14487. });
  14488. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14489. const ContentReader &content_reader) {
  14490. ASSERT_TRUE(req.is_multipart_form_data());
  14491. std::vector<FormData> items;
  14492. content_reader(
  14493. [&](const FormData &file) {
  14494. items.push_back(file);
  14495. return true;
  14496. },
  14497. [&](const char *data, size_t data_length) {
  14498. items.back().content.append(data, data_length);
  14499. return true;
  14500. });
  14501. ASSERT_TRUE(items.size() == 4);
  14502. EXPECT_EQ(std::string(items[0].name), "name1");
  14503. EXPECT_EQ(items[0].content, "Testing123");
  14504. EXPECT_EQ(items[0].filename, "filename1");
  14505. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14506. EXPECT_EQ(items[1].name, "name2");
  14507. EXPECT_EQ(items[1].content, "Testing456");
  14508. EXPECT_EQ(items[1].filename, "");
  14509. EXPECT_EQ(items[1].content_type, "");
  14510. EXPECT_EQ(items[2].name, "name3");
  14511. EXPECT_EQ(items[2].content, rand1);
  14512. EXPECT_EQ(items[2].filename, "filename3");
  14513. EXPECT_EQ(items[2].content_type, "");
  14514. EXPECT_EQ(items[3].name, "name4");
  14515. EXPECT_EQ(items[3].content, rand2);
  14516. EXPECT_EQ(items[3].filename, "filename4");
  14517. EXPECT_EQ(items[3].content_type, "");
  14518. });
  14519. auto port = svr.bind_to_any_port("localhost");
  14520. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14521. auto se = detail::scope_exit([&] {
  14522. svr.stop();
  14523. t.join();
  14524. ASSERT_FALSE(svr.is_running());
  14525. });
  14526. svr.wait_until_ready();
  14527. {
  14528. SSLClient cli("localhost", port);
  14529. cli.enable_server_certificate_verification(false);
  14530. UploadFormDataItems items{
  14531. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14532. {"name2", "Testing456", "", ""}, // not a file
  14533. };
  14534. {
  14535. auto res = cli.Post("/post-none", {}, {}, {});
  14536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14537. ASSERT_EQ(StatusCode::OK_200, res->status);
  14538. }
  14539. FormDataProviderItems providers;
  14540. {
  14541. auto res =
  14542. cli.Post("/post-items", {}, items, providers); // empty providers
  14543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14544. ASSERT_EQ(StatusCode::OK_200, res->status);
  14545. }
  14546. providers.push_back({"name3",
  14547. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14548. // test the offset is given correctly at each step
  14549. if (!offset)
  14550. sink.os.write(rand1.data(), 30);
  14551. else if (offset == 30)
  14552. sink.os.write(rand1.data() + 30, 300);
  14553. else if (offset == 330)
  14554. sink.os.write(rand1.data() + 330, 670);
  14555. else if (offset == rand1.size())
  14556. sink.done();
  14557. return true;
  14558. },
  14559. "filename3",
  14560. {}});
  14561. providers.push_back({"name4",
  14562. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14563. // test the offset is given correctly at each step
  14564. if (!offset)
  14565. sink.os.write(rand2.data(), 2000);
  14566. else if (offset == 2000)
  14567. sink.os.write(rand2.data() + 2000, 1);
  14568. else if (offset == 2001)
  14569. sink.os.write(rand2.data() + 2001, 999);
  14570. else if (offset == rand2.size())
  14571. sink.done();
  14572. return true;
  14573. },
  14574. "filename4",
  14575. {}});
  14576. {
  14577. auto res = cli.Post("/post-providers", {}, {}, providers);
  14578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14579. ASSERT_EQ(StatusCode::OK_200, res->status);
  14580. }
  14581. {
  14582. auto res = cli.Post("/post-both", {}, items, providers);
  14583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14584. ASSERT_EQ(StatusCode::OK_200, res->status);
  14585. }
  14586. }
  14587. }
  14588. TEST(MultipartFormDataTest, BadHeader) {
  14589. Server svr;
  14590. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14591. res.set_content("ok", "text/plain");
  14592. });
  14593. thread t = thread([&] { svr.listen(HOST, PORT); });
  14594. auto se = detail::scope_exit([&] {
  14595. svr.stop();
  14596. t.join();
  14597. ASSERT_FALSE(svr.is_running());
  14598. });
  14599. svr.wait_until_ready();
  14600. const std::string body =
  14601. "This is the preamble. It is to be ignored, though it\r\n"
  14602. "is a handy place for composition agents to include an\r\n"
  14603. "explanatory note to non-MIME conformant readers.\r\n"
  14604. "\r\n"
  14605. "\r\n"
  14606. "--simple boundary\r\n"
  14607. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14608. ": BAD...\r\n"
  14609. "\r\n"
  14610. "value1\r\n"
  14611. "--simple boundary\r\n"
  14612. "Content-Disposition: form-data; name=\"field2\"; "
  14613. "filename=\"example.txt\"\r\n"
  14614. "\r\n"
  14615. "value2\r\n"
  14616. "--simple boundary--\r\n"
  14617. "This is the epilogue. It is also to be ignored.\r\n";
  14618. std::string content_type =
  14619. R"(multipart/form-data; boundary="simple boundary")";
  14620. Client cli(HOST, PORT);
  14621. auto res = cli.Post("/post", body, content_type.c_str());
  14622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14623. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14624. }
  14625. TEST(MultipartFormDataTest, WithPreamble) {
  14626. Server svr;
  14627. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14628. res.set_content("ok", "text/plain");
  14629. });
  14630. thread t = thread([&] { svr.listen(HOST, PORT); });
  14631. auto se = detail::scope_exit([&] {
  14632. svr.stop();
  14633. t.join();
  14634. ASSERT_FALSE(svr.is_running());
  14635. });
  14636. svr.wait_until_ready();
  14637. const std::string body =
  14638. "This is the preamble. It is to be ignored, though it\r\n"
  14639. "is a handy place for composition agents to include an\r\n"
  14640. "explanatory note to non-MIME conformant readers.\r\n"
  14641. "\r\n"
  14642. "\r\n"
  14643. "--simple boundary\r\n"
  14644. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14645. "\r\n"
  14646. "value1\r\n"
  14647. "--simple boundary\r\n"
  14648. "Content-Disposition: form-data; name=\"field2\"; "
  14649. "filename=\"example.txt\"\r\n"
  14650. "\r\n"
  14651. "value2\r\n"
  14652. "--simple boundary--\r\n"
  14653. "This is the epilogue. It is also to be ignored.\r\n";
  14654. std::string content_type =
  14655. R"(multipart/form-data; boundary="simple boundary")";
  14656. Client cli(HOST, PORT);
  14657. auto res = cli.Post("/post", body, content_type.c_str());
  14658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14659. EXPECT_EQ(StatusCode::OK_200, res->status);
  14660. }
  14661. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14662. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14663. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14664. const ContentReader &content_reader) {
  14665. if (req.is_multipart_form_data()) {
  14666. std::vector<FormData> items;
  14667. content_reader(
  14668. [&](const FormData &file) {
  14669. items.push_back(file);
  14670. return true;
  14671. },
  14672. [&](const char *data, size_t data_length) {
  14673. items.back().content.append(data, data_length);
  14674. return true;
  14675. });
  14676. EXPECT_TRUE(std::string(items[0].name) == "document");
  14677. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14678. EXPECT_TRUE(items[0].filename == "2MB_data");
  14679. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14680. EXPECT_TRUE(items[1].name == "hello");
  14681. EXPECT_TRUE(items[1].content == "world");
  14682. EXPECT_TRUE(items[1].filename == "");
  14683. EXPECT_TRUE(items[1].content_type == "");
  14684. } else {
  14685. std::string body;
  14686. content_reader([&](const char *data, size_t data_length) {
  14687. body.append(data, data_length);
  14688. return true;
  14689. });
  14690. }
  14691. });
  14692. auto port = svr.bind_to_any_port("localhost");
  14693. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14694. auto se = detail::scope_exit([&] {
  14695. svr.stop();
  14696. t.join();
  14697. ASSERT_FALSE(svr.is_running());
  14698. });
  14699. svr.wait_until_ready();
  14700. {
  14701. std::string data(1024 * 1024 * 2, '.');
  14702. std::stringstream buffer;
  14703. buffer << data;
  14704. SSLClient cli("localhost", port);
  14705. cli.enable_server_certificate_verification(false);
  14706. UploadFormDataItems items{
  14707. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14708. {"hello", "world", "", ""},
  14709. };
  14710. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14712. ASSERT_EQ(StatusCode::OK_200, res->status);
  14713. }
  14714. }
  14715. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14716. std::string data(1024 * 1024 * 2, '&');
  14717. std::stringstream buffer;
  14718. buffer << data;
  14719. Client cli("https://localhost:8080");
  14720. UploadFormDataItems items{
  14721. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14722. {"hello", "world", "", ""},
  14723. };
  14724. for (const char &c : " \t\r\n") {
  14725. auto res =
  14726. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14727. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14728. ASSERT_FALSE(res);
  14729. }
  14730. }
  14731. TEST(MultipartFormDataTest, PutFormData) {
  14732. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14733. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14734. const ContentReader &content_reader) {
  14735. if (req.is_multipart_form_data()) {
  14736. std::vector<FormData> items;
  14737. content_reader(
  14738. [&](const FormData &file) {
  14739. items.push_back(file);
  14740. return true;
  14741. },
  14742. [&](const char *data, size_t data_length) {
  14743. items.back().content.append(data, data_length);
  14744. return true;
  14745. });
  14746. EXPECT_TRUE(std::string(items[0].name) == "document");
  14747. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14748. EXPECT_TRUE(items[0].filename == "2MB_data");
  14749. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14750. EXPECT_TRUE(items[1].name == "hello");
  14751. EXPECT_TRUE(items[1].content == "world");
  14752. EXPECT_TRUE(items[1].filename == "");
  14753. EXPECT_TRUE(items[1].content_type == "");
  14754. } else {
  14755. std::string body;
  14756. content_reader([&](const char *data, size_t data_length) {
  14757. body.append(data, data_length);
  14758. return true;
  14759. });
  14760. }
  14761. });
  14762. auto port = svr.bind_to_any_port("localhost");
  14763. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14764. auto se = detail::scope_exit([&] {
  14765. svr.stop();
  14766. t.join();
  14767. ASSERT_FALSE(svr.is_running());
  14768. });
  14769. svr.wait_until_ready();
  14770. {
  14771. std::string data(1024 * 1024 * 2, '&');
  14772. std::stringstream buffer;
  14773. buffer << data;
  14774. SSLClient cli("localhost", port);
  14775. cli.enable_server_certificate_verification(false);
  14776. UploadFormDataItems items{
  14777. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14778. {"hello", "world", "", ""},
  14779. };
  14780. auto res = cli.Put("/put", items);
  14781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14782. ASSERT_EQ(StatusCode::OK_200, res->status);
  14783. }
  14784. }
  14785. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14786. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14787. svr.Put("/put_customboundary",
  14788. [&](const Request &req, const Response & /*res*/,
  14789. const ContentReader &content_reader) {
  14790. if (req.is_multipart_form_data()) {
  14791. std::vector<FormData> items;
  14792. content_reader(
  14793. [&](const FormData &file) {
  14794. items.push_back(file);
  14795. return true;
  14796. },
  14797. [&](const char *data, size_t data_length) {
  14798. items.back().content.append(data, data_length);
  14799. return true;
  14800. });
  14801. EXPECT_TRUE(std::string(items[0].name) == "document");
  14802. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14803. EXPECT_TRUE(items[0].filename == "2MB_data");
  14804. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14805. EXPECT_TRUE(items[1].name == "hello");
  14806. EXPECT_TRUE(items[1].content == "world");
  14807. EXPECT_TRUE(items[1].filename == "");
  14808. EXPECT_TRUE(items[1].content_type == "");
  14809. } else {
  14810. std::string body;
  14811. content_reader([&](const char *data, size_t data_length) {
  14812. body.append(data, data_length);
  14813. return true;
  14814. });
  14815. }
  14816. });
  14817. auto port = svr.bind_to_any_port("localhost");
  14818. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14819. auto se = detail::scope_exit([&] {
  14820. svr.stop();
  14821. t.join();
  14822. ASSERT_FALSE(svr.is_running());
  14823. });
  14824. svr.wait_until_ready();
  14825. {
  14826. std::string data(1024 * 1024 * 2, '&');
  14827. std::stringstream buffer;
  14828. buffer << data;
  14829. SSLClient cli("localhost", port);
  14830. cli.enable_server_certificate_verification(false);
  14831. UploadFormDataItems items{
  14832. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14833. {"hello", "world", "", ""},
  14834. };
  14835. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14837. ASSERT_EQ(StatusCode::OK_200, res->status);
  14838. }
  14839. }
  14840. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14841. std::string data(1024 * 1024 * 2, '&');
  14842. std::stringstream buffer;
  14843. buffer << data;
  14844. Client cli("https://localhost:8080");
  14845. cli.enable_server_certificate_verification(false);
  14846. UploadFormDataItems items{
  14847. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14848. {"hello", "world", "", ""},
  14849. };
  14850. for (const char &c : " \t\r\n") {
  14851. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14852. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14853. ASSERT_FALSE(res);
  14854. }
  14855. }
  14856. TEST(MultipartFormDataTest, AlternateFilename) {
  14857. auto handled = false;
  14858. Server svr;
  14859. svr.Post("/test", [&](const Request &req, Response &res) {
  14860. ASSERT_EQ(2u, req.form.files.size());
  14861. ASSERT_EQ(1u, req.form.fields.size());
  14862. // Test files
  14863. const auto &file1 = req.form.get_file("file1");
  14864. ASSERT_EQ("file1", file1.name);
  14865. ASSERT_EQ("A.txt", file1.filename);
  14866. ASSERT_EQ("text/plain", file1.content_type);
  14867. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14868. const auto &file2 = req.form.get_file("file2");
  14869. ASSERT_EQ("file2", file2.name);
  14870. ASSERT_EQ("a.html", file2.filename);
  14871. ASSERT_EQ("text/html", file2.content_type);
  14872. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14873. file2.content);
  14874. // Test text field
  14875. const auto &text = req.form.get_field("text");
  14876. ASSERT_EQ("text default", text);
  14877. res.set_content("ok", "text/plain");
  14878. handled = true;
  14879. });
  14880. thread t = thread([&] { svr.listen(HOST, PORT); });
  14881. auto se = detail::scope_exit([&] {
  14882. svr.stop();
  14883. t.join();
  14884. ASSERT_FALSE(svr.is_running());
  14885. ASSERT_TRUE(handled);
  14886. });
  14887. svr.wait_until_ready();
  14888. auto req = "POST /test HTTP/1.1\r\n"
  14889. "Host: localhost\r\n"
  14890. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14891. "Content-Length: 399\r\n"
  14892. "\r\n"
  14893. "----------\r\n"
  14894. "Content-Disposition: form-data; name=\"text\"\r\n"
  14895. "\r\n"
  14896. "text default\r\n"
  14897. "----------\r\n"
  14898. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14899. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14900. "Content-Type: text/plain\r\n"
  14901. "\r\n"
  14902. "Content of a.txt.\r\n"
  14903. "\r\n"
  14904. "----------\r\n"
  14905. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14906. "\"a.html\"\r\n"
  14907. "Content-Type: text/html\r\n"
  14908. "\r\n"
  14909. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14910. "\r\n"
  14911. "------------\r\n";
  14912. ASSERT_TRUE(send_request(1, req));
  14913. }
  14914. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14915. auto handled = false;
  14916. Server svr;
  14917. svr.Post("/test", [&](const Request &req, Response &res) {
  14918. // Case-insensitive "utf-8''" prefix with a long value
  14919. const auto &file = req.form.get_file("file1");
  14920. ASSERT_EQ("file1", file.name);
  14921. // 8000 chars exercises both the Content-Disposition parser and the
  14922. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14923. // Prior to the fix, std::regex_match on this header would cause O(N)
  14924. // stack recursion in libstdc++, leading to SIGSEGV.
  14925. std::string expected_filename(8000, 'A');
  14926. ASSERT_EQ(expected_filename, file.filename);
  14927. res.set_content("ok", "text/plain");
  14928. handled = true;
  14929. });
  14930. thread t = thread([&] { svr.listen(HOST, PORT); });
  14931. auto se = detail::scope_exit([&] {
  14932. svr.stop();
  14933. t.join();
  14934. ASSERT_FALSE(svr.is_running());
  14935. ASSERT_TRUE(handled);
  14936. });
  14937. svr.wait_until_ready();
  14938. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14939. // Regression test for GHSA-qq6v-r583-3h69
  14940. std::string long_filename(8000, 'A');
  14941. std::string body = "----------\r\n"
  14942. "Content-Disposition: form-data; name=\"file1\"; "
  14943. "filename*=\"Utf-8''" +
  14944. long_filename +
  14945. "\"\r\n"
  14946. "\r\n"
  14947. "hello\r\n"
  14948. "------------\r\n";
  14949. auto req = "POST /test HTTP/1.1\r\n"
  14950. "Host: localhost\r\n"
  14951. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14952. "Content-Length: " +
  14953. std::to_string(body.size()) + "\r\n\r\n" + body;
  14954. ASSERT_TRUE(send_request(1, req));
  14955. }
  14956. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14957. auto handled = false;
  14958. Server svr;
  14959. svr.Post("/test", [&](const Request &req, Response &) {
  14960. ASSERT_EQ(2u, req.form.fields.size());
  14961. const auto &text1 = req.form.get_field("text1");
  14962. ASSERT_EQ("text1", text1);
  14963. const auto &text2 = req.form.get_field("text2");
  14964. ASSERT_EQ("text2", text2);
  14965. handled = true;
  14966. });
  14967. thread t = thread([&] { svr.listen(HOST, PORT); });
  14968. auto se = detail::scope_exit([&] {
  14969. svr.stop();
  14970. t.join();
  14971. ASSERT_FALSE(svr.is_running());
  14972. ASSERT_TRUE(handled);
  14973. });
  14974. svr.wait_until_ready();
  14975. auto req = "POST /test HTTP/1.1\r\n"
  14976. "Host: localhost\r\n"
  14977. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14978. "Content-Length: 146\r\n"
  14979. "\r\n----------\r\n"
  14980. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14981. "\r\n"
  14982. "text1"
  14983. "\r\n----------\r\n"
  14984. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14985. "\r\n"
  14986. "text2"
  14987. "\r\n------------";
  14988. std::string response;
  14989. ASSERT_TRUE(send_request(1, req, &response));
  14990. ASSERT_EQ("200", response.substr(9, 3));
  14991. }
  14992. TEST(MultipartFormDataTest, ContentLength) {
  14993. auto handled = false;
  14994. Server svr;
  14995. svr.Post("/test", [&](const Request &req, Response &) {
  14996. ASSERT_EQ(2u, req.form.fields.size());
  14997. const auto &text1 = req.form.get_field("text1");
  14998. ASSERT_EQ("text1", text1);
  14999. const auto &text2 = req.form.get_field("text2");
  15000. ASSERT_EQ("text2", text2);
  15001. handled = true;
  15002. });
  15003. thread t = thread([&] { svr.listen(HOST, PORT); });
  15004. auto se = detail::scope_exit([&] {
  15005. svr.stop();
  15006. t.join();
  15007. ASSERT_FALSE(svr.is_running());
  15008. ASSERT_TRUE(handled);
  15009. });
  15010. svr.wait_until_ready();
  15011. auto req = "POST /test HTTP/1.1\r\n"
  15012. "Host: localhost\r\n"
  15013. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15014. "Content-Length: 167\r\n"
  15015. "\r\n----------\r\n"
  15016. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15017. "Content-Length: 5\r\n"
  15018. "\r\n"
  15019. "text1"
  15020. "\r\n----------\r\n"
  15021. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15022. "\r\n"
  15023. "text2"
  15024. "\r\n------------\r\n";
  15025. std::string response;
  15026. ASSERT_TRUE(send_request(1, req, &response));
  15027. ASSERT_EQ("200", response.substr(9, 3));
  15028. }
  15029. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15030. auto handled = false;
  15031. Server svr;
  15032. svr.Post("/test", [&](const Request &req, Response &) {
  15033. ASSERT_EQ(2u, req.form.fields.size());
  15034. const auto &text1 = req.form.get_field("text1");
  15035. ASSERT_EQ("text1", text1);
  15036. // TODO: Add header access for text fields if needed
  15037. const auto &text2 = req.form.get_field("text2");
  15038. ASSERT_EQ("text2", text2);
  15039. // TODO: Header access for text fields needs to be implemented
  15040. // auto &headers = it->second.headers;
  15041. // ASSERT_EQ(3U, headers.size());
  15042. // auto custom_header = headers.find("x-whatever");
  15043. // ASSERT_TRUE(custom_header != headers.end());
  15044. // ASSERT_NE("customvalue", custom_header->second);
  15045. // ASSERT_EQ("CustomValue", custom_header->second);
  15046. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15047. handled = true;
  15048. });
  15049. thread t = thread([&] { svr.listen(HOST, PORT); });
  15050. auto se = detail::scope_exit([&] {
  15051. svr.stop();
  15052. t.join();
  15053. ASSERT_FALSE(svr.is_running());
  15054. ASSERT_TRUE(handled);
  15055. });
  15056. svr.wait_until_ready();
  15057. auto req = "POST /test HTTP/1.1\r\n"
  15058. "Host: localhost\r\n"
  15059. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15060. "Content-Length: 232\r\n"
  15061. "\r\n----------\r\n"
  15062. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15063. "Content-Length: 5\r\n"
  15064. "X-Test: 1\r\n"
  15065. "\r\n"
  15066. "text1"
  15067. "\r\n----------\r\n"
  15068. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15069. "Content-Type: text/plain\r\n"
  15070. "X-Whatever: CustomValue\r\n"
  15071. "\r\n"
  15072. "text2"
  15073. "\r\n------------\r\n"
  15074. "That should be disregarded. Not even read";
  15075. std::string response;
  15076. ASSERT_TRUE(send_request(1, req, &response));
  15077. ASSERT_EQ("200", response.substr(9, 3));
  15078. }
  15079. TEST(MultipartFormDataTest, LargeHeader) {
  15080. auto handled = false;
  15081. Server svr;
  15082. svr.Post("/test", [&](const Request &req, Response &) {
  15083. ASSERT_EQ(1u, req.form.fields.size());
  15084. const auto &text = req.form.get_field("name1");
  15085. ASSERT_EQ("text1", text);
  15086. handled = true;
  15087. });
  15088. thread t = thread([&] { svr.listen(HOST, PORT); });
  15089. auto se = detail::scope_exit([&] {
  15090. svr.stop();
  15091. t.join();
  15092. ASSERT_FALSE(svr.is_running());
  15093. ASSERT_TRUE(handled);
  15094. });
  15095. svr.wait_until_ready();
  15096. auto boundary = std::string("cpp-httplib-multipart-data");
  15097. std::string content = "--" + boundary +
  15098. "\r\n"
  15099. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15100. "\r\n"
  15101. "text1\r\n"
  15102. "--" +
  15103. boundary + "--\r\n";
  15104. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15105. "Host: localhost\r\n"
  15106. "Content-Type: multipart/form-data;boundary=" +
  15107. boundary +
  15108. "\r\n"
  15109. "Content-Length: " +
  15110. std::to_string(content.size()) +
  15111. "\r\n"
  15112. "Dummy-Header: ";
  15113. std::string header_suffix = "\r\n"
  15114. "\r\n";
  15115. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15116. size_t header_dummy_size =
  15117. read_buff_size -
  15118. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15119. auto header_dummy = std::string(header_dummy_size, '@');
  15120. auto req = header_prefix + header_dummy + header_suffix + content;
  15121. std::string response;
  15122. ASSERT_TRUE(send_request(1, req, &response));
  15123. ASSERT_EQ("200", response.substr(9, 3));
  15124. }
  15125. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15126. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15127. // (not chunked Transfer-Encoding) after the streaming refactor.
  15128. auto handled = false;
  15129. Server svr;
  15130. svr.Post("/upload", [&](const Request &req, Response &res) {
  15131. auto cl_it = req.headers.find("Content-Length");
  15132. EXPECT_TRUE(cl_it != req.headers.end());
  15133. auto te_it = req.headers.find("Transfer-Encoding");
  15134. EXPECT_TRUE(te_it == req.headers.end());
  15135. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15136. res.set_content("ok", "text/plain");
  15137. handled = true;
  15138. });
  15139. auto port = svr.bind_to_any_port(HOST);
  15140. auto t = thread([&] { svr.listen_after_bind(); });
  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. UploadFormDataItems items = {
  15149. {"field1", "hello", "", "text/plain"},
  15150. {"file1", "world", "test.txt", "application/octet-stream"},
  15151. };
  15152. Client cli(HOST, port);
  15153. auto res = cli.Post("/upload", {}, items);
  15154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15155. EXPECT_EQ(StatusCode::OK_200, res->status);
  15156. }
  15157. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15158. // Verify that make_multipart_content_provider coalesces many small segments
  15159. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15160. constexpr size_t kItemCount = 1000;
  15161. UploadFormDataItems items;
  15162. items.reserve(kItemCount);
  15163. for (size_t i = 0; i < kItemCount; i++) {
  15164. items.push_back(
  15165. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15166. }
  15167. const std::string boundary = "----test-boundary";
  15168. auto content_length = detail::get_multipart_content_length(items, boundary);
  15169. auto provider = detail::make_multipart_content_provider(items, boundary);
  15170. // Drive the provider the same way write_content_with_progress does
  15171. size_t write_count = 0;
  15172. size_t total_bytes = 0;
  15173. DataSink sink;
  15174. size_t offset = 0;
  15175. sink.write = [&](const char *d, size_t l) -> bool {
  15176. (void)d;
  15177. write_count++;
  15178. total_bytes += l;
  15179. offset += l;
  15180. return true;
  15181. };
  15182. sink.is_writable = []() -> bool { return true; };
  15183. while (offset < content_length) {
  15184. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15185. }
  15186. EXPECT_EQ(content_length, total_bytes);
  15187. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15188. // With buffering into 64KB blocks, write_count should be much smaller.
  15189. auto segment_count = 3 * kItemCount + 1;
  15190. EXPECT_LT(write_count, segment_count / 10);
  15191. }
  15192. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15193. // Integration test: send many UploadFormDataItems and verify the server
  15194. // receives all of them correctly (#2410).
  15195. constexpr size_t kItemCount = 500;
  15196. auto handled = false;
  15197. Server svr;
  15198. svr.Post("/upload", [&](const Request &req, Response &res) {
  15199. EXPECT_EQ(kItemCount, req.form.fields.size());
  15200. for (size_t i = 0; i < kItemCount; i++) {
  15201. auto key = "field" + std::to_string(i);
  15202. auto val = "value" + std::to_string(i);
  15203. auto it = req.form.fields.find(key);
  15204. if (it != req.form.fields.end()) {
  15205. EXPECT_EQ(val, it->second.content);
  15206. } else {
  15207. ADD_FAILURE() << "Missing field: " << key;
  15208. }
  15209. }
  15210. res.set_content("ok", "text/plain");
  15211. handled = true;
  15212. });
  15213. auto port = svr.bind_to_any_port(HOST);
  15214. auto t = thread([&] { svr.listen_after_bind(); });
  15215. auto se = detail::scope_exit([&] {
  15216. svr.stop();
  15217. t.join();
  15218. ASSERT_FALSE(svr.is_running());
  15219. ASSERT_TRUE(handled);
  15220. });
  15221. svr.wait_until_ready();
  15222. UploadFormDataItems items;
  15223. items.reserve(kItemCount);
  15224. for (size_t i = 0; i < kItemCount; i++) {
  15225. items.push_back(
  15226. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15227. }
  15228. Client cli(HOST, port);
  15229. auto res = cli.Post("/upload", items);
  15230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15231. EXPECT_EQ(StatusCode::OK_200, res->status);
  15232. }
  15233. TEST(MultipartFormDataTest, MakeFileProvider) {
  15234. // Verify make_file_provider sends a file's contents correctly.
  15235. const std::string file_content(4096, 'Z');
  15236. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15237. {
  15238. std::ofstream ofs(tmp_path, std::ios::binary);
  15239. ofs.write(file_content.data(),
  15240. static_cast<std::streamsize>(file_content.size()));
  15241. }
  15242. auto handled = false;
  15243. Server svr;
  15244. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15245. const ContentReader &content_reader) {
  15246. ASSERT_TRUE(req.is_multipart_form_data());
  15247. std::vector<FormData> items;
  15248. content_reader(
  15249. [&](const FormData &file) {
  15250. items.push_back(file);
  15251. return true;
  15252. },
  15253. [&](const char *data, size_t data_length) {
  15254. items.back().content.append(data, data_length);
  15255. return true;
  15256. });
  15257. ASSERT_EQ(1u, items.size());
  15258. EXPECT_EQ("myfile", items[0].name);
  15259. EXPECT_EQ("data.bin", items[0].filename);
  15260. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15261. EXPECT_EQ(file_content, items[0].content);
  15262. handled = true;
  15263. });
  15264. auto port = svr.bind_to_any_port(HOST);
  15265. auto t = thread([&] { svr.listen_after_bind(); });
  15266. auto se = detail::scope_exit([&] {
  15267. svr.stop();
  15268. t.join();
  15269. ASSERT_FALSE(svr.is_running());
  15270. ASSERT_TRUE(handled);
  15271. std::remove(tmp_path.c_str());
  15272. });
  15273. svr.wait_until_ready();
  15274. FormDataProviderItems providers;
  15275. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15276. "application/octet-stream"));
  15277. Client cli(HOST, port);
  15278. auto res = cli.Post("/upload", {}, {}, providers);
  15279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15280. EXPECT_EQ(StatusCode::OK_200, res->status);
  15281. }
  15282. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15283. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15284. // (100) headers is rejected with a 400 Bad Request response.
  15285. Server svr;
  15286. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15287. res.set_content("ok", "text/plain");
  15288. });
  15289. thread t = thread([&] { svr.listen(HOST, PORT); });
  15290. auto se = detail::scope_exit([&] {
  15291. svr.stop();
  15292. t.join();
  15293. ASSERT_FALSE(svr.is_running());
  15294. });
  15295. svr.wait_until_ready();
  15296. // Build a multipart part with 101 custom headers (exceeding
  15297. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15298. std::stringstream body;
  15299. body << "--simpleboundary\r\n"
  15300. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15301. for (int i = 0; i < 101; i++) {
  15302. body << "X-Custom-Header-" << i << ": value\r\n";
  15303. }
  15304. body << "\r\n"
  15305. << "value1\r\n"
  15306. << "--simpleboundary--\r\n";
  15307. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15308. Client cli(HOST, PORT);
  15309. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15311. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15312. }
  15313. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15314. // A body that never contains the declared boundary must not be accumulated
  15315. // while the parser waits for it. Buffering it would also make every read
  15316. // rescan everything seen so far, which is quadratic in the body size.
  15317. Server svr;
  15318. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15319. res.set_content("ok", "text/plain");
  15320. });
  15321. auto port = svr.bind_to_any_port(HOST);
  15322. thread t = thread([&] { svr.listen_after_bind(); });
  15323. auto se = detail::scope_exit([&] {
  15324. svr.stop();
  15325. t.join();
  15326. ASSERT_FALSE(svr.is_running());
  15327. });
  15328. svr.wait_until_ready();
  15329. Client cli(HOST, port);
  15330. cli.set_read_timeout(60, 0);
  15331. cli.set_write_timeout(60, 0);
  15332. // '-' is the worst case: it matches the first character of the boundary, so
  15333. // every position has to be checked against it.
  15334. auto post_dashes = [&](size_t size) {
  15335. const std::string body(size, '-');
  15336. auto start = std::chrono::steady_clock::now();
  15337. auto res =
  15338. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15339. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15340. std::chrono::steady_clock::now() - start)
  15341. .count();
  15342. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15343. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15344. return ms;
  15345. };
  15346. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15347. // Windows.
  15348. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15349. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15350. // Comparing the two sizes rather than checking an absolute duration keeps
  15351. // this meaningful across build types and CI load, both of which move the
  15352. // absolute numbers by more than an order of magnitude. Four times the bytes
  15353. // costs about four times the time when parsing is linear, and about sixteen
  15354. // times when the body is buffered and rescanned.
  15355. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15356. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15357. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15358. << "ms, which suggests the body is being buffered and rescanned";
  15359. }
  15360. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15361. // A boundary can only be followed by CRLF or by "--", so anything else is
  15362. // malformed no matter what comes next. The parser must say so right away
  15363. // instead of buffering the rest of the declared body.
  15364. Server svr;
  15365. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15366. res.set_content("ok", "text/plain");
  15367. });
  15368. auto port = svr.bind_to_any_port(HOST);
  15369. thread t = thread([&] { svr.listen_after_bind(); });
  15370. auto se = detail::scope_exit([&] {
  15371. svr.stop();
  15372. t.join();
  15373. ASSERT_FALSE(svr.is_running());
  15374. });
  15375. svr.wait_until_ready();
  15376. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15377. // buffers instead of failing would still be waiting for the remaining bytes.
  15378. const std::string body = "--zzzz\r\n"
  15379. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15380. "\r\n"
  15381. "text1"
  15382. "\r\n--zzzzXX";
  15383. const std::string req = "POST /post HTTP/1.1\r\n"
  15384. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15385. "Content-Length: 1048576\r\n"
  15386. "\r\n" +
  15387. body;
  15388. std::string response;
  15389. ASSERT_TRUE(send_request(3, req, &response, port));
  15390. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15391. EXPECT_EQ("400", response.substr(9, 3));
  15392. }
  15393. // Posts a multipart body split into two writes, so that the server sees the
  15394. // split at whatever offset the caller chose, and expects the single "text1"
  15395. // field to come through.
  15396. static void expect_split_multipart_ok(const std::string &body1,
  15397. const std::string &body2) {
  15398. auto handled = false;
  15399. Server svr;
  15400. svr.Post("/post", [&](const Request &req, Response &) {
  15401. EXPECT_EQ(1u, req.form.fields.size());
  15402. EXPECT_EQ("text1", req.form.get_field("text1"));
  15403. handled = true;
  15404. });
  15405. auto port = svr.bind_to_any_port(HOST);
  15406. thread t = thread([&] { svr.listen_after_bind(); });
  15407. auto se = detail::scope_exit([&] {
  15408. svr.stop();
  15409. t.join();
  15410. ASSERT_FALSE(svr.is_running());
  15411. ASSERT_TRUE(handled);
  15412. });
  15413. svr.wait_until_ready();
  15414. // "Connection: close" makes the server close once it has answered, so the
  15415. // response drain ends immediately instead of idling until the read timeout.
  15416. const std::string head =
  15417. "POST /post HTTP/1.1\r\n"
  15418. "Host: localhost\r\n"
  15419. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15420. "Connection: close\r\n"
  15421. "Content-Length: " +
  15422. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15423. std::string response;
  15424. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15425. ASSERT_GE(response.size(), 12u) << "no response";
  15426. EXPECT_EQ("200", response.substr(9, 3));
  15427. }
  15428. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15429. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15430. // ignored, including when it does not arrive in the same read as the
  15431. // close-delimiter itself.
  15432. expect_split_multipart_ok("--zzzz\r\n"
  15433. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15434. "\r\n"
  15435. "text1"
  15436. "\r\n--zzzz--",
  15437. "\r\nthis epilogue must be ignored\r\n");
  15438. }
  15439. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15440. // The initial boundary may be preceded by a preamble of any length and may
  15441. // straddle a read boundary. Discarding data while waiting for it must not
  15442. // throw away a partial boundary sitting at the end of the buffer.
  15443. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15444. "zz\r\n"
  15445. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15446. "\r\n"
  15447. "text1"
  15448. "\r\n--zzzz--\r\n");
  15449. }
  15450. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15451. // The received boundary was only checked for being non-empty, so it could be
  15452. // as long as a header is allowed to be. The parser scans the body for
  15453. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15454. // costs a nearly full comparison at nearly every position, making the
  15455. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15456. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15457. Server svr;
  15458. svr.Post("/post", [](const Request &req, Response &res) {
  15459. EXPECT_EQ(1u, req.form.fields.size());
  15460. EXPECT_EQ("text1", req.form.get_field("text1"));
  15461. res.set_content("ok", "text/plain");
  15462. });
  15463. auto port = svr.bind_to_any_port(HOST);
  15464. thread t = thread([&] { svr.listen_after_bind(); });
  15465. auto se = detail::scope_exit([&] {
  15466. svr.stop();
  15467. t.join();
  15468. ASSERT_FALSE(svr.is_running());
  15469. });
  15470. svr.wait_until_ready();
  15471. Client cli(HOST, port);
  15472. auto post_with_boundary_of_length = [&](size_t len) {
  15473. const std::string boundary(len, 'a');
  15474. const std::string body =
  15475. "--" + boundary +
  15476. "\r\n"
  15477. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15478. "\r\n"
  15479. "text1"
  15480. "\r\n--" +
  15481. boundary + "--\r\n";
  15482. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15483. };
  15484. auto res = post_with_boundary_of_length(70);
  15485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15486. EXPECT_EQ(StatusCode::OK_200, res->status);
  15487. res = post_with_boundary_of_length(71);
  15488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15489. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15490. }
  15491. TEST(MakeFileBodyTest, Basic) {
  15492. const std::string file_content(4096, 'Z');
  15493. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15494. {
  15495. std::ofstream ofs(tmp_path, std::ios::binary);
  15496. ofs.write(file_content.data(),
  15497. static_cast<std::streamsize>(file_content.size()));
  15498. }
  15499. auto handled = false;
  15500. Server svr;
  15501. svr.Post("/upload", [&](const Request &req, Response &res) {
  15502. EXPECT_EQ(file_content, req.body);
  15503. handled = true;
  15504. res.status = StatusCode::OK_200;
  15505. });
  15506. auto port = svr.bind_to_any_port(HOST);
  15507. auto t = thread([&] { svr.listen_after_bind(); });
  15508. auto se = detail::scope_exit([&] {
  15509. svr.stop();
  15510. t.join();
  15511. ASSERT_FALSE(svr.is_running());
  15512. ASSERT_TRUE(handled);
  15513. std::remove(tmp_path.c_str());
  15514. });
  15515. svr.wait_until_ready();
  15516. auto fb = make_file_body(tmp_path);
  15517. ASSERT_GT(fb.first, 0u);
  15518. Client cli(HOST, port);
  15519. auto res =
  15520. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15522. EXPECT_EQ(StatusCode::OK_200, res->status);
  15523. }
  15524. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15525. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15526. {
  15527. std::ofstream ofs(path, std::ios::binary);
  15528. const std::string content(100, 'A');
  15529. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15530. }
  15531. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15532. auto body = make_file_body(path);
  15533. ASSERT_EQ(100u, body.first);
  15534. ASSERT_TRUE(static_cast<bool>(body.second));
  15535. // Rewritten shorter after its length was measured - and, on a server, after
  15536. // that length has already gone out as Content-Length.
  15537. {
  15538. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15539. const std::string content(10, 'A');
  15540. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15541. }
  15542. std::string written;
  15543. DataSink sink;
  15544. sink.write = [&](const char *d, size_t l) {
  15545. written.append(d, l);
  15546. return true;
  15547. };
  15548. // The provider has to report failure. write_content_with_progress() advances
  15549. // its offset only by what was written, so a provider that returns true
  15550. // without completing the length it promised is called again straight away,
  15551. // and again.
  15552. EXPECT_FALSE(body.second(0, body.first, sink));
  15553. EXPECT_EQ(std::string(10, 'A'), written);
  15554. }
  15555. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15556. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15557. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15558. {
  15559. std::ofstream ofs(path, std::ios::binary);
  15560. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15561. }
  15562. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15563. auto body = make_file_body(path);
  15564. ASSERT_EQ(content.size(), body.first);
  15565. ASSERT_TRUE(static_cast<bool>(body.second));
  15566. std::string written;
  15567. DataSink sink;
  15568. sink.write = [&](const char *d, size_t l) {
  15569. written.append(d, l);
  15570. return true;
  15571. };
  15572. EXPECT_TRUE(body.second(0, body.first, sink));
  15573. EXPECT_EQ(content, written);
  15574. }
  15575. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15576. static constexpr unsigned int number_of_tasks{1000000};
  15577. std::atomic_uint count{0};
  15578. std::unique_ptr<TaskQueue> task_queue{
  15579. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15580. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15581. auto queued = task_queue->enqueue(
  15582. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15583. EXPECT_TRUE(queued);
  15584. }
  15585. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15586. task_queue->shutdown();
  15587. #else
  15588. EXPECT_NO_THROW(task_queue->shutdown());
  15589. #endif
  15590. EXPECT_EQ(number_of_tasks, count.load());
  15591. }
  15592. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15593. static constexpr unsigned int number_of_tasks{1000000};
  15594. static constexpr unsigned int qlimit{2};
  15595. unsigned int queued_count{0};
  15596. std::atomic_uint count{0};
  15597. std::unique_ptr<TaskQueue> task_queue{
  15598. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15599. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15600. if (task_queue->enqueue(
  15601. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15602. queued_count++;
  15603. }
  15604. }
  15605. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15606. task_queue->shutdown();
  15607. #else
  15608. EXPECT_NO_THROW(task_queue->shutdown());
  15609. #endif
  15610. EXPECT_EQ(queued_count, count.load());
  15611. EXPECT_TRUE(queued_count <= number_of_tasks);
  15612. EXPECT_TRUE(queued_count >= qlimit);
  15613. }
  15614. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15615. // Use a short idle timeout so a dynamic thread spawns, times out and
  15616. // exits during the test, and the pool keeps working afterwards.
  15617. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15618. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15619. /*idle_timeout_sec=*/1}};
  15620. std::atomic_uint count{0};
  15621. std::condition_variable cv;
  15622. std::mutex mtx;
  15623. bool release = false;
  15624. // Block the base thread so the second task spawns a dynamic thread.
  15625. EXPECT_TRUE(task_queue->enqueue([&] {
  15626. std::unique_lock<std::mutex> lock(mtx);
  15627. while (!release) {
  15628. cv.wait(lock);
  15629. }
  15630. count++;
  15631. }));
  15632. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15633. // Let the dynamic thread finish its task and exceed the idle timeout.
  15634. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15635. {
  15636. std::unique_lock<std::mutex> lock(mtx);
  15637. release = true;
  15638. }
  15639. cv.notify_all();
  15640. // The pool must still accept and run tasks after the dynamic thread exited.
  15641. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15642. task_queue->shutdown();
  15643. EXPECT_EQ(3u, count.load());
  15644. }
  15645. TEST(TaskQueueTest, MaxQueuedRequests) {
  15646. static constexpr unsigned int qlimit{3};
  15647. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15648. std::condition_variable sem_cv;
  15649. std::mutex sem_mtx;
  15650. int credits = 0;
  15651. bool queued;
  15652. /* Fill up the queue with tasks that will block until we give them credits to
  15653. * complete. */
  15654. for (unsigned int n = 0; n <= qlimit;) {
  15655. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15656. std::unique_lock<std::mutex> lock(sem_mtx);
  15657. while (credits <= 0) {
  15658. sem_cv.wait(lock);
  15659. }
  15660. /* Consume the credit and signal the test code if they are all gone. */
  15661. if (--credits == 0) { sem_cv.notify_one(); }
  15662. });
  15663. if (n < qlimit) {
  15664. /* The first qlimit enqueues must succeed. */
  15665. EXPECT_TRUE(queued);
  15666. } else {
  15667. /* The last one will succeed only when the worker thread
  15668. * starts and dequeues the first blocking task. Although
  15669. * not necessary for the correctness of this test, we sleep for
  15670. * a short while to avoid busy waiting. */
  15671. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15672. }
  15673. if (queued) { n++; }
  15674. }
  15675. /* Further enqueues must fail since the queue is full. */
  15676. for (auto i = 0; i < 4; i++) {
  15677. queued = task_queue->enqueue([] {});
  15678. EXPECT_FALSE(queued);
  15679. }
  15680. /* Give the credits to allow the previous tasks to complete. */
  15681. {
  15682. std::unique_lock<std::mutex> lock(sem_mtx);
  15683. credits += qlimit + 1;
  15684. }
  15685. sem_cv.notify_all();
  15686. /* Wait for all the credits to be consumed. */
  15687. {
  15688. std::unique_lock<std::mutex> lock(sem_mtx);
  15689. while (credits > 0) {
  15690. sem_cv.wait(lock);
  15691. }
  15692. }
  15693. /* Check that we are able again to enqueue at least qlimit tasks. */
  15694. for (unsigned int i = 0; i < qlimit; i++) {
  15695. queued = task_queue->enqueue([] {});
  15696. EXPECT_TRUE(queued);
  15697. }
  15698. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15699. task_queue->shutdown();
  15700. #else
  15701. EXPECT_NO_THROW(task_queue->shutdown());
  15702. #endif
  15703. }
  15704. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15705. Server svr;
  15706. std::string method;
  15707. std::string body;
  15708. auto has_content_length = false;
  15709. auto has_transfer_encoding = false;
  15710. std::atomic<int> bad_requests{0};
  15711. // Leftover body bytes get parsed as a malformed request and answered with
  15712. // 400
  15713. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15714. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15715. });
  15716. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15717. res.set_redirect("/down", StatusCode::SeeOther_303);
  15718. });
  15719. svr.Get("/down", [&](const Request &req, Response &res) {
  15720. method = req.method;
  15721. body = req.body;
  15722. has_content_length = req.has_header("Content-Length");
  15723. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15724. res.set_content("ok", "text/plain");
  15725. });
  15726. auto port = svr.bind_to_any_port(HOST);
  15727. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15728. auto se = detail::scope_exit([&] {
  15729. svr.stop();
  15730. thread.join();
  15731. ASSERT_FALSE(svr.is_running());
  15732. });
  15733. svr.wait_until_ready();
  15734. const std::string payload = "SECRET-BODY";
  15735. auto check = [&](Client &cli, const Result &res) {
  15736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15737. EXPECT_EQ(StatusCode::OK_200, res->status);
  15738. EXPECT_EQ("ok", res->body);
  15739. EXPECT_EQ("GET", method);
  15740. EXPECT_TRUE(body.empty());
  15741. EXPECT_FALSE(has_content_length);
  15742. EXPECT_FALSE(has_transfer_encoding);
  15743. // Nothing of the original body may be left on the connection
  15744. auto res2 = cli.Get("/down");
  15745. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15746. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15747. EXPECT_EQ("ok", res2->body);
  15748. EXPECT_EQ(0, bad_requests);
  15749. };
  15750. // With content length
  15751. {
  15752. Client cli(HOST, port);
  15753. cli.set_keep_alive(true);
  15754. cli.set_follow_location(true);
  15755. auto res = cli.Post(
  15756. "/up", payload.size(),
  15757. [&](size_t offset, size_t length, DataSink &sink) {
  15758. return sink.write(payload.data() + offset, length);
  15759. },
  15760. "text/plain");
  15761. check(cli, res);
  15762. }
  15763. // Without content length (chunked)
  15764. {
  15765. Client cli(HOST, port);
  15766. cli.set_keep_alive(true);
  15767. cli.set_follow_location(true);
  15768. auto res = cli.Post(
  15769. "/up",
  15770. [&](size_t /*offset*/, DataSink &sink) {
  15771. sink.write(payload.data(), payload.size());
  15772. sink.done();
  15773. return true;
  15774. },
  15775. "text/plain");
  15776. check(cli, res);
  15777. }
  15778. }
  15779. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15780. Server svr;
  15781. std::string target;
  15782. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15783. // Echo the still-encoded name back in the Location
  15784. const std::string prefix = "/start/";
  15785. res.status = StatusCode::Found_302;
  15786. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15787. });
  15788. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15789. target = req.target;
  15790. res.set_content("ok", "text/plain");
  15791. });
  15792. auto port = svr.bind_to_any_port(HOST);
  15793. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15794. auto se = detail::scope_exit([&] {
  15795. svr.stop();
  15796. thread.join();
  15797. ASSERT_FALSE(svr.is_running());
  15798. });
  15799. svr.wait_until_ready();
  15800. // Decoding the Location path would turn the first four into a path
  15801. // separator, a query delimiter, a fragment delimiter and a different
  15802. // percent-encoded octet. The rest must keep reaching the server as they are.
  15803. const std::vector<std::string> names = {
  15804. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15805. };
  15806. for (auto path_encode : {true, false}) {
  15807. Client cli(HOST, port);
  15808. cli.set_follow_location(true);
  15809. cli.set_path_encode(path_encode);
  15810. for (const auto &name : names) {
  15811. target.clear();
  15812. auto res = cli.Get("/start/" + name);
  15813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15814. EXPECT_EQ(StatusCode::OK_200, res->status);
  15815. EXPECT_EQ("/dest/" + name, target);
  15816. }
  15817. }
  15818. }
  15819. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15820. Server svr;
  15821. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15822. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15823. });
  15824. svr.Get("/hello", [](const Request &req, Response &res) {
  15825. res.set_content(req.get_param_value("key"), "text/plain");
  15826. });
  15827. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15828. auto se = detail::scope_exit([&] {
  15829. svr.stop();
  15830. thread.join();
  15831. ASSERT_FALSE(svr.is_running());
  15832. });
  15833. svr.wait_until_ready();
  15834. {
  15835. Client cli(HOST, PORT);
  15836. cli.set_follow_location(true);
  15837. auto res = cli.Get("/");
  15838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15839. EXPECT_EQ(StatusCode::OK_200, res->status);
  15840. EXPECT_EQ("val&key2=val2", res->body);
  15841. }
  15842. }
  15843. #endif
  15844. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15845. Server svr;
  15846. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15847. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15848. });
  15849. svr.Get("/hello", [](const Request &req, Response &res) {
  15850. res.set_content(req.get_param_value("key"), "text/plain");
  15851. });
  15852. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15853. auto se = detail::scope_exit([&] {
  15854. svr.stop();
  15855. thread.join();
  15856. ASSERT_FALSE(svr.is_running());
  15857. });
  15858. svr.wait_until_ready();
  15859. {
  15860. Client cli(HOST, PORT);
  15861. cli.set_follow_location(true);
  15862. auto res = cli.Get("/");
  15863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15864. EXPECT_EQ(StatusCode::OK_200, res->status);
  15865. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15866. }
  15867. }
  15868. TEST(RedirectTest, RedirectWithPlusInPath) {
  15869. Server svr;
  15870. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15871. res.set_redirect("/a+b");
  15872. });
  15873. // Route pattern uses regex; escape + as \\+
  15874. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15875. res.set_content(req.path, "text/plain");
  15876. });
  15877. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15878. auto se = detail::scope_exit([&] {
  15879. svr.stop();
  15880. thread.join();
  15881. ASSERT_FALSE(svr.is_running());
  15882. });
  15883. svr.wait_until_ready();
  15884. {
  15885. Client cli(HOST, PORT);
  15886. cli.set_follow_location(true);
  15887. auto res = cli.Get("/");
  15888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15889. EXPECT_EQ(StatusCode::OK_200, res->status);
  15890. EXPECT_EQ("/a+b", res->body);
  15891. }
  15892. }
  15893. TEST(RedirectTest, ResolveRelativeLocation) {
  15894. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15895. const std::vector<std::pair<std::string, std::string>> cases = {
  15896. {"g", "/b/c/g"},
  15897. {"./g", "/b/c/g"},
  15898. {"g/", "/b/c/g/"},
  15899. {"?y", "/b/c/d;p?y"},
  15900. {"g?y", "/b/c/g?y"},
  15901. {"#s", "/b/c/d;p?q#s"},
  15902. {"g#s", "/b/c/g#s"},
  15903. {"g?y#s", "/b/c/g?y#s"},
  15904. {";x", "/b/c/;x"},
  15905. {"g;x", "/b/c/g;x"},
  15906. {".", "/b/c/"},
  15907. {"./", "/b/c/"},
  15908. {"..", "/b/"},
  15909. {"../", "/b/"},
  15910. {"../g", "/b/g"},
  15911. {"../..", "/"},
  15912. {"../../", "/"},
  15913. {"../../g", "/g"},
  15914. {"../../../g", "/g"},
  15915. {"g.", "/b/c/g."},
  15916. {".g", "/b/c/.g"},
  15917. {"g..", "/b/c/g.."},
  15918. {"..g", "/b/c/..g"},
  15919. {"./../g", "/b/g"},
  15920. {"./g/.", "/b/c/g/"},
  15921. {"g/./h", "/b/c/g/h"},
  15922. {"g/../h", "/b/c/h"},
  15923. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15924. {"g;x=1/../y", "/b/c/y"},
  15925. {"g?y/./x", "/b/c/g?y/./x"},
  15926. {"g#s/../x", "/b/c/g#s/../x"},
  15927. // Not relative-path references, so left for parse_url.
  15928. {"/g", "/g"},
  15929. {"//g", "//g"},
  15930. {"http://g/x", "http://g/x"},
  15931. {"g:h", "g:h"},
  15932. };
  15933. for (const auto &c : cases) {
  15934. EXPECT_EQ(c.second,
  15935. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15936. << c.first;
  15937. }
  15938. }
  15939. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15940. Server svr;
  15941. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15942. res.set_redirect(req.get_param_value("to"));
  15943. });
  15944. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15945. res.set_content(req.target, "text/plain");
  15946. });
  15947. svr.Get("/other", [](const Request &req, Response &res) {
  15948. res.set_content(req.target, "text/plain");
  15949. });
  15950. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15951. auto se = detail::scope_exit([&] {
  15952. svr.stop();
  15953. thread.join();
  15954. ASSERT_FALSE(svr.is_running());
  15955. });
  15956. svr.wait_until_ready();
  15957. const std::vector<std::pair<std::string, std::string>> cases = {
  15958. {"next", "/dir/next"},
  15959. {"./next?x=1", "/dir/next?x=1"},
  15960. {"../other", "/other"},
  15961. };
  15962. for (const auto &c : cases) {
  15963. Client cli(HOST, PORT);
  15964. cli.set_follow_location(true);
  15965. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15966. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15967. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15968. EXPECT_EQ(c.second, res->body) << c.first;
  15969. }
  15970. }
  15971. #ifdef CPPHTTPLIB_SSL_ENABLED
  15972. TEST(RedirectTest, Issue2185_Online) {
  15973. SSLClient client("github.com");
  15974. client.set_follow_location(true);
  15975. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15976. "Coollab-Windows.zip");
  15977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15978. EXPECT_EQ(StatusCode::OK_200, res->status);
  15979. EXPECT_EQ(9920427U, res->body.size());
  15980. }
  15981. #endif
  15982. TEST(VulnerabilityTest, CRLFInjection) {
  15983. Server svr;
  15984. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15985. res.set_content("Hello 1", "text/plain");
  15986. });
  15987. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15988. res.set_content("Hello 2", "text/plain");
  15989. });
  15990. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15991. res.set_content("Hello 3", "text/plain");
  15992. });
  15993. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15994. res.set_content("Hello 4", "text/plain");
  15995. });
  15996. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15997. for (const auto &x : req.headers) {
  15998. auto key = x.first;
  15999. EXPECT_STRNE("evil", key.c_str());
  16000. }
  16001. });
  16002. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16003. auto se = detail::scope_exit([&] {
  16004. svr.stop();
  16005. thread.join();
  16006. ASSERT_FALSE(svr.is_running());
  16007. });
  16008. svr.wait_until_ready();
  16009. {
  16010. Client cli(HOST, PORT);
  16011. cli.Post("/test1", "A=B",
  16012. "application/x-www-form-urlencoded\r\nevil: hello1");
  16013. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16014. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16015. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16016. }
  16017. }
  16018. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16019. auto server_thread = std::thread([] {
  16020. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16021. default_socket_options(srv);
  16022. sockaddr_in addr{};
  16023. addr.sin_family = AF_INET;
  16024. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16025. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16026. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16027. ::listen(srv, 1);
  16028. sockaddr_in cli_addr{};
  16029. socklen_t cli_len = sizeof(cli_addr);
  16030. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16031. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16032. std::string buf_all;
  16033. char buf[2048];
  16034. ssize_t n;
  16035. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16036. buf_all.append(buf, static_cast<size_t>(n));
  16037. size_t pos;
  16038. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16039. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16040. auto e = request_block.find("\r\n");
  16041. if (e != std::string::npos) {
  16042. auto request_line = request_block.substr(0, e);
  16043. std::string msg =
  16044. "CRLF injection detected in request line: '" + request_line + "'";
  16045. EXPECT_FALSE(true) << msg;
  16046. }
  16047. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16048. ::send(cli,
  16049. #ifdef _WIN32
  16050. static_cast<const char *>(resp.c_str()),
  16051. static_cast<int>(resp.size()),
  16052. #else
  16053. resp.c_str(), resp.size(),
  16054. #endif
  16055. 0);
  16056. buf_all.erase(0, pos + 4);
  16057. }
  16058. }
  16059. detail::close_socket(cli);
  16060. detail::close_socket(srv);
  16061. });
  16062. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16063. auto cli = Client("127.0.0.1", PORT + 1);
  16064. auto headers = Headers{
  16065. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16066. {"Connection", "keep-alive"}};
  16067. auto res = cli.Get("/hi", headers);
  16068. EXPECT_FALSE(res);
  16069. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16070. server_thread.join();
  16071. }
  16072. // A request rejected before any byte reaches the socket must fail right away
  16073. // instead of waiting for a response the server will never send.
  16074. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16075. // The kernel completes the TCP handshake from the listen backlog, so the
  16076. // client connects, but nothing ever reads, responds or closes.
  16077. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16078. default_socket_options(srv);
  16079. sockaddr_in addr{};
  16080. addr.sin_family = AF_INET;
  16081. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16082. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16083. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16084. ASSERT_EQ(0, ::listen(srv, 8));
  16085. auto cli = Client("127.0.0.1", PORT + 1);
  16086. cli.set_read_timeout(10, 0);
  16087. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16088. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16089. std::chrono::steady_clock::now() - start)
  16090. .count();
  16091. };
  16092. {
  16093. Request req;
  16094. req.method = "GE T";
  16095. req.path = "/";
  16096. auto start = std::chrono::steady_clock::now();
  16097. auto res = cli.send(req);
  16098. EXPECT_FALSE(res);
  16099. EXPECT_EQ(Error::Write, res.error());
  16100. EXPECT_LT(elapsed_ms(start), 1000);
  16101. }
  16102. {
  16103. auto start = std::chrono::steady_clock::now();
  16104. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16105. EXPECT_FALSE(res);
  16106. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16107. EXPECT_LT(elapsed_ms(start), 1000);
  16108. }
  16109. EXPECT_FALSE(cli.is_socket_open());
  16110. detail::close_socket(srv);
  16111. }
  16112. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16113. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16114. default_socket_options(srv);
  16115. sockaddr_in addr{};
  16116. addr.sin_family = AF_INET;
  16117. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16118. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16119. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16120. ASSERT_EQ(0, ::listen(srv, 1));
  16121. std::string received;
  16122. auto server_thread = std::thread([&] {
  16123. auto sock = ::accept(srv, nullptr, nullptr);
  16124. if (sock == INVALID_SOCKET) { return; }
  16125. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16126. char buf[2048];
  16127. ssize_t n;
  16128. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16129. received.append(buf, static_cast<size_t>(n));
  16130. }
  16131. detail::close_socket(sock);
  16132. });
  16133. {
  16134. auto cli = Client("127.0.0.1", PORT + 1);
  16135. // "Z" sorts after the default headers, so writing straight to the socket
  16136. // would have sent the request line and those headers before the rejection.
  16137. auto handle =
  16138. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16139. EXPECT_FALSE(handle.is_valid());
  16140. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16141. }
  16142. server_thread.join();
  16143. detail::close_socket(srv);
  16144. EXPECT_TRUE(received.empty()) << received;
  16145. }
  16146. TEST(PathParamsTest, StaticMatch) {
  16147. const auto pattern = "/users/all";
  16148. detail::PathParamsMatcher matcher(pattern);
  16149. Request request;
  16150. request.path = "/users/all";
  16151. ASSERT_TRUE(matcher.match(request));
  16152. std::unordered_map<std::string, std::string> expected_params = {};
  16153. EXPECT_EQ(request.path_params, expected_params);
  16154. }
  16155. TEST(PathParamsTest, StaticMismatch) {
  16156. const auto pattern = "/users/all";
  16157. detail::PathParamsMatcher matcher(pattern);
  16158. Request request;
  16159. request.path = "/users/1";
  16160. ASSERT_FALSE(matcher.match(request));
  16161. }
  16162. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16163. const auto pattern = "/users/:id/subscriptions";
  16164. detail::PathParamsMatcher matcher(pattern);
  16165. Request request;
  16166. request.path = "/users/42/subscriptions";
  16167. ASSERT_TRUE(matcher.match(request));
  16168. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16169. EXPECT_EQ(request.path_params, expected_params);
  16170. }
  16171. TEST(PathParamsTest, SingleParamInTheEnd) {
  16172. const auto pattern = "/users/:id";
  16173. detail::PathParamsMatcher matcher(pattern);
  16174. Request request;
  16175. request.path = "/users/24";
  16176. ASSERT_TRUE(matcher.match(request));
  16177. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16178. EXPECT_EQ(request.path_params, expected_params);
  16179. }
  16180. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16181. const auto pattern = "/users/:id/";
  16182. detail::PathParamsMatcher matcher(pattern);
  16183. Request request;
  16184. request.path = "/users/42/";
  16185. ASSERT_TRUE(matcher.match(request));
  16186. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16187. EXPECT_EQ(request.path_params, expected_params);
  16188. }
  16189. TEST(PathParamsTest, EmptyParam) {
  16190. const auto pattern = "/users/:id/";
  16191. detail::PathParamsMatcher matcher(pattern);
  16192. Request request;
  16193. request.path = "/users//";
  16194. ASSERT_TRUE(matcher.match(request));
  16195. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16196. EXPECT_EQ(request.path_params, expected_params);
  16197. }
  16198. TEST(PathParamsTest, FragmentMismatch) {
  16199. const auto pattern = "/users/:id/";
  16200. detail::PathParamsMatcher matcher(pattern);
  16201. Request request;
  16202. request.path = "/admins/24/";
  16203. ASSERT_FALSE(matcher.match(request));
  16204. }
  16205. TEST(PathParamsTest, ExtraFragments) {
  16206. const auto pattern = "/users/:id";
  16207. detail::PathParamsMatcher matcher(pattern);
  16208. Request request;
  16209. request.path = "/users/42/subscriptions";
  16210. ASSERT_FALSE(matcher.match(request));
  16211. }
  16212. TEST(PathParamsTest, MissingTrailingParam) {
  16213. const auto pattern = "/users/:id";
  16214. detail::PathParamsMatcher matcher(pattern);
  16215. Request request;
  16216. request.path = "/users";
  16217. ASSERT_FALSE(matcher.match(request));
  16218. }
  16219. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16220. const auto pattern = "/users/:id/subscriptions";
  16221. detail::PathParamsMatcher matcher(pattern);
  16222. Request request;
  16223. request.path = "/users/subscriptions";
  16224. ASSERT_FALSE(matcher.match(request));
  16225. }
  16226. TEST(PathParamsTest, MultipleParams) {
  16227. const auto pattern = "/users/:userid/subscriptions/:subid";
  16228. detail::PathParamsMatcher matcher(pattern);
  16229. Request request;
  16230. request.path = "/users/42/subscriptions/2";
  16231. ASSERT_TRUE(matcher.match(request));
  16232. std::unordered_map<std::string, std::string> expected_params = {
  16233. {"userid", "42"}, {"subid", "2"}};
  16234. EXPECT_EQ(request.path_params, expected_params);
  16235. }
  16236. TEST(PathParamsTest, SequenceOfParams) {
  16237. const auto pattern = "/values/:x/:y/:z";
  16238. detail::PathParamsMatcher matcher(pattern);
  16239. Request request;
  16240. request.path = "/values/1/2/3";
  16241. ASSERT_TRUE(matcher.match(request));
  16242. std::unordered_map<std::string, std::string> expected_params = {
  16243. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16244. EXPECT_EQ(request.path_params, expected_params);
  16245. }
  16246. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16247. const auto pattern = "/prefix:suffix";
  16248. detail::PathParamsMatcher matcher(pattern);
  16249. Request request;
  16250. request.path = "/prefix:suffix";
  16251. ASSERT_TRUE(matcher.match(request));
  16252. const std::unordered_map<std::string, std::string> expected_params = {};
  16253. EXPECT_EQ(request.path_params, expected_params);
  16254. }
  16255. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16256. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16257. // calling thread's stack on a long enough path for a quantified pattern;
  16258. // RegexMatcher must refuse to run regex matching on paths beyond
  16259. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16260. detail::RegexMatcher matcher("/files/(.*)");
  16261. Request within_limit;
  16262. within_limit.path = "/files/" + std::string(10, 'A');
  16263. EXPECT_TRUE(matcher.match(within_limit));
  16264. Request over_limit;
  16265. over_limit.path =
  16266. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16267. EXPECT_FALSE(matcher.match(over_limit));
  16268. }
  16269. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16270. Server svr;
  16271. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16272. res.set_content("ok", "text/plain");
  16273. });
  16274. auto port = svr.bind_to_any_port(HOST);
  16275. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16276. auto se = detail::scope_exit([&] {
  16277. svr.stop();
  16278. thread.join();
  16279. ASSERT_FALSE(svr.is_running());
  16280. });
  16281. svr.wait_until_ready();
  16282. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16283. // request URI limit; this used to be able to crash the process.
  16284. std::string path =
  16285. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16286. std::string req = "GET " + path +
  16287. " HTTP/1.1\r\n"
  16288. "Host: " +
  16289. std::string(HOST) + ":" + std::to_string(port) +
  16290. "\r\n"
  16291. "Connection: close\r\n"
  16292. "\r\n";
  16293. std::string response;
  16294. ASSERT_TRUE(send_request(5, req, &response, port));
  16295. EXPECT_NE(std::string::npos, response.find("404"));
  16296. }
  16297. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16298. Server svr;
  16299. auto handler = [](const Request & /*req*/, Response &res) {
  16300. res.set_content("hit", "text/plain");
  16301. };
  16302. // No regex metacharacter, so this one is compared literally
  16303. svr.Get("/literal/route", handler);
  16304. // '.' is a regex metacharacter, so this one must keep regex semantics
  16305. svr.Get("/a.c", handler);
  16306. auto port = svr.bind_to_any_port(HOST);
  16307. std::thread t([&]() { svr.listen_after_bind(); });
  16308. auto se = detail::scope_exit([&] {
  16309. svr.stop();
  16310. t.join();
  16311. ASSERT_FALSE(svr.is_running());
  16312. });
  16313. svr.wait_until_ready();
  16314. Client cli(HOST, port);
  16315. struct {
  16316. const char *path;
  16317. int status;
  16318. } cases[] = {
  16319. {"/literal/route", StatusCode::OK_200},
  16320. {"/literal/routes", StatusCode::NotFound_404},
  16321. {"/literal/rout", StatusCode::NotFound_404},
  16322. {"/abc", StatusCode::OK_200},
  16323. {"/a.c", StatusCode::OK_200},
  16324. };
  16325. for (const auto &x : cases) {
  16326. auto res = cli.Get(x.path);
  16327. ASSERT_TRUE(res) << x.path;
  16328. EXPECT_EQ(x.status, res->status) << x.path;
  16329. }
  16330. }
  16331. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16332. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16333. // from exhausting the stack, so it must only constrain routes that actually
  16334. // run a regular expression. A literal route is matched by comparison and
  16335. // stays usable at any length.
  16336. Server svr;
  16337. const std::string pattern =
  16338. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16339. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16340. res.set_content("hit", "text/plain");
  16341. });
  16342. auto port = svr.bind_to_any_port(HOST);
  16343. std::thread t([&]() { svr.listen_after_bind(); });
  16344. auto se = detail::scope_exit([&] {
  16345. svr.stop();
  16346. t.join();
  16347. ASSERT_FALSE(svr.is_running());
  16348. });
  16349. svr.wait_until_ready();
  16350. Client cli(HOST, port);
  16351. auto res = cli.Get(pattern);
  16352. ASSERT_TRUE(res);
  16353. EXPECT_EQ(StatusCode::OK_200, res->status);
  16354. }
  16355. TEST(ParseUrlTest, VariousPatterns) {
  16356. {
  16357. detail::UrlComponents uc;
  16358. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16359. EXPECT_EQ("http", uc.scheme);
  16360. EXPECT_EQ("example.com", uc.host);
  16361. EXPECT_EQ("8080", uc.port);
  16362. EXPECT_EQ("/path", uc.path);
  16363. EXPECT_EQ("?q=1", uc.query);
  16364. }
  16365. {
  16366. detail::UrlComponents uc;
  16367. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16368. EXPECT_EQ("https", uc.scheme);
  16369. EXPECT_EQ("example.com", uc.host);
  16370. EXPECT_TRUE(uc.port.empty());
  16371. EXPECT_EQ("/path", uc.path);
  16372. }
  16373. {
  16374. detail::UrlComponents uc;
  16375. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16376. EXPECT_EQ("::1", uc.host);
  16377. EXPECT_EQ("8080", uc.port);
  16378. EXPECT_EQ("/path", uc.path);
  16379. }
  16380. {
  16381. detail::UrlComponents uc;
  16382. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16383. }
  16384. {
  16385. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16386. // the path while the connection still targets the bracketed host.
  16387. detail::UrlComponents uc;
  16388. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16389. }
  16390. {
  16391. detail::UrlComponents uc;
  16392. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16393. }
  16394. {
  16395. detail::UrlComponents uc;
  16396. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16397. EXPECT_EQ("::1", uc.host);
  16398. EXPECT_TRUE(uc.port.empty());
  16399. EXPECT_EQ("/path", uc.path);
  16400. }
  16401. {
  16402. detail::UrlComponents uc;
  16403. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16404. EXPECT_TRUE(uc.scheme.empty());
  16405. EXPECT_EQ("example.com", uc.host);
  16406. EXPECT_EQ("/path", uc.path);
  16407. EXPECT_EQ("?q=1", uc.query);
  16408. }
  16409. {
  16410. detail::UrlComponents uc;
  16411. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16412. EXPECT_TRUE(uc.host.empty());
  16413. EXPECT_EQ("/path", uc.path);
  16414. EXPECT_EQ("?q=1", uc.query);
  16415. }
  16416. {
  16417. detail::UrlComponents uc;
  16418. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16419. EXPECT_EQ("example.com", uc.host);
  16420. EXPECT_EQ("8080", uc.port);
  16421. }
  16422. {
  16423. // Unix socket path — must not be parsed as host
  16424. detail::UrlComponents uc;
  16425. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16426. EXPECT_TRUE(uc.host.empty());
  16427. }
  16428. {
  16429. detail::UrlComponents uc;
  16430. ASSERT_TRUE(detail::parse_url("", uc));
  16431. EXPECT_TRUE(uc.host.empty());
  16432. EXPECT_TRUE(uc.path.empty());
  16433. }
  16434. {
  16435. detail::UrlComponents uc;
  16436. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16437. }
  16438. {
  16439. detail::UrlComponents uc;
  16440. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16441. }
  16442. {
  16443. // Accepted by parse_url; callers restrict to http/https
  16444. detail::UrlComponents uc;
  16445. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16446. EXPECT_EQ("ftp", uc.scheme);
  16447. }
  16448. {
  16449. detail::UrlComponents uc;
  16450. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16451. }
  16452. {
  16453. detail::UrlComponents uc;
  16454. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16455. }
  16456. }
  16457. TEST(ParseUrlTest, FragmentHandling) {
  16458. {
  16459. detail::UrlComponents uc;
  16460. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16461. EXPECT_EQ("/path", uc.path);
  16462. EXPECT_TRUE(uc.query.empty());
  16463. }
  16464. {
  16465. detail::UrlComponents uc;
  16466. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16467. EXPECT_TRUE(uc.path.empty());
  16468. EXPECT_TRUE(uc.query.empty());
  16469. }
  16470. }
  16471. TEST(ParseUrlTest, UserinfoHandling) {
  16472. // userinfo is not supported. Parsers that honour it, or take a backslash for
  16473. // '/', would see evil.com where the host used to be the whole authority.
  16474. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16475. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16476. for (auto url : urls) {
  16477. detail::UrlComponents uc;
  16478. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16479. }
  16480. }
  16481. TEST(ParseUrlTest, IPv6EdgeCases) {
  16482. {
  16483. detail::UrlComponents uc;
  16484. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16485. EXPECT_TRUE(uc.scheme.empty());
  16486. EXPECT_EQ("::1", uc.host);
  16487. EXPECT_EQ("8080", uc.port);
  16488. }
  16489. {
  16490. // Zone ID '%25' is not in [a-fA-F0-9:]
  16491. detail::UrlComponents uc;
  16492. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16493. }
  16494. }
  16495. TEST(ParseUrlTest, SchemeEdgeCases) {
  16496. {
  16497. detail::UrlComponents uc;
  16498. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16499. }
  16500. {
  16501. detail::UrlComponents uc;
  16502. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16503. }
  16504. {
  16505. detail::UrlComponents uc;
  16506. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16507. }
  16508. }
  16509. TEST(ParseUrlTest, PortEdgeCases) {
  16510. {
  16511. detail::UrlComponents uc;
  16512. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16513. EXPECT_TRUE(uc.port.empty());
  16514. EXPECT_EQ("/path", uc.path);
  16515. }
  16516. {
  16517. // parse_url accepts any port string; validation is done by parse_port
  16518. detail::UrlComponents uc;
  16519. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16520. EXPECT_EQ("abc", uc.port);
  16521. }
  16522. }
  16523. TEST(ParseUrlTest, WebSocketPatterns) {
  16524. {
  16525. detail::UrlComponents uc;
  16526. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16527. EXPECT_EQ("ws", uc.scheme);
  16528. EXPECT_EQ("echo.example.com", uc.host);
  16529. EXPECT_EQ("8080", uc.port);
  16530. EXPECT_EQ("/ws", uc.path);
  16531. }
  16532. {
  16533. detail::UrlComponents uc;
  16534. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16535. EXPECT_EQ("wss", uc.scheme);
  16536. EXPECT_EQ("echo.example.com", uc.host);
  16537. EXPECT_TRUE(uc.port.empty());
  16538. EXPECT_EQ("/ws", uc.path);
  16539. }
  16540. }
  16541. TEST(ParseUrlTest, QueryOnly) {
  16542. detail::UrlComponents uc;
  16543. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16544. EXPECT_TRUE(uc.host.empty());
  16545. EXPECT_TRUE(uc.path.empty());
  16546. EXPECT_EQ("?q=1&r=2", uc.query);
  16547. }
  16548. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16549. detail::UrlComponents uc;
  16550. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16551. EXPECT_TRUE(uc.scheme.empty());
  16552. EXPECT_EQ("example.com", uc.host);
  16553. EXPECT_EQ("443", uc.port);
  16554. EXPECT_EQ("/path", uc.path);
  16555. }
  16556. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16557. // If ipv6 regex working, regex match codepath is taken.
  16558. // else port will default to 80 in Client impl
  16559. int clientImplMagicPort = 80;
  16560. int port = 4321;
  16561. // above ports must be different to avoid false negative
  16562. EXPECT_NE(clientImplMagicPort, port);
  16563. std::string ipV6TestURL = "http://[ff06::c3]";
  16564. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16565. CLIENT_PRIVATE_KEY_FILE);
  16566. EXPECT_EQ(cli.port(), port);
  16567. }
  16568. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16569. auto file_path = "./www/dir/index.html";
  16570. auto dir_path = "./www/dir";
  16571. detail::FileStat stat_file(file_path);
  16572. EXPECT_TRUE(stat_file.is_file());
  16573. EXPECT_FALSE(stat_file.is_dir());
  16574. detail::FileStat stat_dir(dir_path);
  16575. EXPECT_FALSE(stat_dir.is_file());
  16576. EXPECT_TRUE(stat_dir.is_dir());
  16577. }
  16578. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16579. // IPv4 with default HTTP port (80)
  16580. EXPECT_EQ("example.com",
  16581. detail::make_host_and_port_string("example.com", 80, false));
  16582. // IPv4 with default HTTPS port (443)
  16583. EXPECT_EQ("example.com",
  16584. detail::make_host_and_port_string("example.com", 443, true));
  16585. // IPv4 with non-default HTTP port
  16586. EXPECT_EQ("example.com:8080",
  16587. detail::make_host_and_port_string("example.com", 8080, false));
  16588. // IPv4 with non-default HTTPS port
  16589. EXPECT_EQ("example.com:8443",
  16590. detail::make_host_and_port_string("example.com", 8443, true));
  16591. // IPv6 with default HTTP port (80)
  16592. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16593. // IPv6 with default HTTPS port (443)
  16594. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16595. // IPv6 with non-default HTTP port
  16596. EXPECT_EQ("[::1]:8080",
  16597. detail::make_host_and_port_string("::1", 8080, false));
  16598. // IPv6 with non-default HTTPS port
  16599. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16600. // IPv6 full address with default port
  16601. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16602. detail::make_host_and_port_string(
  16603. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16604. // IPv6 full address with non-default port
  16605. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16606. detail::make_host_and_port_string(
  16607. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16608. // IPv6 localhost with non-default port
  16609. EXPECT_EQ("[::1]:3000",
  16610. detail::make_host_and_port_string("::1", 3000, false));
  16611. // IPv6 with zone ID (link-local address) with default port
  16612. EXPECT_EQ("[fe80::1%eth0]",
  16613. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16614. // IPv6 with zone ID (link-local address) with non-default port
  16615. EXPECT_EQ("[fe80::1%eth0]:8080",
  16616. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16617. // Edge case: Port 443 with is_ssl=false (should add port)
  16618. EXPECT_EQ("example.com:443",
  16619. detail::make_host_and_port_string("example.com", 443, false));
  16620. // Edge case: Port 80 with is_ssl=true (should add port)
  16621. EXPECT_EQ("example.com:80",
  16622. detail::make_host_and_port_string("example.com", 80, true));
  16623. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16624. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16625. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16626. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16627. // Security fix: Already bracketed IPv6 should not get double brackets
  16628. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16629. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16630. EXPECT_EQ("[::1]:8080",
  16631. detail::make_host_and_port_string("[::1]", 8080, false));
  16632. EXPECT_EQ("[2001:db8::1]:8080",
  16633. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16634. EXPECT_EQ("[fe80::1%eth0]",
  16635. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16636. EXPECT_EQ("[fe80::1%eth0]:8080",
  16637. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16638. // Edge case: Empty host (should return as-is)
  16639. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16640. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16641. // This is a known limitation but shouldn't crash
  16642. EXPECT_EQ("[host:name]",
  16643. detail::make_host_and_port_string("host:name", 80, false));
  16644. // Port number edge cases (no validation, but should not crash)
  16645. EXPECT_EQ("example.com:0",
  16646. detail::make_host_and_port_string("example.com", 0, false));
  16647. EXPECT_EQ("example.com:-1",
  16648. detail::make_host_and_port_string("example.com", -1, false));
  16649. EXPECT_EQ("example.com:65535",
  16650. detail::make_host_and_port_string("example.com", 65535, false));
  16651. EXPECT_EQ("example.com:65536",
  16652. detail::make_host_and_port_string("example.com", 65536, false));
  16653. }
  16654. #ifdef CPPHTTPLIB_SSL_ENABLED
  16655. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16656. httplib::SSLClient cli("roblox.com", 443);
  16657. cli.set_follow_location(true);
  16658. auto res = cli.Get("/");
  16659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16660. EXPECT_EQ(StatusCode::OK_200, res->status);
  16661. }
  16662. #endif
  16663. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16664. Server svr;
  16665. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16666. EXPECT_EQ(res.status, 400);
  16667. });
  16668. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16669. auto se = detail::scope_exit([&] {
  16670. svr.stop();
  16671. thread.join();
  16672. ASSERT_FALSE(svr.is_running());
  16673. });
  16674. svr.wait_until_ready();
  16675. Client cli(HOST, PORT);
  16676. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16677. }
  16678. TEST(InvalidHeaderCharsTest, is_field_name) {
  16679. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16680. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16681. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16682. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16683. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16684. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16685. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16686. EXPECT_FALSE(detail::fields::is_field_name(""));
  16687. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16688. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16689. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16690. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16691. }
  16692. TEST(InvalidHeaderCharsTest, is_field_value) {
  16693. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16694. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16695. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16696. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16697. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16698. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16699. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16700. EXPECT_TRUE(detail::fields::is_field_value(""));
  16701. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16702. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16703. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16704. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16705. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16706. }
  16707. TEST(InvalidHeaderCharsTest, OnServer) {
  16708. Server svr;
  16709. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16710. std::string header = "Not Set";
  16711. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16712. res.set_header(header, "value");
  16713. res.set_content("Page Content Page Content", "text/plain");
  16714. });
  16715. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16716. std::string header = "Not Set";
  16717. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16718. res.set_header("X-Test", header);
  16719. res.set_content("Page Content Page Content", "text/plain");
  16720. });
  16721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16722. auto se = detail::scope_exit([&] {
  16723. svr.stop();
  16724. thread.join();
  16725. ASSERT_FALSE(svr.is_running());
  16726. });
  16727. svr.wait_until_ready();
  16728. Client cli(HOST, PORT);
  16729. {
  16730. auto res = cli.Get(
  16731. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16733. EXPECT_EQ("Page Content Page Content", res->body);
  16734. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16735. }
  16736. {
  16737. auto res = cli.Get(
  16738. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16740. EXPECT_EQ("Page Content Page Content", res->body);
  16741. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16742. }
  16743. }
  16744. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16745. auto handled = false;
  16746. Server svr;
  16747. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16748. thread t = thread([&] { svr.listen(HOST, PORT); });
  16749. auto se = detail::scope_exit([&] {
  16750. svr.stop();
  16751. t.join();
  16752. ASSERT_FALSE(svr.is_running());
  16753. ASSERT_FALSE(handled);
  16754. });
  16755. svr.wait_until_ready();
  16756. auto req = "POST /test HTTP/1.1\r\n"
  16757. "Content-Length: x\r\n"
  16758. "\r\n";
  16759. std::string response;
  16760. ASSERT_TRUE(send_request(1, req, &response));
  16761. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16762. response.substr(0, response.find("\r\n")));
  16763. }
  16764. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16765. // case-insensitive, and a server that receives a 100-continue expectation in
  16766. // an HTTP/1.0 request MUST ignore it.
  16767. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16768. std::string response;
  16769. ASSERT_TRUE(send_request(1, req, &response, port));
  16770. *got_100 = response.find("100 Continue") != std::string::npos;
  16771. }
  16772. class ExpectTokenTest : public ::testing::Test {
  16773. protected:
  16774. void SetUp() override {
  16775. svr_.Post("/p", [](const Request &, Response &res) {
  16776. res.set_content("ok", "text/plain");
  16777. });
  16778. port_ = svr_.bind_to_any_port(HOST);
  16779. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16780. svr_.wait_until_ready();
  16781. }
  16782. void TearDown() override {
  16783. svr_.stop();
  16784. if (thread_.joinable()) { thread_.join(); }
  16785. }
  16786. std::string request(const char *version, const char *expect_value) const {
  16787. return std::string("POST /p ") + version +
  16788. "\r\n"
  16789. "Host: localhost\r\n"
  16790. "Content-Length: 2\r\n"
  16791. "Connection: close\r\n"
  16792. "Expect: " +
  16793. expect_value +
  16794. "\r\n"
  16795. "\r\n"
  16796. "hi";
  16797. }
  16798. Server svr_;
  16799. int port_ = 0;
  16800. thread thread_;
  16801. };
  16802. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16803. bool got_100 = false;
  16804. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16805. EXPECT_TRUE(got_100);
  16806. }
  16807. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16808. bool got_100 = true;
  16809. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16810. EXPECT_FALSE(got_100);
  16811. }
  16812. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16813. bool got_100 = false;
  16814. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16815. EXPECT_TRUE(got_100);
  16816. }
  16817. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16818. bool got_100 = false;
  16819. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16820. EXPECT_TRUE(got_100);
  16821. }
  16822. // `100 Continue` is sent only when the server starts reading the body, so a
  16823. // request rejected before that never invites the client to send it. The
  16824. // requests below carry the expectation but withhold the body, as a client
  16825. // waiting for `100 Continue` would.
  16826. // A POST that expects `100 Continue` and withholds its two-byte body.
  16827. static std::string expect_headers_only(const std::string &path) {
  16828. return "POST " + path +
  16829. " HTTP/1.1\r\n"
  16830. "Host: localhost\r\n"
  16831. "Content-Length: 2\r\n"
  16832. "Expect: 100-continue\r\n"
  16833. "\r\n";
  16834. }
  16835. class ExpectLazyContinueTest : public ::testing::Test {
  16836. protected:
  16837. void SetUp() override {
  16838. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16839. if (req.path == "/pre-routing") {
  16840. res.status = StatusCode::Unauthorized_401;
  16841. return Server::HandlerResponse::Handled;
  16842. }
  16843. return Server::HandlerResponse::Unhandled;
  16844. });
  16845. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16846. if (req.matched_route == "/pre-request") {
  16847. res.status = StatusCode::Forbidden_403;
  16848. return Server::HandlerResponse::Handled;
  16849. }
  16850. return Server::HandlerResponse::Unhandled;
  16851. });
  16852. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16853. res.set_content("ok", "text/plain");
  16854. });
  16855. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16856. res.set_content("ok", "text/plain");
  16857. });
  16858. svr_.Post("/reader-used", [](const Request &, Response &res,
  16859. const ContentReader &content_reader) {
  16860. std::string body;
  16861. content_reader([&](const char *data, size_t len) {
  16862. body.append(data, len);
  16863. return true;
  16864. });
  16865. res.set_content(body, "text/plain");
  16866. });
  16867. svr_.Post("/reader-unused",
  16868. [](const Request &, Response &res, const ContentReader &) {
  16869. res.set_content("ignored", "text/plain");
  16870. });
  16871. port_ = svr_.bind_to_any_port(HOST);
  16872. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16873. svr_.wait_until_ready();
  16874. }
  16875. void TearDown() override {
  16876. svr_.stop();
  16877. if (thread_.joinable()) { thread_.join(); }
  16878. }
  16879. // Sends `req` and reads until the server closes the connection. Returns
  16880. // false if the read had to wait for the client-side timeout instead.
  16881. bool send_until_closed(const std::string &req, std::string *resp) const {
  16882. auto start = std::chrono::steady_clock::now();
  16883. if (!send_request(3, req, resp, port_)) { return false; }
  16884. auto elapsed = std::chrono::steady_clock::now() - start;
  16885. return elapsed < std::chrono::seconds(2);
  16886. }
  16887. // The final response comes without `100 Continue`, and the server closes
  16888. // the connection since the body may or may not follow.
  16889. void expect_final_without_interim(const std::string &path,
  16890. const char *status_line) const {
  16891. std::string resp;
  16892. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16893. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16894. EXPECT_EQ(0u, resp.find(status_line));
  16895. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16896. }
  16897. Server svr_;
  16898. int port_ = 0;
  16899. thread thread_;
  16900. };
  16901. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16902. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16903. }
  16904. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16905. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16906. }
  16907. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16908. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16909. }
  16910. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16911. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16912. }
  16913. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16914. // The body follows once `100 Continue` has had time to arrive.
  16915. auto req = expect_headers_only("/reader-used");
  16916. req.insert(req.size() - 2, "Connection: close\r\n");
  16917. std::string resp;
  16918. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16919. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16920. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16921. EXPECT_NE(std::string::npos, resp.find("hi"));
  16922. }
  16923. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16924. // Large enough for the client to add `Expect: 100-continue` itself.
  16925. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16926. std::atomic<bool> body_sent{false};
  16927. Client cli(HOST, port_);
  16928. auto res = cli.Post(
  16929. "/pre-request", length,
  16930. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16931. body_sent = true;
  16932. std::string chunk(len, 'x');
  16933. sink.write(chunk.data(), chunk.size());
  16934. return true;
  16935. },
  16936. "application/octet-stream");
  16937. ASSERT_TRUE(res);
  16938. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16939. EXPECT_FALSE(body_sent);
  16940. }
  16941. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16942. Server svr;
  16943. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16944. return StatusCode::ExpectationFailed_417;
  16945. });
  16946. svr.Post("/p", [](const Request &, Response &res) {
  16947. res.set_content("ok", "text/plain");
  16948. });
  16949. auto port = svr.bind_to_any_port(HOST);
  16950. thread t = thread([&] { svr.listen_after_bind(); });
  16951. auto se = detail::scope_exit([&] {
  16952. svr.stop();
  16953. t.join();
  16954. });
  16955. svr.wait_until_ready();
  16956. std::string resp;
  16957. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16958. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16959. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16960. // Exactly one response: the route handler must not run after the 417.
  16961. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16962. }
  16963. #ifndef _WIN32
  16964. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16965. static constexpr char reject[] = "Unauthorized";
  16966. static constexpr char accept[] = "Upload accepted";
  16967. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16968. Server svr;
  16969. svr.set_expect_100_continue_handler(
  16970. [](const Request & /*req*/, Response &res) {
  16971. res.status = StatusCode::Unauthorized_401;
  16972. res.set_content(reject, "text/plain");
  16973. return res.status;
  16974. });
  16975. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16976. res.set_content(accept, "text/plain");
  16977. });
  16978. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16979. auto se = detail::scope_exit([&] {
  16980. svr.stop();
  16981. thread.join();
  16982. ASSERT_FALSE(svr.is_running());
  16983. });
  16984. svr.wait_until_ready();
  16985. {
  16986. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16987. curl_easy_init(), &curl_easy_cleanup};
  16988. ASSERT_NE(curl, nullptr);
  16989. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16990. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16991. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16992. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16993. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16994. &curl_slist_free_all};
  16995. ASSERT_NE(list, nullptr);
  16996. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16997. struct read_data {
  16998. size_t read_size;
  16999. size_t total_size;
  17000. } data = {0, total_size};
  17001. using read_callback_t =
  17002. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17003. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17004. void *userdata) -> size_t {
  17005. read_data *d = (read_data *)userdata;
  17006. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17007. std::fill_n(ptr, size * nmemb, 'A');
  17008. d->read_size += size * nmemb;
  17009. return size * nmemb;
  17010. };
  17011. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17012. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17013. std::vector<char> buffer;
  17014. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17015. using write_callback_t =
  17016. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17017. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17018. void *userdata) -> size_t {
  17019. std::vector<char> *buf = (std::vector<char> *)userdata;
  17020. buf->reserve(buf->size() + size * nmemb + 1);
  17021. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17022. return size * nmemb;
  17023. };
  17024. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17025. {
  17026. const auto res = curl_easy_perform(curl.get());
  17027. ASSERT_EQ(res, CURLE_OK);
  17028. }
  17029. {
  17030. auto response_code = long{};
  17031. const auto res =
  17032. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17033. ASSERT_EQ(res, CURLE_OK);
  17034. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17035. }
  17036. {
  17037. auto dl = curl_off_t{};
  17038. const auto res =
  17039. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17040. ASSERT_EQ(res, CURLE_OK);
  17041. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17042. }
  17043. {
  17044. buffer.push_back('\0');
  17045. ASSERT_STRCASEEQ(buffer.data(), reject);
  17046. }
  17047. }
  17048. }
  17049. #endif
  17050. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17051. // Regression test for #2458.
  17052. //
  17053. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17054. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17055. // ticket can make the client socket spuriously readable during the
  17056. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17057. // the client withholds the body and then blocks reading a response that never
  17058. // comes, failing with `Failed to read connection`.
  17059. //
  17060. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17061. // within the timeout. This raw OpenSSL server deliberately never sends
  17062. // `100 Continue`; the client must still deliver the body and receive 200.
  17063. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17064. signal(SIGPIPE, SIG_IGN);
  17065. const auto port = PORT + 4;
  17066. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17067. ASSERT_NE(srv, INVALID_SOCKET);
  17068. int opt = 1;
  17069. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17070. sockaddr_in addr{};
  17071. addr.sin_family = AF_INET;
  17072. addr.sin_port = htons(static_cast<uint16_t>(port));
  17073. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17074. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17075. ASSERT_EQ(0, ::listen(srv, 1));
  17076. std::atomic<size_t> server_body_bytes{0};
  17077. auto server_thread = std::thread([&] {
  17078. sockaddr_in cli_addr{};
  17079. socklen_t cli_len = sizeof(cli_addr);
  17080. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17081. if (cli == INVALID_SOCKET) { return; }
  17082. // Bound the lifetime of the server side so a buggy client (which never
  17083. // sends the body) cannot make this thread block forever on join.
  17084. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17085. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17086. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17087. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17088. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17089. SSL *ssl = SSL_new(ctx);
  17090. SSL_set_fd(ssl, static_cast<int>(cli));
  17091. if (SSL_accept(ssl) > 0) {
  17092. // Read the request headers. Reading here also flushes the TLS 1.3
  17093. // session tickets to the client. Deliberately do NOT send
  17094. // `100 Continue`.
  17095. std::string buf;
  17096. char tmp[1024];
  17097. while (buf.find("\r\n\r\n") == std::string::npos) {
  17098. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17099. if (n <= 0) { break; }
  17100. buf.append(tmp, static_cast<size_t>(n));
  17101. }
  17102. // A correct client sends the body now; count what arrives.
  17103. auto pos = buf.find("\r\n\r\n");
  17104. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17105. while (body < 4096) {
  17106. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17107. if (n <= 0) { break; }
  17108. body += static_cast<size_t>(n);
  17109. }
  17110. server_body_bytes = body;
  17111. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17112. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17113. SSL_shutdown(ssl);
  17114. }
  17115. SSL_free(ssl);
  17116. detail::close_socket(cli);
  17117. SSL_CTX_free(ctx);
  17118. });
  17119. auto se = detail::scope_exit([&] {
  17120. server_thread.join();
  17121. detail::close_socket(srv);
  17122. });
  17123. SSLClient cli("127.0.0.1", port);
  17124. cli.enable_server_certificate_verification(false);
  17125. cli.set_connection_timeout(5, 0);
  17126. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17127. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17128. std::string body(4096, 'A');
  17129. auto res = cli.Put("/api/test", body, "application/json");
  17130. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17131. EXPECT_EQ(StatusCode::OK_200, res->status);
  17132. EXPECT_EQ(body.size(), server_body_bytes.load());
  17133. }
  17134. #endif
  17135. template <typename S, typename C>
  17136. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17137. svr.Get("/stream", [&](const Request &, Response &res) {
  17138. auto data = new std::string("01234567890123456789");
  17139. res.set_content_provider(
  17140. data->size(), "text/plain",
  17141. [&, data](size_t offset, size_t length, DataSink &sink) {
  17142. const size_t DATA_CHUNK_SIZE = 4;
  17143. const auto &d = *data;
  17144. std::this_thread::sleep_for(std::chrono::seconds(1));
  17145. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17146. return true;
  17147. },
  17148. [data](bool success) {
  17149. EXPECT_FALSE(success);
  17150. delete data;
  17151. });
  17152. });
  17153. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17154. auto i = new size_t(0);
  17155. res.set_content_provider(
  17156. "text/plain",
  17157. [i](size_t, DataSink &sink) {
  17158. if (*i < 5) {
  17159. std::this_thread::sleep_for(std::chrono::seconds(1));
  17160. sink.write("abcd", 4);
  17161. (*i)++;
  17162. } else {
  17163. sink.done();
  17164. }
  17165. return true;
  17166. },
  17167. [i](bool success) {
  17168. EXPECT_FALSE(success);
  17169. delete i;
  17170. });
  17171. });
  17172. svr.Get("/chunked", [&](const Request &, Response &res) {
  17173. auto i = new size_t(0);
  17174. res.set_chunked_content_provider(
  17175. "text/plain",
  17176. [i](size_t, DataSink &sink) {
  17177. if (*i < 5) {
  17178. std::this_thread::sleep_for(std::chrono::seconds(1));
  17179. sink.os << "abcd";
  17180. (*i)++;
  17181. } else {
  17182. sink.done();
  17183. }
  17184. return true;
  17185. },
  17186. [i](bool success) {
  17187. EXPECT_FALSE(success);
  17188. delete i;
  17189. });
  17190. });
  17191. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17192. auto se = detail::scope_exit([&] {
  17193. svr.stop();
  17194. listen_thread.join();
  17195. ASSERT_FALSE(svr.is_running());
  17196. });
  17197. svr.wait_until_ready();
  17198. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17199. {
  17200. auto start = std::chrono::steady_clock::now();
  17201. auto res = cli.Get("/stream");
  17202. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17203. std::chrono::steady_clock::now() - start)
  17204. .count();
  17205. ASSERT_FALSE(res);
  17206. EXPECT_EQ(Error::Read, res.error());
  17207. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17208. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17209. }
  17210. {
  17211. auto start = std::chrono::steady_clock::now();
  17212. auto res = cli.Get("/stream_without_length");
  17213. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17214. std::chrono::steady_clock::now() - start)
  17215. .count();
  17216. ASSERT_FALSE(res);
  17217. EXPECT_EQ(Error::Read, res.error());
  17218. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17219. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17220. }
  17221. {
  17222. auto start = std::chrono::steady_clock::now();
  17223. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17224. EXPECT_EQ("abcd", string(data, data_length));
  17225. return true;
  17226. });
  17227. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17228. std::chrono::steady_clock::now() - start)
  17229. .count();
  17230. ASSERT_FALSE(res);
  17231. EXPECT_EQ(Error::Read, res.error());
  17232. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17233. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17234. }
  17235. }
  17236. TEST(MaxTimeoutTest, ContentStream) {
  17237. time_t timeout = 2000;
  17238. time_t threshold = 200;
  17239. Server svr;
  17240. Client cli("localhost", PORT);
  17241. max_timeout_test(svr, cli, timeout, threshold);
  17242. }
  17243. #ifdef CPPHTTPLIB_SSL_ENABLED
  17244. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17245. time_t timeout = 2000;
  17246. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17247. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17248. SSLClient cli("localhost", PORT);
  17249. cli.enable_server_certificate_verification(false);
  17250. max_timeout_test(svr, cli, timeout, threshold);
  17251. }
  17252. #endif
  17253. class EventDispatcher {
  17254. public:
  17255. EventDispatcher() {}
  17256. bool wait_event(DataSink *sink) {
  17257. unique_lock<mutex> lk(m_);
  17258. int id = id_;
  17259. // Wait with timeout to prevent hanging if client disconnects
  17260. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17261. [&] { return cid_ == id; })) {
  17262. return false; // Timeout occurred
  17263. }
  17264. sink->write(message_.data(), message_.size());
  17265. return true;
  17266. }
  17267. void send_event(const string &message) {
  17268. lock_guard<mutex> lk(m_);
  17269. cid_ = id_++;
  17270. message_ = message;
  17271. cv_.notify_all();
  17272. }
  17273. private:
  17274. mutex m_;
  17275. condition_variable cv_;
  17276. atomic_int id_{0};
  17277. atomic_int cid_{-1};
  17278. string message_;
  17279. };
  17280. TEST(ClientInThreadTest, Issue2068) {
  17281. EventDispatcher ed;
  17282. Server svr;
  17283. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17284. res.set_chunked_content_provider("text/event-stream",
  17285. [&](size_t /*offset*/, DataSink &sink) {
  17286. return ed.wait_event(&sink);
  17287. });
  17288. });
  17289. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17290. svr.wait_until_ready();
  17291. thread event_thread([&] {
  17292. int id = 0;
  17293. while (svr.is_running()) {
  17294. this_thread::sleep_for(chrono::milliseconds(500));
  17295. std::stringstream ss;
  17296. ss << "data: " << id << "\n\n";
  17297. ed.send_event(ss.str());
  17298. id++;
  17299. }
  17300. });
  17301. auto se = detail::scope_exit([&] {
  17302. svr.stop();
  17303. listen_thread.join();
  17304. event_thread.join();
  17305. ASSERT_FALSE(svr.is_running());
  17306. });
  17307. {
  17308. auto client = detail::make_unique<Client>(HOST, PORT);
  17309. client->set_read_timeout(std::chrono::minutes(10));
  17310. std::atomic<bool> stop{false};
  17311. std::thread t([&] {
  17312. client->Get("/event1",
  17313. [&](const char *, size_t) -> bool { return !stop; });
  17314. });
  17315. std::this_thread::sleep_for(std::chrono::seconds(2));
  17316. stop = true;
  17317. client->stop();
  17318. t.join();
  17319. // Reset client after thread has finished
  17320. client.reset();
  17321. }
  17322. }
  17323. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17324. auto handled = false;
  17325. Server svr;
  17326. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17327. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17328. auto se = detail::scope_exit([&] {
  17329. svr.stop();
  17330. t.join();
  17331. ASSERT_FALSE(svr.is_running());
  17332. ASSERT_FALSE(handled);
  17333. });
  17334. svr.wait_until_ready();
  17335. // Two Content-Length headers with different values — must be rejected
  17336. auto req = "POST /test HTTP/1.1\r\n"
  17337. "Content-Length: 5\r\n"
  17338. "Content-Length: 10\r\n"
  17339. "\r\n"
  17340. "hello";
  17341. std::string response;
  17342. ASSERT_TRUE(send_request(1, req, &response));
  17343. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17344. response.substr(0, response.find("\r\n")));
  17345. }
  17346. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17347. auto handled = false;
  17348. Server svr;
  17349. svr.Post("/test", [&](const Request &, Response &res) {
  17350. handled = true;
  17351. res.set_content("ok", "text/plain");
  17352. });
  17353. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17354. auto se = detail::scope_exit([&] {
  17355. svr.stop();
  17356. t.join();
  17357. ASSERT_FALSE(svr.is_running());
  17358. ASSERT_TRUE(handled);
  17359. });
  17360. svr.wait_until_ready();
  17361. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17362. auto req = "POST /test HTTP/1.1\r\n"
  17363. "Host: localhost\r\n"
  17364. "Content-Length: 5\r\n"
  17365. "Content-Length: 5\r\n"
  17366. "\r\n"
  17367. "hello";
  17368. std::string response;
  17369. ASSERT_TRUE(send_request(1, req, &response));
  17370. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17371. }
  17372. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17373. Server svr;
  17374. svr.Get("/test", [](const Request &, Response &res) {
  17375. res.set_content("ok", "text/plain");
  17376. });
  17377. auto port = svr.bind_to_any_port(HOST);
  17378. thread t = thread([&] { svr.listen_after_bind(); });
  17379. auto se = detail::scope_exit([&] {
  17380. svr.stop();
  17381. t.join();
  17382. ASSERT_FALSE(svr.is_running());
  17383. });
  17384. svr.wait_until_ready();
  17385. auto status_line = [&](const std::string &host_lines) {
  17386. std::string res;
  17387. send_request(
  17388. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17389. &res, port);
  17390. return res.substr(0, res.find("\r\n"));
  17391. };
  17392. const char *accepted[] = {
  17393. "Host: localhost\r\n",
  17394. "Host: a.example:8080\r\n",
  17395. "Host: my_service\r\n",
  17396. "Host: [::1]:8080\r\n",
  17397. "Host: [fe80::1%25eth0]\r\n",
  17398. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17399. };
  17400. for (auto host_lines : accepted) {
  17401. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17402. }
  17403. const char *rejected[] = {
  17404. "Host: a.example\r\nHost: b.example\r\n",
  17405. "Host: a.example\r\nHost: a.example\r\n",
  17406. "Host: a@b.example\r\n",
  17407. "Host: a.example/b\r\n",
  17408. "Host: a.example\\b\r\n",
  17409. "Host: a.example?b\r\n",
  17410. "Host: a.example#b\r\n",
  17411. "Host: a.example b.example\r\n",
  17412. };
  17413. for (auto host_lines : rejected) {
  17414. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17415. << host_lines;
  17416. }
  17417. }
  17418. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17419. Server svr;
  17420. svr.Get("/", [](const Request &req, Response &res) {
  17421. EXPECT_EQ(2U, req.trailers.size());
  17422. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17423. // Denied
  17424. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17425. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17426. // Accepted
  17427. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17428. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17429. EXPECT_TRUE(req.has_trailer("X-World"));
  17430. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17431. res.set_content("ok", "text/plain");
  17432. });
  17433. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17434. auto se = detail::scope_exit([&] {
  17435. svr.stop();
  17436. t.join();
  17437. ASSERT_FALSE(svr.is_running());
  17438. });
  17439. svr.wait_until_ready();
  17440. const std::string req = "GET / HTTP/1.1\r\n"
  17441. "Transfer-Encoding: chunked\r\n"
  17442. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17443. "\r\n"
  17444. "0\r\n"
  17445. "Content-Length: 10\r\n"
  17446. "Host: internal.local\r\n"
  17447. "Content-Type: malicious/content\r\n"
  17448. "Cookie: any\r\n"
  17449. "Set-Cookie: any\r\n"
  17450. "X-Forwarded-For: attacker.com\r\n"
  17451. "X-Real-Ip: 1.1.1.1\r\n"
  17452. "X-Hello: hello\r\n"
  17453. "X-World: world\r\n"
  17454. "\r\n";
  17455. std::string res;
  17456. ASSERT_TRUE(send_request(1, req, &res));
  17457. }
  17458. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17459. // several field lines, and the combined value is what has to be parsed. A
  17460. // Trailer field split across lines therefore declares every name it lists;
  17461. // reading only the first line silently drops the trailers the later lines
  17462. // declare. The prohibited-trailer filter still applies to every line.
  17463. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17464. Server svr;
  17465. size_t observed_trailer_count = 0;
  17466. std::string observed_hello;
  17467. std::string observed_world;
  17468. bool observed_content_length = true;
  17469. svr.Get("/", [&](const Request &req, Response &res) {
  17470. observed_trailer_count = req.trailers.size();
  17471. observed_hello = req.get_trailer_value("X-Hello");
  17472. observed_world = req.get_trailer_value("X-World");
  17473. observed_content_length = req.has_trailer("Content-Length");
  17474. res.set_content("ok", "text/plain");
  17475. });
  17476. auto port = svr.bind_to_any_port(HOST);
  17477. thread t = thread([&]() { svr.listen_after_bind(); });
  17478. auto se = detail::scope_exit([&] {
  17479. svr.stop();
  17480. t.join();
  17481. ASSERT_FALSE(svr.is_running());
  17482. });
  17483. svr.wait_until_ready();
  17484. const std::string req = "GET / HTTP/1.1\r\n"
  17485. "Host: localhost\r\n"
  17486. "Transfer-Encoding: chunked\r\n"
  17487. "Trailer: X-Hello\r\n"
  17488. "Trailer: X-World, Content-Length\r\n"
  17489. "\r\n"
  17490. "0\r\n"
  17491. "X-Hello: hello\r\n"
  17492. "X-World: world\r\n"
  17493. "Content-Length: 10\r\n"
  17494. "\r\n";
  17495. std::string res;
  17496. ASSERT_TRUE(send_request(1, req, &res, port));
  17497. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17498. // Accepted: both field lines contribute to the declared set
  17499. EXPECT_EQ(2U, observed_trailer_count);
  17500. EXPECT_EQ(observed_hello, "hello");
  17501. EXPECT_EQ(observed_world, "world");
  17502. // Denied: a prohibited name stays prohibited on a later field line
  17503. EXPECT_FALSE(observed_content_length);
  17504. }
  17505. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17506. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17507. // unbounded run of fields that are never declared, because the counter would
  17508. // only advance for declared fields.
  17509. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17510. Server svr;
  17511. bool handler_called = false;
  17512. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17513. handler_called = true;
  17514. res.set_content("ok", "text/plain");
  17515. });
  17516. auto port = svr.bind_to_any_port(HOST);
  17517. thread t = thread([&]() { svr.listen_after_bind(); });
  17518. auto se = detail::scope_exit([&] {
  17519. svr.stop();
  17520. t.join();
  17521. ASSERT_FALSE(svr.is_running());
  17522. });
  17523. svr.wait_until_ready();
  17524. // Declare nothing, then send far more undeclared trailer fields than the
  17525. // header-count limit. Parsing must stop and reject the request rather than
  17526. // read every line.
  17527. std::string req = "GET / HTTP/1.1\r\n"
  17528. "Transfer-Encoding: chunked\r\n"
  17529. "\r\n"
  17530. "0\r\n";
  17531. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17532. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17533. }
  17534. req += "\r\n";
  17535. std::string res;
  17536. ASSERT_TRUE(send_request(1, req, &res, port));
  17537. // The request is rejected before the handler runs.
  17538. EXPECT_FALSE(handler_called);
  17539. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17540. }
  17541. // The set of declared trailer names is capped so a peer cannot grow it without
  17542. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17543. // declared past the cap is not honored, even if the field is actually sent.
  17544. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17545. Server svr;
  17546. // One name inside the cap and one past it, so the test tracks the cap rather
  17547. // than a fixed count.
  17548. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17549. const std::string within_cap_name = "X-T-0";
  17550. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17551. bool observed_within_cap = false;
  17552. bool observed_past_cap = false;
  17553. svr.Get("/", [&](const Request &req, Response &res) {
  17554. observed_within_cap = req.has_trailer(within_cap_name);
  17555. observed_past_cap = req.has_trailer(past_cap_name);
  17556. res.set_content("ok", "text/plain");
  17557. });
  17558. auto port = svr.bind_to_any_port(HOST);
  17559. thread t = thread([&]() { svr.listen_after_bind(); });
  17560. auto se = detail::scope_exit([&] {
  17561. svr.stop();
  17562. t.join();
  17563. ASSERT_FALSE(svr.is_running());
  17564. });
  17565. svr.wait_until_ready();
  17566. // Declare more trailer names than the cap in a single Trailer field, then
  17567. // actually send the first (within the cap) and the last (past it).
  17568. std::string trailer_decl = "Trailer: ";
  17569. for (int i = 0; i < declared_count; i++) {
  17570. if (i != 0) { trailer_decl += ", "; }
  17571. trailer_decl += "X-T-" + std::to_string(i);
  17572. }
  17573. trailer_decl += "\r\n";
  17574. const std::string req = "GET / HTTP/1.1\r\n"
  17575. "Host: localhost\r\n"
  17576. "Transfer-Encoding: chunked\r\n" +
  17577. trailer_decl +
  17578. "\r\n"
  17579. "0\r\n" +
  17580. within_cap_name + ": a\r\n" + past_cap_name +
  17581. ": b\r\n"
  17582. "\r\n";
  17583. std::string res;
  17584. ASSERT_TRUE(send_request(1, req, &res, port));
  17585. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17586. // A name within the cap is honored; one declared past the cap is dropped.
  17587. EXPECT_TRUE(observed_within_cap);
  17588. EXPECT_FALSE(observed_past_cap);
  17589. }
  17590. // A direct client that is not listed in trusted_proxies must not be able to
  17591. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17592. // the peer address on the actual TCP connection determines whether the
  17593. // header is honored.
  17594. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17595. Server svr;
  17596. // Deliberately does NOT include the loopback address the test client
  17597. // actually connects from, so the direct connection is not a trusted proxy.
  17598. svr.set_trusted_proxies({"203.0.113.66"});
  17599. std::string observed_remote_addr;
  17600. svr.Get("/ip", [&](const Request &req, Response &res) {
  17601. observed_remote_addr = req.remote_addr;
  17602. res.set_content("ok", "text/plain");
  17603. });
  17604. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17605. auto se = detail::scope_exit([&] {
  17606. svr.stop();
  17607. t.join();
  17608. ASSERT_FALSE(svr.is_running());
  17609. });
  17610. svr.wait_until_ready();
  17611. Client cli(HOST, PORT);
  17612. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17614. EXPECT_EQ(StatusCode::OK_200, res->status);
  17615. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17616. // ignored entirely and the real connection-level address retained.
  17617. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17618. observed_remote_addr == "127.0.0.1");
  17619. }
  17620. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17621. Server svr;
  17622. std::string observed_remote_addr;
  17623. std::string observed_xff;
  17624. svr.Get("/ip", [&](const Request &req, Response &res) {
  17625. observed_remote_addr = req.remote_addr;
  17626. observed_xff = req.get_header_value("X-Forwarded-For");
  17627. res.set_content("ok", "text/plain");
  17628. });
  17629. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17630. auto se = detail::scope_exit([&] {
  17631. svr.stop();
  17632. t.join();
  17633. ASSERT_FALSE(svr.is_running());
  17634. });
  17635. svr.wait_until_ready();
  17636. Client cli(HOST, PORT);
  17637. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17639. EXPECT_EQ(StatusCode::OK_200, res->status);
  17640. EXPECT_EQ(observed_xff, "203.0.113.66");
  17641. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17642. observed_remote_addr == "127.0.0.1");
  17643. }
  17644. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17645. Server svr;
  17646. svr.set_trusted_proxies({"203.0.113.66"});
  17647. std::string observed_remote_addr;
  17648. std::string observed_xff;
  17649. svr.Get("/ip", [&](const Request &req, Response &res) {
  17650. observed_remote_addr = req.remote_addr;
  17651. observed_xff = req.get_header_value("X-Forwarded-For");
  17652. res.set_content("ok", "text/plain");
  17653. });
  17654. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17655. auto se = detail::scope_exit([&] {
  17656. svr.stop();
  17657. t.join();
  17658. ASSERT_FALSE(svr.is_running());
  17659. });
  17660. svr.wait_until_ready();
  17661. Client cli(HOST, PORT);
  17662. auto res = cli.Get("/ip");
  17663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17664. EXPECT_EQ(StatusCode::OK_200, res->status);
  17665. EXPECT_EQ(observed_xff, "");
  17666. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17667. observed_remote_addr == "127.0.0.1");
  17668. }
  17669. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17670. Server svr;
  17671. // Include the loopback address the test client actually connects from, so
  17672. // the direct connection itself is recognized as the trusted proxy hop.
  17673. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17674. std::string observed_remote_addr;
  17675. std::string observed_xff;
  17676. svr.Get("/ip", [&](const Request &req, Response &res) {
  17677. observed_remote_addr = req.remote_addr;
  17678. observed_xff = req.get_header_value("X-Forwarded-For");
  17679. res.set_content("ok", "text/plain");
  17680. });
  17681. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17682. auto se = detail::scope_exit([&] {
  17683. svr.stop();
  17684. t.join();
  17685. ASSERT_FALSE(svr.is_running());
  17686. });
  17687. svr.wait_until_ready();
  17688. Client cli(HOST, PORT);
  17689. auto res = cli.Get(
  17690. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17692. EXPECT_EQ(StatusCode::OK_200, res->status);
  17693. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17694. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17695. }
  17696. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17697. Server svr;
  17698. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17699. std::string observed_remote_addr;
  17700. std::string observed_xff;
  17701. svr.Get("/ip", [&](const Request &req, Response &res) {
  17702. observed_remote_addr = req.remote_addr;
  17703. observed_xff = req.get_header_value("X-Forwarded-For");
  17704. res.set_content("ok", "text/plain");
  17705. });
  17706. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17707. auto se = detail::scope_exit([&] {
  17708. svr.stop();
  17709. t.join();
  17710. ASSERT_FALSE(svr.is_running());
  17711. });
  17712. svr.wait_until_ready();
  17713. Client cli(HOST, PORT);
  17714. auto res = cli.Get(
  17715. "/ip",
  17716. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17718. EXPECT_EQ(StatusCode::OK_200, res->status);
  17719. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17720. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17721. }
  17722. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17723. Server svr;
  17724. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17725. std::string observed_remote_addr;
  17726. std::string observed_xff;
  17727. svr.Get("/ip", [&](const Request &req, Response &res) {
  17728. observed_remote_addr = req.remote_addr;
  17729. observed_xff = req.get_header_value("X-Forwarded-For");
  17730. res.set_content("ok", "text/plain");
  17731. });
  17732. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17733. auto se = detail::scope_exit([&] {
  17734. svr.stop();
  17735. t.join();
  17736. ASSERT_FALSE(svr.is_running());
  17737. });
  17738. svr.wait_until_ready();
  17739. Client cli(HOST, PORT);
  17740. auto res = cli.Get(
  17741. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17743. EXPECT_EQ(StatusCode::OK_200, res->status);
  17744. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17745. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17746. // and must not be selected.
  17747. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17748. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17749. }
  17750. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17751. Server svr;
  17752. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17753. std::string observed_remote_addr;
  17754. svr.Get("/ip", [&](const Request &req, Response &res) {
  17755. observed_remote_addr = req.remote_addr;
  17756. res.set_content("ok", "text/plain");
  17757. });
  17758. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17759. auto se = detail::scope_exit([&] {
  17760. svr.stop();
  17761. t.join();
  17762. ASSERT_FALSE(svr.is_running());
  17763. });
  17764. svr.wait_until_ready();
  17765. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17766. // a forged address and the trusted proxy's own address; the forged value must
  17767. // not win over the address the trusted proxy actually recorded.
  17768. Client cli(HOST, PORT);
  17769. auto res = cli.Get(
  17770. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17772. EXPECT_EQ(StatusCode::OK_200, res->status);
  17773. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17774. }
  17775. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17776. Server svr;
  17777. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17778. std::string observed_remote_addr;
  17779. std::string observed_xff;
  17780. svr.Get("/ip", [&](const Request &req, Response &res) {
  17781. observed_remote_addr = req.remote_addr;
  17782. observed_xff = req.get_header_value("X-Forwarded-For");
  17783. res.set_content("ok", "text/plain");
  17784. });
  17785. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17786. auto se = detail::scope_exit([&] {
  17787. svr.stop();
  17788. t.join();
  17789. ASSERT_FALSE(svr.is_running());
  17790. });
  17791. svr.wait_until_ready();
  17792. Client cli(HOST, PORT);
  17793. auto res = cli.Get(
  17794. "/ip",
  17795. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17797. EXPECT_EQ(StatusCode::OK_200, res->status);
  17798. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17799. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17800. }
  17801. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17802. Server svr;
  17803. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17804. std::string observed_remote_addr;
  17805. std::string observed_xff;
  17806. svr.Get("/ip", [&](const Request &req, Response &res) {
  17807. observed_remote_addr = req.remote_addr;
  17808. observed_xff = req.get_header_value("X-Forwarded-For");
  17809. res.set_content("ok", "text/plain");
  17810. });
  17811. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17812. auto se = detail::scope_exit([&] {
  17813. svr.stop();
  17814. t.join();
  17815. ASSERT_FALSE(svr.is_running());
  17816. });
  17817. svr.wait_until_ready();
  17818. std::string raw_req =
  17819. "GET /ip HTTP/1.1\r\n"
  17820. "Host: localhost\r\n"
  17821. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17822. "Connection: close\r\n"
  17823. "\r\n";
  17824. std::string out;
  17825. ASSERT_TRUE(send_request(5, raw_req, &out));
  17826. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17827. // Header parser trims surrounding whitespace of the header value
  17828. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17829. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17830. }
  17831. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17832. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17833. // their own X-Forwarded-For as a separate field line rather than extending the
  17834. // one the client sent, so every occurrence has to be taken into account.
  17835. // Reading only the first one hands back the address the client chose.
  17836. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17837. Server svr;
  17838. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17839. std::string observed_remote_addr;
  17840. size_t observed_xff_count = 0;
  17841. svr.Get("/ip", [&](const Request &req, Response &res) {
  17842. observed_remote_addr = req.remote_addr;
  17843. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17844. res.set_content("ok", "text/plain");
  17845. });
  17846. auto port = svr.bind_to_any_port(HOST);
  17847. thread t = thread([&]() { svr.listen_after_bind(); });
  17848. auto se = detail::scope_exit([&] {
  17849. svr.stop();
  17850. t.join();
  17851. ASSERT_FALSE(svr.is_running());
  17852. });
  17853. svr.wait_until_ready();
  17854. // The client supplies the first field line; the trusted proxy appends the
  17855. // address it observed as a second one.
  17856. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17857. "Host: localhost\r\n"
  17858. "X-Forwarded-For: 1.2.3.4\r\n"
  17859. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17860. "Connection: close\r\n"
  17861. "\r\n";
  17862. std::string out;
  17863. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17864. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17865. EXPECT_EQ(observed_xff_count, 2U);
  17866. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17867. // The same chain spread over one field line per hop derives the same client
  17868. // address, i.e. the split and the comma-joined representations agree.
  17869. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17870. "Host: localhost\r\n"
  17871. "X-Forwarded-For: 1.2.3.4\r\n"
  17872. "X-Forwarded-For: 198.51.100.23\r\n"
  17873. "X-Forwarded-For: 192.0.2.45\r\n"
  17874. "Connection: close\r\n"
  17875. "\r\n";
  17876. out.clear();
  17877. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17878. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17879. EXPECT_EQ(observed_xff_count, 3U);
  17880. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17881. }
  17882. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17883. // crash the server (it used to call front() on an empty vector inside
  17884. // get_client_ip). The connection-level remote address must be retained instead.
  17885. static void run_malformed_xff_test(const std::string &xff_value) {
  17886. Server svr;
  17887. svr.set_trusted_proxies({"192.0.2.45"});
  17888. std::string observed_remote_addr;
  17889. svr.Get("/ip", [&](const Request &req, Response &res) {
  17890. observed_remote_addr = req.remote_addr;
  17891. res.set_content("ok", "text/plain");
  17892. });
  17893. int port = 0;
  17894. thread t = thread([&]() {
  17895. port = svr.bind_to_any_port(HOST);
  17896. svr.listen_after_bind();
  17897. });
  17898. auto se = detail::scope_exit([&] {
  17899. svr.stop();
  17900. t.join();
  17901. ASSERT_FALSE(svr.is_running());
  17902. });
  17903. svr.wait_until_ready();
  17904. Client cli(HOST, port);
  17905. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17907. EXPECT_EQ(StatusCode::OK_200, res->status);
  17908. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17909. observed_remote_addr == "127.0.0.1");
  17910. }
  17911. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17912. run_malformed_xff_test("");
  17913. }
  17914. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17915. run_malformed_xff_test(",");
  17916. }
  17917. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17918. run_malformed_xff_test(", , ,");
  17919. }
  17920. // The same rule applies to Accept: a request whose acceptable types are spread
  17921. // over several field lines must be negotiated against all of them.
  17922. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17923. // case-insensitive connection options. Comparing the whole field value against
  17924. // one option misses a client that sends several of them, and misses every
  17925. // casing but the one written in the comparison.
  17926. //
  17927. // Sends req, reads the response, then reuses the same socket for a second
  17928. // request to find out whether the server kept the connection.
  17929. static void probe_connection_reuse(int port, const std::string &req,
  17930. bool *announced_close, bool *reusable) {
  17931. auto error = Error::Success;
  17932. auto sock = detail::create_client_socket(
  17933. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17934. /*connection_timeout_sec=*/5, 0,
  17935. /*read_timeout_sec=*/1, 0,
  17936. /*write_timeout_sec=*/5, 0, std::string(), error);
  17937. ASSERT_NE(sock, INVALID_SOCKET);
  17938. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17939. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17940. "Host: localhost\r\n"
  17941. "Connection: close\r\n"
  17942. "\r\n";
  17943. std::string first_response;
  17944. std::string second_response;
  17945. detail::process_client_socket(
  17946. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17947. [&](Stream &strm) {
  17948. if (strm.write(req.data(), req.size()) !=
  17949. static_cast<ssize_t>(req.size())) {
  17950. return false;
  17951. }
  17952. char buf[512];
  17953. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17954. // Headers plus the two-byte body of the handler below
  17955. while (reader.getline()) {
  17956. first_response += reader.ptr();
  17957. if (first_response.find("ok") != std::string::npos) { break; }
  17958. }
  17959. if (strm.write(second.data(), second.size()) !=
  17960. static_cast<ssize_t>(second.size())) {
  17961. return true;
  17962. }
  17963. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17964. while (reader2.getline()) {
  17965. second_response += reader2.ptr();
  17966. if (second_response.find("ok") != std::string::npos) { break; }
  17967. }
  17968. return true;
  17969. });
  17970. *announced_close =
  17971. first_response.find("Connection: close") != std::string::npos;
  17972. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17973. }
  17974. class ConnectionTokenTest : public ::testing::Test {
  17975. protected:
  17976. void SetUp() override {
  17977. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17978. res.set_content("ok", "text/plain");
  17979. });
  17980. port_ = svr_.bind_to_any_port(HOST);
  17981. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17982. svr_.wait_until_ready();
  17983. }
  17984. void TearDown() override {
  17985. svr_.stop();
  17986. if (thread_.joinable()) { thread_.join(); }
  17987. }
  17988. Server svr_;
  17989. int port_ = 0;
  17990. thread thread_;
  17991. };
  17992. // "close" alongside another option still closes the connection, and the
  17993. // response says so rather than leaving the peer to discover it.
  17994. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17995. bool announced_close = false;
  17996. bool reusable = true;
  17997. probe_connection_reuse(port_,
  17998. "GET /keepalive HTTP/1.1\r\n"
  17999. "Host: localhost\r\n"
  18000. "Connection: keep-alive, close\r\n"
  18001. "\r\n",
  18002. &announced_close, &reusable);
  18003. EXPECT_TRUE(announced_close);
  18004. EXPECT_FALSE(reusable);
  18005. }
  18006. // "close" split over two field lines is the same list, so it is honored too.
  18007. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18008. bool announced_close = false;
  18009. bool reusable = true;
  18010. probe_connection_reuse(port_,
  18011. "GET /keepalive HTTP/1.1\r\n"
  18012. "Host: localhost\r\n"
  18013. "Connection: keep-alive\r\n"
  18014. "Connection: close\r\n"
  18015. "\r\n",
  18016. &announced_close, &reusable);
  18017. EXPECT_TRUE(announced_close);
  18018. EXPECT_FALSE(reusable);
  18019. }
  18020. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18021. // keep-alive in the spelling everyone actually sends keeps its connection.
  18022. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18023. bool announced_close = false;
  18024. bool reusable = false;
  18025. probe_connection_reuse(port_,
  18026. "GET /keepalive HTTP/1.0\r\n"
  18027. "Host: localhost\r\n"
  18028. "Connection: keep-alive\r\n"
  18029. "\r\n",
  18030. &announced_close, &reusable);
  18031. EXPECT_FALSE(announced_close);
  18032. EXPECT_TRUE(reusable);
  18033. }
  18034. // A token the value merely contains is not the token itself.
  18035. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18036. bool announced_close = false;
  18037. bool reusable = false;
  18038. probe_connection_reuse(port_,
  18039. "GET /keepalive HTTP/1.1\r\n"
  18040. "Host: localhost\r\n"
  18041. "Connection: notclose\r\n"
  18042. "\r\n",
  18043. &announced_close, &reusable);
  18044. EXPECT_FALSE(announced_close);
  18045. EXPECT_TRUE(reusable);
  18046. }
  18047. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18048. Server svr;
  18049. std::vector<std::string> observed_types;
  18050. svr.Get("/", [&](const Request &req, Response &res) {
  18051. observed_types = req.accept_content_types;
  18052. res.set_content("ok", "text/plain");
  18053. });
  18054. auto port = svr.bind_to_any_port(HOST);
  18055. thread t = thread([&]() { svr.listen_after_bind(); });
  18056. auto se = detail::scope_exit([&] {
  18057. svr.stop();
  18058. t.join();
  18059. ASSERT_FALSE(svr.is_running());
  18060. });
  18061. svr.wait_until_ready();
  18062. Client cli(HOST, port);
  18063. Headers headers;
  18064. headers.emplace("Accept", "text/plain;q=0.5");
  18065. headers.emplace("Accept", "application/json");
  18066. auto res = cli.Get("/", headers);
  18067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18068. EXPECT_EQ(StatusCode::OK_200, res->status);
  18069. // Sorted by q-value, so the second field line's type comes first
  18070. ASSERT_EQ(2U, observed_types.size());
  18071. EXPECT_EQ("application/json", observed_types[0]);
  18072. EXPECT_EQ("text/plain", observed_types[1]);
  18073. }
  18074. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18075. // empty field line must not contribute a bare comma to the combined value.
  18076. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18077. Server svr;
  18078. std::vector<std::string> observed_types;
  18079. svr.Get("/", [&](const Request &req, Response &res) {
  18080. observed_types = req.accept_content_types;
  18081. res.set_content("ok", "text/plain");
  18082. });
  18083. auto port = svr.bind_to_any_port(HOST);
  18084. thread t = thread([&]() { svr.listen_after_bind(); });
  18085. auto se = detail::scope_exit([&] {
  18086. svr.stop();
  18087. t.join();
  18088. ASSERT_FALSE(svr.is_running());
  18089. });
  18090. svr.wait_until_ready();
  18091. // Empty first field line, then a real one
  18092. std::string raw_req = "GET / HTTP/1.1\r\n"
  18093. "Host: localhost\r\n"
  18094. "Accept:\r\n"
  18095. "Accept: application/json\r\n"
  18096. "Connection: close\r\n"
  18097. "\r\n";
  18098. std::string out;
  18099. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18100. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18101. ASSERT_EQ(1U, observed_types.size());
  18102. EXPECT_EQ("application/json", observed_types[0]);
  18103. }
  18104. // The skip in get_combined_header_value() is what keeps an empty field line
  18105. // from contributing a bare comma. Only a trailing empty field line exercises
  18106. // it: a leading one is already covered by the "combined is still empty" check,
  18107. // and parse_accept_header() now ignores the empty element either way, so the
  18108. // request-level test above can no longer tell the two apart.
  18109. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18110. Headers headers;
  18111. headers.emplace("Accept", "text/html");
  18112. headers.emplace("Accept", "");
  18113. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18114. headers.clear();
  18115. headers.emplace("Accept", "");
  18116. headers.emplace("Accept", "application/json");
  18117. EXPECT_EQ("application/json",
  18118. detail::get_combined_header_value(headers, "Accept"));
  18119. }
  18120. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18121. // An encoding offered on a later Accept-Encoding field line is still offered.
  18122. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18123. Server svr;
  18124. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18125. res.set_content(std::string(1024, 'x'), "text/plain");
  18126. });
  18127. auto port = svr.bind_to_any_port(HOST);
  18128. thread t = thread([&]() { svr.listen_after_bind(); });
  18129. auto se = detail::scope_exit([&] {
  18130. svr.stop();
  18131. t.join();
  18132. ASSERT_FALSE(svr.is_running());
  18133. });
  18134. svr.wait_until_ready();
  18135. Client cli(HOST, port);
  18136. cli.set_decompress(false);
  18137. Headers headers;
  18138. headers.emplace("Accept-Encoding", "identity");
  18139. headers.emplace("Accept-Encoding", "gzip");
  18140. auto res = cli.Get("/", headers);
  18141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18142. EXPECT_EQ(StatusCode::OK_200, res->status);
  18143. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18144. }
  18145. #endif
  18146. #ifndef _WIN32
  18147. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18148. Server svr;
  18149. svr.Post("/post", [&](const Request &req, Response &res) {
  18150. res.set_content(req.body, "text/plain");
  18151. });
  18152. svr.Put("/put", [&](const Request &req, Response &res) {
  18153. res.set_content(req.body, "text/plain");
  18154. });
  18155. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18156. res.set_content(req.body, "text/plain");
  18157. });
  18158. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18159. res.set_content(req.body, "text/plain");
  18160. });
  18161. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18162. auto se = detail::scope_exit([&] {
  18163. svr.stop();
  18164. t.join();
  18165. ASSERT_FALSE(svr.is_running());
  18166. });
  18167. svr.wait_until_ready();
  18168. std::string resp;
  18169. // POST without Content-Length
  18170. ASSERT_TRUE(send_request(5,
  18171. "POST /post HTTP/1.1\r\n"
  18172. "Host: localhost\r\n"
  18173. "Connection: close\r\n"
  18174. "\r\n",
  18175. &resp));
  18176. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18177. // PUT without Content-Length
  18178. resp.clear();
  18179. ASSERT_TRUE(send_request(5,
  18180. "PUT /put HTTP/1.1\r\n"
  18181. "Host: localhost\r\n"
  18182. "Connection: close\r\n"
  18183. "\r\n",
  18184. &resp));
  18185. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18186. // PATCH without Content-Length
  18187. resp.clear();
  18188. ASSERT_TRUE(send_request(5,
  18189. "PATCH /patch HTTP/1.1\r\n"
  18190. "Host: localhost\r\n"
  18191. "Connection: close\r\n"
  18192. "\r\n",
  18193. &resp));
  18194. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18195. // DELETE without Content-Length
  18196. resp.clear();
  18197. ASSERT_TRUE(send_request(5,
  18198. "DELETE /delete HTTP/1.1\r\n"
  18199. "Host: localhost\r\n"
  18200. "Connection: close\r\n"
  18201. "\r\n",
  18202. &resp));
  18203. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18204. }
  18205. #endif
  18206. //==============================================================================
  18207. // open_stream() Tests
  18208. //==============================================================================
  18209. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18210. std::string result;
  18211. char buf[8192];
  18212. ssize_t n;
  18213. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18214. result.append(buf, static_cast<size_t>(n));
  18215. }
  18216. return result;
  18217. }
  18218. // Mock stream for unit tests
  18219. class MockStream : public Stream {
  18220. public:
  18221. std::string data;
  18222. size_t pos = 0;
  18223. ssize_t error_after = -1; // -1 = no error
  18224. explicit MockStream(const std::string &d, ssize_t err = -1)
  18225. : data(d), error_after(err) {}
  18226. bool is_readable() const override { return true; }
  18227. bool wait_readable() const override { return true; }
  18228. bool wait_writable() const override { return true; }
  18229. ssize_t read(char *ptr, size_t size) override {
  18230. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18231. if (pos >= data.size()) return 0;
  18232. size_t limit =
  18233. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18234. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18235. std::memcpy(ptr, data.data() + pos, to_read);
  18236. pos += to_read;
  18237. return static_cast<ssize_t>(to_read);
  18238. }
  18239. ssize_t write(const char *, size_t) override { return -1; }
  18240. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18241. ip = "127.0.0.1";
  18242. port = 0;
  18243. }
  18244. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18245. ip = "127.0.0.1";
  18246. port = 0;
  18247. }
  18248. socket_t socket() const override { return INVALID_SOCKET; }
  18249. time_t duration() const override { return 0; }
  18250. };
  18251. TEST(StreamHandleTest, Basic) {
  18252. ClientImpl::StreamHandle handle;
  18253. EXPECT_FALSE(handle.is_valid());
  18254. handle.response = detail::make_unique<Response>();
  18255. handle.error = Error::Connection;
  18256. EXPECT_FALSE(handle.is_valid());
  18257. handle.error = Error::Success;
  18258. EXPECT_TRUE(handle.is_valid());
  18259. }
  18260. TEST(BodyReaderTest, Basic) {
  18261. MockStream stream("Hello, World!");
  18262. detail::BodyReader reader;
  18263. reader.stream = &stream;
  18264. reader.content_length = 13;
  18265. char buf[32];
  18266. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18267. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18268. EXPECT_TRUE(reader.eof);
  18269. }
  18270. TEST(BodyReaderTest, NoStream) {
  18271. detail::BodyReader reader;
  18272. char buf[32];
  18273. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18274. EXPECT_EQ(Error::Connection, reader.last_error);
  18275. }
  18276. TEST(BodyReaderTest, Error) {
  18277. MockStream stream("Hello, World!", 5);
  18278. detail::BodyReader reader;
  18279. reader.stream = &stream;
  18280. reader.content_length = 13;
  18281. char buf[32];
  18282. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18283. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18284. EXPECT_EQ(Error::Read, reader.last_error);
  18285. }
  18286. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18287. // Mock-based StreamHandle tests relying on private internals are removed.
  18288. class OpenStreamTest : public ::testing::Test {
  18289. protected:
  18290. void SetUp() override {
  18291. svr_.Get("/hello", [](const Request &, Response &res) {
  18292. res.set_content("Hello World!", "text/plain");
  18293. });
  18294. svr_.Get("/large", [](const Request &, Response &res) {
  18295. res.set_content(std::string(10000, 'X'), "text/plain");
  18296. });
  18297. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18298. res.set_content("Hello World!", "image/jpeg");
  18299. res.set_header("Content-Encoding", "UTF-8");
  18300. });
  18301. svr_.Get("/chunked", [](const Request &, Response &res) {
  18302. res.set_chunked_content_provider("text/plain",
  18303. [](size_t offset, DataSink &sink) {
  18304. if (offset < 15) {
  18305. sink.write("chunk", 5);
  18306. return true;
  18307. }
  18308. sink.done();
  18309. return true;
  18310. });
  18311. });
  18312. svr_.Get("/compressible", [](const Request &, Response &res) {
  18313. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18314. DataSink &sink) {
  18315. if (offset < 100 * 1024) {
  18316. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18317. sink.write(chunk.data(), chunk.size());
  18318. return true;
  18319. }
  18320. sink.done();
  18321. return true;
  18322. });
  18323. });
  18324. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18325. [](const Request & /*req*/, Response &res) {
  18326. auto i = new int(0);
  18327. res.set_header("Trailer", "Content-Length, X-Allowed");
  18328. res.set_chunked_content_provider(
  18329. "text/plain",
  18330. [i](size_t /*offset*/, DataSink &sink) {
  18331. switch (*i) {
  18332. case 0: sink.os << "123"; break;
  18333. case 1: sink.os << "456"; break;
  18334. case 2: sink.os << "789"; break;
  18335. case 3: {
  18336. sink.done_with_trailer(
  18337. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18338. } break;
  18339. }
  18340. (*i)++;
  18341. return true;
  18342. },
  18343. [i](bool success) {
  18344. EXPECT_TRUE(success);
  18345. delete i;
  18346. });
  18347. });
  18348. // Echo headers endpoint for header-related tests
  18349. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18350. std::string body;
  18351. for (const auto &h : req.headers) {
  18352. body.append(h.first);
  18353. body.push_back(':');
  18354. body.append(h.second);
  18355. body.push_back('\n');
  18356. }
  18357. res.set_content(body, "text/plain");
  18358. });
  18359. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18360. std::string body;
  18361. for (const auto &h : req.headers) {
  18362. body.append(h.first);
  18363. body.push_back(':');
  18364. body.append(h.second);
  18365. body.push_back('\n');
  18366. }
  18367. res.set_content(body, "text/plain");
  18368. });
  18369. port_ = svr_.bind_to_any_port("127.0.0.1");
  18370. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18371. svr_.wait_until_ready();
  18372. }
  18373. void TearDown() override {
  18374. svr_.stop();
  18375. if (thread_.joinable()) thread_.join();
  18376. }
  18377. Server svr_;
  18378. std::thread thread_;
  18379. int port_ = 0;
  18380. };
  18381. TEST_F(OpenStreamTest, Basic) {
  18382. Client cli("127.0.0.1", port_);
  18383. auto handle = cli.open_stream("GET", "/hello");
  18384. EXPECT_TRUE(handle.is_valid());
  18385. EXPECT_EQ("Hello World!", read_all(handle));
  18386. }
  18387. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18388. Client cli("127.0.0.1", port_);
  18389. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18390. ASSERT_TRUE(handle.is_valid());
  18391. EXPECT_EQ("Hello World!", read_all(handle));
  18392. }
  18393. TEST_F(OpenStreamTest, SmallBuffer) {
  18394. Client cli("127.0.0.1", port_);
  18395. auto handle = cli.open_stream("GET", "/hello");
  18396. std::string result;
  18397. char buf[4];
  18398. ssize_t n;
  18399. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18400. result.append(buf, static_cast<size_t>(n));
  18401. EXPECT_EQ("Hello World!", result);
  18402. }
  18403. TEST_F(OpenStreamTest, DefaultHeaders) {
  18404. Client cli("127.0.0.1", port_);
  18405. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18406. {
  18407. auto handle = cli.open_stream("GET", "/echo-headers");
  18408. ASSERT_TRUE(handle.is_valid());
  18409. auto body = read_all(handle);
  18410. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18411. std::string::npos);
  18412. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18413. std::string::npos);
  18414. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18415. }
  18416. // open_stream POST with body and no explicit content_type should NOT add
  18417. // text/plain Content-Type (behavior differs from non-streaming path), but
  18418. // should include Content-Length
  18419. {
  18420. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18421. ASSERT_TRUE(handle.is_valid());
  18422. auto body = read_all(handle);
  18423. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18424. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18425. }
  18426. // open_stream POST with explicit Content-Type should preserve it
  18427. {
  18428. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18429. {{"Content-Type", "application/custom"}},
  18430. "{}", "application/custom");
  18431. ASSERT_TRUE(handle.is_valid());
  18432. auto body = read_all(handle);
  18433. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18434. }
  18435. // User-specified User-Agent must not be overwritten for stream API
  18436. {
  18437. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18438. {{"User-Agent", "MyAgent/1.2"}});
  18439. ASSERT_TRUE(handle.is_valid());
  18440. auto body = read_all(handle);
  18441. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18442. }
  18443. }
  18444. TEST_F(OpenStreamTest, Large) {
  18445. Client cli("127.0.0.1", port_);
  18446. auto handle = cli.open_stream("GET", "/large");
  18447. EXPECT_EQ(10000u, read_all(handle).size());
  18448. }
  18449. TEST_F(OpenStreamTest, ConnectionError) {
  18450. Client cli("127.0.0.1", 9999);
  18451. auto handle = cli.open_stream("GET", "/hello");
  18452. EXPECT_FALSE(handle.is_valid());
  18453. }
  18454. TEST_F(OpenStreamTest, Chunked) {
  18455. Client cli("127.0.0.1", port_);
  18456. auto handle = cli.open_stream("GET", "/chunked");
  18457. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18458. "Transfer-Encoding") == "chunked");
  18459. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18460. }
  18461. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18462. Client cli("127.0.0.1", port_);
  18463. auto handle =
  18464. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18465. ASSERT_TRUE(handle.is_valid());
  18466. // Consume body to allow trailers to be received/parsed
  18467. auto body = read_all(handle);
  18468. // Explicitly parse trailers (ensure trailers are available for assertion)
  18469. handle.parse_trailers_if_needed();
  18470. EXPECT_EQ(std::string("123456789"), body);
  18471. // The response should include a Trailer header declaring both names
  18472. ASSERT_TRUE(handle.response);
  18473. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18474. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18475. handle.response->get_header_value("Trailer"));
  18476. // Prohibited trailer must not be present
  18477. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18478. // Allowed trailer should be present
  18479. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18480. EXPECT_EQ(std::string("yes"),
  18481. handle.response->get_trailer_value("X-Allowed"));
  18482. // Verify trailers are NOT present as regular headers
  18483. EXPECT_EQ(std::string(""),
  18484. handle.response->get_header_value("Content-Length"));
  18485. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18486. }
  18487. static std::thread serve_single_response(std::promise<int> &port_promise,
  18488. const std::string &response) {
  18489. return std::thread([&port_promise, response] {
  18490. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18491. default_socket_options(srv);
  18492. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18493. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18494. sockaddr_in addr{};
  18495. addr.sin_family = AF_INET;
  18496. addr.sin_port = htons(0); // Let OS assign a free port
  18497. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18498. int opt = 1;
  18499. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18500. #ifdef _WIN32
  18501. reinterpret_cast<const char *>(&opt),
  18502. #else
  18503. &opt,
  18504. #endif
  18505. sizeof(opt));
  18506. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18507. ::listen(srv, 1) != 0) {
  18508. port_promise.set_value(-1);
  18509. detail::close_socket(srv);
  18510. return;
  18511. }
  18512. socklen_t addr_len = sizeof(addr);
  18513. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18514. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18515. sockaddr_in cli_addr{};
  18516. socklen_t cli_len = sizeof(cli_addr);
  18517. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18518. if (cli != INVALID_SOCKET) {
  18519. // Read the complete HTTP request (until the blank line that terminates
  18520. // headers) before sending the response. If the server closes the socket
  18521. // while the client's request data is still unread in the kernel receive
  18522. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18523. // connection on both sides: it discards the client's receive buffer
  18524. // (which already holds our response) and causes any in-progress write on
  18525. // the client to fail with ECONNRESET. Reading all request data first
  18526. // ensures close() emits a graceful FIN.
  18527. {
  18528. char rbuf[256];
  18529. std::string req;
  18530. while (req.find("\r\n\r\n") == std::string::npos) {
  18531. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18532. if (n <= 0) { break; }
  18533. req.append(rbuf, static_cast<size_t>(n));
  18534. }
  18535. }
  18536. ::send(cli,
  18537. #ifdef _WIN32
  18538. static_cast<const char *>(response.c_str()),
  18539. static_cast<int>(response.size()),
  18540. #else
  18541. response.c_str(), response.size(),
  18542. #endif
  18543. 0);
  18544. detail::close_socket(cli);
  18545. }
  18546. detail::close_socket(srv);
  18547. });
  18548. }
  18549. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18550. #ifndef _WIN32
  18551. signal(SIGPIPE, SIG_IGN);
  18552. #endif
  18553. std::promise<int> port_promise;
  18554. auto port_future = port_promise.get_future();
  18555. auto server_thread =
  18556. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18557. "Content-Type: text/plain\r\n"
  18558. "Content-Length: not-a-number\r\n"
  18559. "Connection: close\r\n"
  18560. "\r\n"
  18561. "hello");
  18562. auto port = port_future.get();
  18563. ASSERT_GT(port, 0);
  18564. Client cli("127.0.0.1", port);
  18565. auto handle = cli.open_stream("GET", "/");
  18566. EXPECT_FALSE(handle.is_valid());
  18567. server_thread.join();
  18568. }
  18569. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18570. #ifndef _WIN32
  18571. signal(SIGPIPE, SIG_IGN);
  18572. #endif
  18573. std::promise<int> port_promise;
  18574. auto port_future = port_promise.get_future();
  18575. auto server_thread = serve_single_response(
  18576. port_promise, "HTTP/1.1 200 OK\r\n"
  18577. "Content-Type: text/plain\r\n"
  18578. "Content-Length: 99999999999999999999999999\r\n"
  18579. "Connection: close\r\n"
  18580. "\r\n"
  18581. "hello");
  18582. auto port = port_future.get();
  18583. ASSERT_GT(port, 0);
  18584. // Historically std::stoull would throw std::out_of_range here and crash
  18585. // the process, then parsing silently clamped to a bogus framing length and
  18586. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18587. // so the stream fails to open, matching the not-a-number case above. The
  18588. // process still must NOT terminate.
  18589. Client cli("127.0.0.1", port);
  18590. auto handle = cli.open_stream("GET", "/");
  18591. EXPECT_FALSE(handle.is_valid());
  18592. server_thread.join();
  18593. }
  18594. // Serves `response` to the single request `fn` makes with a fresh client.
  18595. template <typename Fn>
  18596. static void with_single_response(const std::string &response, Fn fn) {
  18597. #ifndef _WIN32
  18598. signal(SIGPIPE, SIG_IGN);
  18599. #endif
  18600. std::promise<int> port_promise;
  18601. auto port_future = port_promise.get_future();
  18602. auto server_thread = serve_single_response(port_promise, response);
  18603. auto se = detail::scope_exit([&] { server_thread.join(); });
  18604. auto port = port_future.get();
  18605. ASSERT_GT(port, 0);
  18606. Client cli("127.0.0.1", port);
  18607. fn(cli);
  18608. }
  18609. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18610. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18611. // the chunked coding and drop Content-Length, so a front-end that trusts
  18612. // Content-Length would disagree about where the body ends (response
  18613. // smuggling). The client must reject such a response.
  18614. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18615. for (const char *te : {"chunked", "gzip, chunked"}) {
  18616. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18617. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18618. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18619. "5\r\nhello\r\n0\r\n\r\n";
  18620. with_single_response(response, [&](Client &cli) {
  18621. auto res = cli.Get("/");
  18622. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18623. EXPECT_EQ(Error::Read, res.error()) << te;
  18624. });
  18625. with_single_response(response, [&](Client &cli) {
  18626. auto handle = cli.open_stream("GET", "/");
  18627. EXPECT_FALSE(handle.is_valid()) << te;
  18628. EXPECT_EQ(Error::Read, handle.error) << te;
  18629. });
  18630. }
  18631. }
  18632. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18633. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18634. // closing the connection (unlike a request, which must be rejected).
  18635. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18636. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18637. "Transfer-Encoding: chunked\r\n"
  18638. "Connection: close\r\n"
  18639. "\r\n"
  18640. "5\r\nhello\r\n0\r\n\r\n",
  18641. "HTTP/1.1 200 OK\r\n"
  18642. "Transfer-Encoding: gzip\r\n"
  18643. "Connection: close\r\n"
  18644. "\r\n"
  18645. "hello"}) {
  18646. with_single_response(response, [&](Client &cli) {
  18647. auto res = cli.Get("/");
  18648. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18649. EXPECT_EQ("hello", res->body);
  18650. });
  18651. with_single_response(response, [&](Client &cli) {
  18652. auto handle = cli.open_stream("GET", "/");
  18653. ASSERT_TRUE(handle.is_valid()) << response;
  18654. EXPECT_EQ("hello", read_all(handle));
  18655. });
  18656. }
  18657. }
  18658. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18659. // framing headers describe nothing to read and must not be rejected.
  18660. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18661. const std::string framing = "Content-Length: 5\r\n"
  18662. "Transfer-Encoding: chunked\r\n"
  18663. "Connection: close\r\n"
  18664. "\r\n";
  18665. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18666. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18667. });
  18668. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18669. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18670. });
  18671. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18672. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18673. with_single_response(response, [&](Client &cli) {
  18674. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18675. });
  18676. with_single_response(response, [&](Client &cli) {
  18677. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18678. });
  18679. }
  18680. }
  18681. // A payload max length of 0 means no limit, however the body is framed.
  18682. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18683. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18684. "Transfer-Encoding: chunked\r\n"
  18685. "\r\n"
  18686. "5\r\nhello\r\n0\r\n\r\n",
  18687. "HTTP/1.1 200 OK\r\n"
  18688. "Connection: close\r\n"
  18689. "\r\n"
  18690. "hello"}) {
  18691. with_single_response(response, [&](Client &cli) {
  18692. cli.set_payload_max_length(0);
  18693. auto res = cli.Get("/");
  18694. ASSERT_TRUE(res) << response;
  18695. EXPECT_EQ("hello", res->body) << response;
  18696. });
  18697. }
  18698. }
  18699. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18700. Server svr;
  18701. svr.set_payload_max_length(0);
  18702. svr.Post("/echo", [](const Request &req, Response &res) {
  18703. res.set_content(req.body, "text/plain");
  18704. });
  18705. auto port = svr.bind_to_any_port(HOST);
  18706. thread t = thread([&] { svr.listen_after_bind(); });
  18707. auto se = detail::scope_exit([&] {
  18708. svr.stop();
  18709. t.join();
  18710. ASSERT_FALSE(svr.is_running());
  18711. });
  18712. svr.wait_until_ready();
  18713. Client cli(HOST, port);
  18714. auto res = cli.Post(
  18715. "/echo",
  18716. [](size_t /*offset*/, DataSink &sink) {
  18717. sink.write("hello", 5);
  18718. sink.done();
  18719. return true;
  18720. },
  18721. "text/plain");
  18722. ASSERT_TRUE(res);
  18723. EXPECT_EQ(StatusCode::OK_200, res->status);
  18724. EXPECT_EQ("hello", res->body);
  18725. }
  18726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18727. TEST_F(OpenStreamTest, Gzip) {
  18728. Client cli("127.0.0.1", port_);
  18729. auto handle = cli.open_stream("GET", "/compressible", {},
  18730. {{"Accept-Encoding", "gzip"}});
  18731. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18732. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18733. }
  18734. #endif
  18735. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18736. TEST_F(OpenStreamTest, Brotli) {
  18737. Client cli("127.0.0.1", port_);
  18738. auto handle =
  18739. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18740. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18741. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18742. }
  18743. #endif
  18744. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18745. TEST_F(OpenStreamTest, Zstd) {
  18746. Client cli("127.0.0.1", port_);
  18747. auto handle = cli.open_stream("GET", "/compressible", {},
  18748. {{"Accept-Encoding", "zstd"}});
  18749. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18750. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18751. }
  18752. #endif
  18753. #ifdef CPPHTTPLIB_SSL_ENABLED
  18754. class SSLOpenStreamTest : public ::testing::Test {
  18755. protected:
  18756. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18757. void SetUp() override {
  18758. svr_.Get("/hello", [](const Request &, Response &res) {
  18759. res.set_content("Hello SSL World!", "text/plain");
  18760. });
  18761. svr_.Get("/chunked", [](const Request &, Response &res) {
  18762. res.set_chunked_content_provider("text/plain",
  18763. [](size_t offset, DataSink &sink) {
  18764. if (offset < 15) {
  18765. sink.write("chunk", 5);
  18766. return true;
  18767. }
  18768. sink.done();
  18769. return true;
  18770. });
  18771. });
  18772. svr_.Post("/echo", [](const Request &req, Response &res) {
  18773. res.set_content(req.body, req.get_header_value("Content-Type"));
  18774. });
  18775. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18776. std::string body = req.body;
  18777. res.set_chunked_content_provider(
  18778. "text/plain", [body](size_t offset, DataSink &sink) {
  18779. if (offset < body.size()) {
  18780. sink.write(body.data() + offset, body.size() - offset);
  18781. }
  18782. sink.done();
  18783. return true;
  18784. });
  18785. });
  18786. port_ = svr_.bind_to_any_port("127.0.0.1");
  18787. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18788. svr_.wait_until_ready();
  18789. }
  18790. void TearDown() override {
  18791. svr_.stop();
  18792. if (thread_.joinable()) thread_.join();
  18793. }
  18794. SSLServer svr_;
  18795. std::thread thread_;
  18796. int port_ = 0;
  18797. };
  18798. TEST_F(SSLOpenStreamTest, Basic) {
  18799. SSLClient cli("127.0.0.1", port_);
  18800. cli.enable_server_certificate_verification(false);
  18801. auto handle = cli.open_stream("GET", "/hello");
  18802. ASSERT_TRUE(handle.is_valid());
  18803. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18804. }
  18805. TEST_F(SSLOpenStreamTest, Chunked) {
  18806. SSLClient cli("127.0.0.1", port_);
  18807. cli.enable_server_certificate_verification(false);
  18808. auto handle = cli.open_stream("GET", "/chunked");
  18809. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18810. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18811. "Transfer-Encoding") == "chunked");
  18812. auto body = read_all(handle);
  18813. EXPECT_EQ("chunkchunkchunk", body);
  18814. }
  18815. TEST_F(SSLOpenStreamTest, Post) {
  18816. SSLClient cli("127.0.0.1", port_);
  18817. cli.enable_server_certificate_verification(false);
  18818. auto handle =
  18819. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18820. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18821. EXPECT_EQ(200, handle.response->status);
  18822. auto body = read_all(handle);
  18823. EXPECT_EQ("Hello SSL POST", body);
  18824. }
  18825. TEST_F(SSLOpenStreamTest, PostChunked) {
  18826. SSLClient cli("127.0.0.1", port_);
  18827. cli.enable_server_certificate_verification(false);
  18828. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18829. "Chunked SSL Data", "text/plain");
  18830. ASSERT_TRUE(handle.is_valid());
  18831. EXPECT_EQ(200, handle.response->status);
  18832. auto body = read_all(handle);
  18833. EXPECT_EQ("Chunked SSL Data", body);
  18834. }
  18835. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18836. // Content-Length is terminated by the server closing the connection. When the
  18837. // SSL peer sends a close_notify after the body, the client must treat it as a
  18838. // clean EOF and return a successful response rather than an error.
  18839. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18840. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18841. ASSERT_TRUE(svr.is_valid());
  18842. svr.set_keep_alive_max_count(1);
  18843. const std::string expected_body = "Hello from connection-close response!";
  18844. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18845. res.set_content_provider("text/plain",
  18846. [&](size_t offset, DataSink &sink) -> bool {
  18847. if (offset < expected_body.size()) {
  18848. sink.write(expected_body.data() + offset,
  18849. expected_body.size() - offset);
  18850. }
  18851. sink.done();
  18852. return true;
  18853. });
  18854. });
  18855. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18856. auto se = detail::scope_exit([&] {
  18857. svr.stop();
  18858. listen_thread.join();
  18859. ASSERT_FALSE(svr.is_running());
  18860. });
  18861. svr.wait_until_ready();
  18862. SSLClient cli(HOST, PORT);
  18863. cli.enable_server_certificate_verification(false);
  18864. auto res = cli.Get("/no-content-length");
  18865. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18866. EXPECT_EQ(StatusCode::OK_200, res->status);
  18867. EXPECT_EQ(expected_body, res->body);
  18868. }
  18869. #endif // CPPHTTPLIB_SSL_ENABLED
  18870. //==============================================================================
  18871. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18872. // results for various scenarios.
  18873. //==============================================================================
  18874. TEST(ParityTest, GetVsOpenStream) {
  18875. Server svr;
  18876. const std::string path = "/parity";
  18877. const std::string content = "Parity test content: hello world";
  18878. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18879. res.set_content(content, "text/plain");
  18880. });
  18881. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18882. auto se = detail::scope_exit([&] {
  18883. svr.stop();
  18884. t.join();
  18885. ASSERT_FALSE(svr.is_running());
  18886. });
  18887. svr.wait_until_ready();
  18888. Client cli(HOST, PORT);
  18889. // Non-stream path
  18890. auto r1 = cli.Get(path);
  18891. ASSERT_TRUE(r1);
  18892. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18893. // Stream path
  18894. auto h = cli.open_stream("GET", path);
  18895. ASSERT_TRUE(h.is_valid());
  18896. EXPECT_EQ(r1->body, read_all(h));
  18897. }
  18898. // Helper to compress data with provided compressor type T
  18899. template <typename Compressor>
  18900. static std::string compress_payload_for_parity(const std::string &in) {
  18901. std::string out;
  18902. Compressor compressor;
  18903. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18904. [&](const char *data, size_t n) {
  18905. out.append(data, n);
  18906. return true;
  18907. });
  18908. EXPECT_TRUE(ok);
  18909. return out;
  18910. }
  18911. // Helper function for compression parity tests
  18912. template <typename Compressor>
  18913. static void test_compression_parity(const std::string &original,
  18914. const std::string &path,
  18915. const std::string &encoding) {
  18916. const std::string compressed =
  18917. compress_payload_for_parity<Compressor>(original);
  18918. Server svr;
  18919. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18920. res.set_content(compressed, "application/octet-stream");
  18921. res.set_header("Content-Encoding", encoding);
  18922. });
  18923. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18924. auto se = detail::scope_exit([&] {
  18925. svr.stop();
  18926. t.join();
  18927. ASSERT_FALSE(svr.is_running());
  18928. });
  18929. svr.wait_until_ready();
  18930. Client cli(HOST, PORT);
  18931. // Non-streaming
  18932. {
  18933. auto res = cli.Get(path);
  18934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18935. EXPECT_EQ(StatusCode::OK_200, res->status);
  18936. EXPECT_EQ(original, res->body);
  18937. }
  18938. // Streaming
  18939. {
  18940. auto h = cli.open_stream("GET", path);
  18941. ASSERT_TRUE(h.is_valid());
  18942. EXPECT_EQ(original, read_all(h));
  18943. }
  18944. }
  18945. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18946. TEST(ParityTest, Gzip) {
  18947. test_compression_parity<detail::gzip_compressor>(
  18948. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18949. }
  18950. #endif
  18951. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18952. TEST(ParityTest, Brotli) {
  18953. test_compression_parity<detail::brotli_compressor>(
  18954. "Hello, brotli parity test payload", "/parity-br", "br");
  18955. }
  18956. #endif
  18957. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18958. TEST(ParityTest, Zstd) {
  18959. test_compression_parity<detail::zstd_compressor>(
  18960. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18961. }
  18962. #endif
  18963. //==============================================================================
  18964. // New Stream API Tests
  18965. //==============================================================================
  18966. inline std::string read_body(httplib::stream::Result &result) {
  18967. std::string body;
  18968. while (result.next()) {
  18969. body.append(result.data(), result.size());
  18970. }
  18971. return body;
  18972. }
  18973. TEST(ClientConnectionTest, Basic) {
  18974. httplib::ClientConnection conn;
  18975. EXPECT_FALSE(conn.is_open());
  18976. conn.sock = 1;
  18977. EXPECT_TRUE(conn.is_open());
  18978. httplib::ClientConnection conn2(std::move(conn));
  18979. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18980. conn2.sock = INVALID_SOCKET;
  18981. }
  18982. // Unified test server for all stream::* tests
  18983. class StreamApiTest : public ::testing::Test {
  18984. protected:
  18985. void SetUp() override {
  18986. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18987. res.set_content("Hello World!", "text/plain");
  18988. });
  18989. svr_.Get("/echo-params",
  18990. [](const httplib::Request &req, httplib::Response &res) {
  18991. std::string r;
  18992. for (const auto &p : req.params) {
  18993. if (!r.empty()) r += "&";
  18994. r += p.first + "=" + p.second;
  18995. }
  18996. res.set_content(r, "text/plain");
  18997. });
  18998. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18999. res.set_content(req.body, req.get_header_value("Content-Type"));
  19000. });
  19001. svr_.Post("/echo-headers",
  19002. [](const httplib::Request &req, httplib::Response &res) {
  19003. std::string r;
  19004. for (const auto &h : req.headers)
  19005. r += h.first + ": " + h.second + "\n";
  19006. res.set_content(r, "text/plain");
  19007. });
  19008. svr_.Post("/echo-params",
  19009. [](const httplib::Request &req, httplib::Response &res) {
  19010. std::string r = "params:";
  19011. for (const auto &p : req.params)
  19012. r += p.first + "=" + p.second + ";";
  19013. res.set_content(r + " body:" + req.body, "text/plain");
  19014. });
  19015. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19016. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19017. });
  19018. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19019. res.set_content("PUT:" + req.body, "text/plain");
  19020. });
  19021. svr_.Patch("/echo",
  19022. [](const httplib::Request &req, httplib::Response &res) {
  19023. res.set_content("PATCH:" + req.body, "text/plain");
  19024. });
  19025. svr_.Delete(
  19026. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19027. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19028. "text/plain");
  19029. });
  19030. svr_.Get("/head-test",
  19031. [](const httplib::Request &, httplib::Response &res) {
  19032. res.set_content("body for HEAD", "text/plain");
  19033. });
  19034. svr_.Options("/options",
  19035. [](const httplib::Request &, httplib::Response &res) {
  19036. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19037. });
  19038. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19039. svr_.wait_until_ready();
  19040. }
  19041. void TearDown() override {
  19042. svr_.stop();
  19043. if (thread_.joinable()) thread_.join();
  19044. }
  19045. httplib::Server svr_;
  19046. std::thread thread_;
  19047. };
  19048. // stream::Get tests
  19049. TEST_F(StreamApiTest, GetBasic) {
  19050. httplib::Client cli(HOST, PORT);
  19051. auto result = httplib::stream::Get(cli, "/hello");
  19052. ASSERT_TRUE(result.is_valid());
  19053. EXPECT_EQ(200, result.status());
  19054. EXPECT_EQ("Hello World!", read_body(result));
  19055. }
  19056. TEST_F(StreamApiTest, GetWithParams) {
  19057. httplib::Client cli(HOST, PORT);
  19058. httplib::Params params{{"foo", "bar"}};
  19059. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19060. ASSERT_TRUE(result.is_valid());
  19061. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19062. }
  19063. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19064. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19065. httplib::Client cli(HOST, PORT);
  19066. cli.set_payload_max_length(0);
  19067. auto result = httplib::stream::Get(cli, "/hello");
  19068. ASSERT_TRUE(result.is_valid());
  19069. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19070. EXPECT_EQ("Hello World!", read_body(result));
  19071. }
  19072. #endif
  19073. TEST_F(StreamApiTest, GetConnectionError) {
  19074. httplib::Client cli(HOST, 9999);
  19075. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19076. }
  19077. TEST_F(StreamApiTest, Get404) {
  19078. httplib::Client cli(HOST, PORT);
  19079. auto result = httplib::stream::Get(cli, "/nonexistent");
  19080. EXPECT_TRUE(result.is_valid());
  19081. EXPECT_EQ(404, result.status());
  19082. }
  19083. // stream::Post tests
  19084. TEST_F(StreamApiTest, PostBasic) {
  19085. httplib::Client cli(HOST, PORT);
  19086. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19087. "application/json");
  19088. ASSERT_TRUE(result.is_valid());
  19089. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19090. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19091. }
  19092. TEST_F(StreamApiTest, PostWithHeaders) {
  19093. httplib::Client cli(HOST, PORT);
  19094. httplib::Headers headers{{"X-Custom", "value"}};
  19095. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19096. "text/plain");
  19097. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19098. }
  19099. TEST_F(StreamApiTest, PostWithParams) {
  19100. httplib::Client cli(HOST, PORT);
  19101. httplib::Params params{{"k", "v"}};
  19102. auto result =
  19103. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19104. auto body = read_body(result);
  19105. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19106. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19107. }
  19108. TEST_F(StreamApiTest, PostLarge) {
  19109. httplib::Client cli(HOST, PORT);
  19110. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19111. size_t total = 0;
  19112. while (result.next()) {
  19113. total += result.size();
  19114. }
  19115. EXPECT_EQ(100u * 1024u, total);
  19116. }
  19117. // stream::Put/Patch tests
  19118. TEST_F(StreamApiTest, PutAndPatch) {
  19119. httplib::Client cli(HOST, PORT);
  19120. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19121. EXPECT_EQ("PUT:test", read_body(put));
  19122. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19123. EXPECT_EQ("PATCH:test", read_body(patch));
  19124. }
  19125. // stream::Delete tests
  19126. TEST_F(StreamApiTest, Delete) {
  19127. httplib::Client cli(HOST, PORT);
  19128. auto del1 = httplib::stream::Delete(cli, "/resource");
  19129. EXPECT_EQ("Deleted", read_body(del1));
  19130. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19131. EXPECT_EQ("Deleted:data", read_body(del2));
  19132. }
  19133. // stream::Head/Options tests
  19134. TEST_F(StreamApiTest, HeadAndOptions) {
  19135. httplib::Client cli(HOST, PORT);
  19136. auto head = httplib::stream::Head(cli, "/head-test");
  19137. EXPECT_TRUE(head.is_valid());
  19138. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19139. auto opts = httplib::stream::Options(cli, "/options");
  19140. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19141. }
  19142. // SSL stream::* tests
  19143. #ifdef CPPHTTPLIB_SSL_ENABLED
  19144. class SSLStreamApiTest : public ::testing::Test {
  19145. protected:
  19146. void SetUp() override {
  19147. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19148. res.set_content("Hello SSL!", "text/plain");
  19149. });
  19150. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19151. res.set_content(req.body, "text/plain");
  19152. });
  19153. port_ = svr_.bind_to_any_port("127.0.0.1");
  19154. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19155. svr_.wait_until_ready();
  19156. }
  19157. void TearDown() override {
  19158. svr_.stop();
  19159. if (thread_.joinable()) thread_.join();
  19160. }
  19161. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19162. std::thread thread_;
  19163. int port_ = 0;
  19164. };
  19165. TEST_F(SSLStreamApiTest, GetAndPost) {
  19166. httplib::SSLClient cli("127.0.0.1", port_);
  19167. cli.enable_server_certificate_verification(false);
  19168. auto get = httplib::stream::Get(cli, "/hello");
  19169. EXPECT_EQ("Hello SSL!", read_body(get));
  19170. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19171. EXPECT_EQ("test", read_body(post));
  19172. }
  19173. #endif
  19174. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19175. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19176. // BodyReader
  19177. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19178. // Test that read timeout during streaming is detected
  19179. // Use a large content-length response where server delays mid-stream
  19180. Server svr;
  19181. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19182. // Send a large response with delay in the middle
  19183. res.set_content_provider(
  19184. 1000, // content_length
  19185. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19186. if (offset < 100) {
  19187. // Send first 100 bytes immediately
  19188. std::string data(100, 'A');
  19189. sink.write(data.c_str(), data.size());
  19190. return true;
  19191. }
  19192. // Then delay longer than client timeout
  19193. std::this_thread::sleep_for(std::chrono::seconds(3));
  19194. std::string data(900, 'B');
  19195. sink.write(data.c_str(), data.size());
  19196. return true;
  19197. });
  19198. });
  19199. auto port = 8091;
  19200. std::thread t([&]() { svr.listen("localhost", port); });
  19201. svr.wait_until_ready();
  19202. Client cli("localhost", port);
  19203. cli.set_read_timeout(1, 0); // 1 second timeout
  19204. auto handle = cli.open_stream("GET", "/slow-stream");
  19205. ASSERT_TRUE(handle.is_valid());
  19206. char buf[256];
  19207. ssize_t total = 0;
  19208. ssize_t n;
  19209. bool got_error = false;
  19210. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19211. total += n;
  19212. }
  19213. if (n < 0) {
  19214. got_error = true;
  19215. // Should be timeout or read error
  19216. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19217. handle.get_read_error() == Error::Read)
  19218. << "Actual error: " << to_string(handle.get_read_error());
  19219. }
  19220. // Either we got an error, or we got less data than expected
  19221. EXPECT_TRUE(got_error || total < 1000)
  19222. << "Expected timeout but got all " << total << " bytes";
  19223. svr.stop();
  19224. t.join();
  19225. }
  19226. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19227. // Test connection closed detection via BodyReader
  19228. Server svr;
  19229. std::atomic<bool> close_now{false};
  19230. svr.Get("/will-close", [&](const Request &, Response &res) {
  19231. res.set_content_provider(
  19232. 10000, // Large content_length that we won't fully send
  19233. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19234. if (offset < 100) {
  19235. std::string data(100, 'X');
  19236. sink.write(data.c_str(), data.size());
  19237. return true;
  19238. }
  19239. // Wait for signal then abort
  19240. while (!close_now) {
  19241. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19242. }
  19243. return false; // Abort - server will close connection
  19244. });
  19245. });
  19246. auto port = 8092;
  19247. std::thread t([&]() { svr.listen("localhost", port); });
  19248. svr.wait_until_ready();
  19249. Client cli("localhost", port);
  19250. auto handle = cli.open_stream("GET", "/will-close");
  19251. ASSERT_TRUE(handle.is_valid());
  19252. char buf[256];
  19253. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19254. EXPECT_GT(n, 0) << "First read should succeed";
  19255. // Signal server to close
  19256. close_now = true;
  19257. // Keep reading until error or EOF
  19258. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19259. // Keep reading
  19260. }
  19261. // Should get an error since content_length wasn't satisfied
  19262. if (n < 0) {
  19263. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19264. handle.get_read_error() == Error::Read)
  19265. << "Actual error: " << to_string(handle.get_read_error());
  19266. }
  19267. svr.stop();
  19268. t.join();
  19269. }
  19270. #ifdef CPPHTTPLIB_SSL_ENABLED
  19271. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19272. // Test that read timeout during SSL streaming is detected
  19273. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19274. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19275. res.set_content_provider(
  19276. 1000, "text/plain",
  19277. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19278. if (offset < 100) {
  19279. std::string data(100, 'A');
  19280. sink.write(data.c_str(), data.size());
  19281. return true;
  19282. }
  19283. std::this_thread::sleep_for(std::chrono::seconds(3));
  19284. std::string data(900, 'B');
  19285. sink.write(data.c_str(), data.size());
  19286. return true;
  19287. });
  19288. });
  19289. auto port = 8093;
  19290. std::thread t([&]() { svr.listen("localhost", port); });
  19291. svr.wait_until_ready();
  19292. SSLClient cli("localhost", port);
  19293. cli.enable_server_certificate_verification(false);
  19294. cli.set_read_timeout(1, 0); // 1 second timeout
  19295. auto handle = cli.open_stream("GET", "/slow-stream");
  19296. ASSERT_TRUE(handle.is_valid());
  19297. char buf[256];
  19298. ssize_t total = 0;
  19299. ssize_t n;
  19300. bool got_error = false;
  19301. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19302. total += n;
  19303. }
  19304. if (n < 0) {
  19305. got_error = true;
  19306. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19307. handle.get_read_error() == Error::Read)
  19308. << "Actual error: " << to_string(handle.get_read_error());
  19309. }
  19310. EXPECT_TRUE(got_error || total < 1000)
  19311. << "Expected timeout but got all " << total << " bytes";
  19312. svr.stop();
  19313. t.join();
  19314. }
  19315. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19316. // Test SSL connection closed detection
  19317. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19318. std::atomic<bool> close_now{false};
  19319. svr.Get("/will-close", [&](const Request &, Response &res) {
  19320. res.set_content_provider(
  19321. 10000, "text/plain",
  19322. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19323. if (offset < 100) {
  19324. std::string data(100, 'X');
  19325. sink.write(data.c_str(), data.size());
  19326. return true;
  19327. }
  19328. while (!close_now) {
  19329. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19330. }
  19331. return false;
  19332. });
  19333. });
  19334. auto port = 8094;
  19335. std::thread t([&]() { svr.listen("localhost", port); });
  19336. svr.wait_until_ready();
  19337. SSLClient cli("localhost", port);
  19338. cli.enable_server_certificate_verification(false);
  19339. auto handle = cli.open_stream("GET", "/will-close");
  19340. ASSERT_TRUE(handle.is_valid());
  19341. char buf[256];
  19342. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19343. EXPECT_GT(n, 0);
  19344. // Signal server to close
  19345. close_now = true;
  19346. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19347. // Keep reading
  19348. }
  19349. if (n < 0) {
  19350. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19351. handle.get_read_error() == Error::Read)
  19352. << "Actual error: " << to_string(handle.get_read_error());
  19353. }
  19354. svr.stop();
  19355. t.join();
  19356. }
  19357. #endif
  19358. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19359. using namespace httplib;
  19360. // Create a test file
  19361. const char *fname = "etag_testfile.txt";
  19362. const char *content = "etag-content";
  19363. {
  19364. std::ofstream ofs(fname);
  19365. ofs << content;
  19366. ASSERT_TRUE(ofs.good());
  19367. }
  19368. Server svr;
  19369. svr.set_mount_point("/static", ".");
  19370. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19371. svr.wait_until_ready();
  19372. Client cli(HOST, PORT);
  19373. // First request: should get 200 with ETag header
  19374. auto res1 = cli.Get("/static/etag_testfile.txt");
  19375. ASSERT_TRUE(res1);
  19376. ASSERT_EQ(200, res1->status);
  19377. ASSERT_TRUE(res1->has_header("ETag"));
  19378. std::string etag = res1->get_header_value("ETag");
  19379. EXPECT_FALSE(etag.empty());
  19380. // Verify ETag format: W/"hex-hex"
  19381. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19382. EXPECT_EQ('W', etag[0]);
  19383. EXPECT_EQ('/', etag[1]);
  19384. EXPECT_EQ('"', etag[2]);
  19385. EXPECT_EQ('"', etag.back());
  19386. // Exact match: expect 304 Not Modified
  19387. Headers h2 = {{"If-None-Match", etag}};
  19388. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19389. ASSERT_TRUE(res2);
  19390. EXPECT_EQ(304, res2->status);
  19391. // Wildcard match: expect 304 Not Modified
  19392. Headers h3 = {{"If-None-Match", "*"}};
  19393. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19394. ASSERT_TRUE(res3);
  19395. EXPECT_EQ(304, res3->status);
  19396. // Non-matching ETag: expect 200
  19397. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19398. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19399. ASSERT_TRUE(res4);
  19400. EXPECT_EQ(200, res4->status);
  19401. // Multiple ETags with one matching: expect 304
  19402. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19403. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19404. ASSERT_TRUE(res5);
  19405. EXPECT_EQ(304, res5->status);
  19406. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19407. // that equivalent to the single comma-separated list above, so the match on
  19408. // the second line must still be found.
  19409. Headers h6;
  19410. h6.emplace("If-None-Match", "W/\"other\"");
  19411. h6.emplace("If-None-Match", etag);
  19412. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19413. ASSERT_TRUE(res6);
  19414. EXPECT_EQ(304, res6->status);
  19415. svr.stop();
  19416. t.join();
  19417. std::remove(fname);
  19418. }
  19419. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19420. using namespace httplib;
  19421. Server svr;
  19422. svr.set_mount_point("/static", ".");
  19423. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19424. svr.wait_until_ready();
  19425. Client cli(HOST, PORT);
  19426. // Send If-None-Match: * to a non-existent file
  19427. Headers h = {{"If-None-Match", "*"}};
  19428. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19430. EXPECT_EQ(404, res->status);
  19431. svr.stop();
  19432. t.join();
  19433. }
  19434. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19435. using namespace httplib;
  19436. // Create a test file
  19437. const char *fname = "etag_boundary_testfile.txt";
  19438. const char *content = "boundary-test";
  19439. {
  19440. std::ofstream ofs(fname);
  19441. ofs << content;
  19442. ASSERT_TRUE(ofs.good());
  19443. }
  19444. Server svr;
  19445. svr.set_mount_point("/static", ".");
  19446. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19447. svr.wait_until_ready();
  19448. Client cli(HOST, PORT);
  19449. // Get the actual ETag
  19450. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19451. ASSERT_TRUE(res1);
  19452. ASSERT_EQ(200, res1->status);
  19453. ASSERT_TRUE(res1->has_header("ETag"));
  19454. std::string etag = res1->get_header_value("ETag");
  19455. // Test 1: Very long ETag value (longer than actual ETag)
  19456. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19457. Headers h1 = {{"If-None-Match", "W/"
  19458. "\"very-long-etag-value-that-is-much-longer-"
  19459. "than-the-actual-etag-value\""}};
  19460. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19461. ASSERT_TRUE(res2);
  19462. EXPECT_EQ(200, res2->status); // Should not match
  19463. // Test 2: Long string followed by wildcard
  19464. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19465. // string)
  19466. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19467. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19468. ASSERT_TRUE(res3);
  19469. EXPECT_EQ(304, res3->status); // Should match on "*"
  19470. // Test 3: Wildcard followed by long string
  19471. // Should match on "*" immediately and return 304
  19472. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19473. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19474. ASSERT_TRUE(res4);
  19475. EXPECT_EQ(304, res4->status); // Should match on "*"
  19476. // Test 4: Multiple long non-matching values
  19477. // Should NOT match and return 200 (test that all comparisons are safe)
  19478. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19479. "W/\"second-long-non-matching-value\", "
  19480. "W/\"third-long-non-matching-value\""}};
  19481. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19482. ASSERT_TRUE(res5);
  19483. EXPECT_EQ(200, res5->status); // Should not match
  19484. // Test 5: Single character that is not "*" (edge case)
  19485. Headers h5 = {{"If-None-Match", "X"}};
  19486. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19487. ASSERT_TRUE(res6);
  19488. EXPECT_EQ(200, res6->status); // Should not match
  19489. svr.stop();
  19490. t.join();
  19491. std::remove(fname);
  19492. }
  19493. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19494. using namespace httplib;
  19495. // Create a test file
  19496. const char *fname = "ims_testfile.txt";
  19497. const char *content = "if-modified-since-test";
  19498. {
  19499. std::ofstream ofs(fname);
  19500. ofs << content;
  19501. ASSERT_TRUE(ofs.good());
  19502. }
  19503. Server svr;
  19504. svr.set_mount_point("/static", ".");
  19505. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19506. svr.wait_until_ready();
  19507. Client cli(HOST, PORT);
  19508. // First request: should get 200 with Last-Modified header
  19509. auto res1 = cli.Get("/static/ims_testfile.txt");
  19510. ASSERT_TRUE(res1);
  19511. ASSERT_EQ(200, res1->status);
  19512. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19513. std::string last_modified = res1->get_header_value("Last-Modified");
  19514. EXPECT_FALSE(last_modified.empty());
  19515. // If-Modified-Since with same time: expect 304
  19516. Headers h2 = {{"If-Modified-Since", last_modified}};
  19517. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19518. ASSERT_TRUE(res2);
  19519. EXPECT_EQ(304, res2->status);
  19520. // If-Modified-Since with future time: expect 304
  19521. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19522. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19523. ASSERT_TRUE(res3);
  19524. EXPECT_EQ(304, res3->status);
  19525. // If-Modified-Since with past time: expect 200
  19526. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19527. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19528. ASSERT_TRUE(res4);
  19529. EXPECT_EQ(200, res4->status);
  19530. // If-None-Match takes precedence over If-Modified-Since
  19531. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19532. ASSERT_TRUE(res1->has_header("ETag"));
  19533. std::string etag = res1->get_header_value("ETag");
  19534. Headers h5 = {{"If-None-Match", etag},
  19535. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19536. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19537. ASSERT_TRUE(res5);
  19538. EXPECT_EQ(304, res5->status);
  19539. svr.stop();
  19540. t.join();
  19541. std::remove(fname);
  19542. }
  19543. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19544. using namespace httplib;
  19545. Server svr;
  19546. // Endpoint that returns compressible content
  19547. svr.Get("/compressible", [](const Request &, Response &res) {
  19548. // Return a large enough body to trigger compression
  19549. std::string body(1000, 'a');
  19550. res.set_content(body, "text/plain");
  19551. });
  19552. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19553. svr.wait_until_ready();
  19554. Client cli(HOST, PORT);
  19555. // Request with gzip support: should get Vary header when compressed
  19556. cli.set_compress(true);
  19557. auto res1 = cli.Get("/compressible");
  19558. ASSERT_TRUE(res1);
  19559. EXPECT_EQ(200, res1->status);
  19560. // If Content-Encoding is set, Vary should also be set
  19561. if (res1->has_header("Content-Encoding")) {
  19562. EXPECT_TRUE(res1->has_header("Vary"));
  19563. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19564. }
  19565. // Request without Accept-Encoding header: should not have compression
  19566. Headers h_no_compress;
  19567. auto res2 = cli.Get("/compressible", h_no_compress);
  19568. ASSERT_TRUE(res2);
  19569. EXPECT_EQ(200, res2->status);
  19570. // Verify Vary header is present when compression is applied
  19571. // (the exact behavior depends on server configuration)
  19572. svr.stop();
  19573. t.join();
  19574. }
  19575. TEST(ETagTest, IfRangeWithETag) {
  19576. using namespace httplib;
  19577. // Create a test file with known content
  19578. const char *fname = "if_range_testfile.txt";
  19579. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19580. {
  19581. std::ofstream ofs(fname);
  19582. ofs << content;
  19583. ASSERT_TRUE(ofs.good());
  19584. }
  19585. Server svr;
  19586. svr.set_mount_point("/static", ".");
  19587. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19588. svr.wait_until_ready();
  19589. Client cli(HOST, PORT);
  19590. // First request: get ETag
  19591. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19592. ASSERT_TRUE(res1);
  19593. ASSERT_EQ(200, res1->status);
  19594. ASSERT_TRUE(res1->has_header("ETag"));
  19595. std::string etag = res1->get_header_value("ETag");
  19596. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19597. // Since our server generates weak ETags (W/"..."), If-Range with our
  19598. // ETag should NOT result in partial content - it should return full content.
  19599. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19600. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19601. ASSERT_TRUE(res2);
  19602. // Weak ETag in If-Range -> full content (200), not partial (206)
  19603. EXPECT_EQ(200, res2->status);
  19604. EXPECT_EQ(content, res2->body);
  19605. EXPECT_FALSE(res2->has_header("Content-Range"));
  19606. // Range request with non-matching If-Range (ETag): should get 200 (full
  19607. // content)
  19608. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19609. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19610. ASSERT_TRUE(res3);
  19611. EXPECT_EQ(200, res3->status);
  19612. EXPECT_EQ(content, res3->body);
  19613. EXPECT_FALSE(res3->has_header("Content-Range"));
  19614. // Range request with strong ETag (hypothetical - our server doesn't generate
  19615. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19616. // should return full content)
  19617. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19618. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19619. ASSERT_TRUE(res4);
  19620. EXPECT_EQ(200, res4->status);
  19621. EXPECT_EQ(content, res4->body);
  19622. EXPECT_FALSE(res4->has_header("Content-Range"));
  19623. svr.stop();
  19624. t.join();
  19625. std::remove(fname);
  19626. }
  19627. TEST(ETagTest, IfRangeWithDate) {
  19628. using namespace httplib;
  19629. // Create a test file
  19630. const char *fname = "if_range_date_testfile.txt";
  19631. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19632. {
  19633. std::ofstream ofs(fname);
  19634. ofs << content;
  19635. ASSERT_TRUE(ofs.good());
  19636. }
  19637. Server svr;
  19638. svr.set_mount_point("/static", ".");
  19639. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19640. svr.wait_until_ready();
  19641. Client cli(HOST, PORT);
  19642. // First request: get Last-Modified
  19643. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19644. ASSERT_TRUE(res1);
  19645. ASSERT_EQ(200, res1->status);
  19646. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19647. std::string last_modified = res1->get_header_value("Last-Modified");
  19648. // Range request with matching If-Range (date): should get 206
  19649. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19650. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19651. ASSERT_TRUE(res2);
  19652. EXPECT_EQ(206, res2->status);
  19653. EXPECT_EQ("FGHIJ", res2->body);
  19654. // Range request with old If-Range date: should get 200 (full content)
  19655. Headers h3 = {{"Range", "bytes=5-9"},
  19656. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19657. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19658. ASSERT_TRUE(res3);
  19659. EXPECT_EQ(200, res3->status);
  19660. EXPECT_EQ(content, res3->body);
  19661. // Range request with future If-Range date: should get 206
  19662. Headers h4 = {{"Range", "bytes=0-4"},
  19663. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19664. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19665. ASSERT_TRUE(res4);
  19666. EXPECT_EQ(206, res4->status);
  19667. EXPECT_EQ("ABCDE", res4->body);
  19668. svr.stop();
  19669. t.join();
  19670. std::remove(fname);
  19671. }
  19672. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19673. using namespace httplib;
  19674. const char *fname = "etag_malformed.txt";
  19675. const char *content = "malformed-etag";
  19676. {
  19677. std::ofstream ofs(fname);
  19678. ofs << content;
  19679. ASSERT_TRUE(ofs.good());
  19680. }
  19681. Server svr;
  19682. svr.set_mount_point("/static", ".");
  19683. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19684. svr.wait_until_ready();
  19685. Client cli(HOST, PORT);
  19686. // baseline: should get 200 and an ETag
  19687. auto res1 = cli.Get("/static/etag_malformed.txt");
  19688. ASSERT_TRUE(res1);
  19689. ASSERT_EQ(200, res1->status);
  19690. ASSERT_TRUE(res1->has_header("ETag"));
  19691. // Malformed ETag value (missing quotes) should be treated as non-matching
  19692. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19693. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19694. ASSERT_TRUE(res_bad);
  19695. EXPECT_EQ(200, res_bad->status);
  19696. // Whitespace-only header value should be considered invalid / non-matching
  19697. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19698. "Host: localhost\r\n"
  19699. "If-None-Match: \r\n"
  19700. "Connection: close\r\n"
  19701. "\r\n";
  19702. std::string out;
  19703. ASSERT_TRUE(send_request(5, raw_req, &out));
  19704. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19705. svr.stop();
  19706. t.join();
  19707. std::remove(fname);
  19708. }
  19709. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19710. using namespace httplib;
  19711. const char *fname = "ims_invalid_format.txt";
  19712. const char *content = "ims-bad-format";
  19713. {
  19714. std::ofstream ofs(fname);
  19715. ofs << content;
  19716. ASSERT_TRUE(ofs.good());
  19717. }
  19718. Server svr;
  19719. svr.set_mount_point("/static", ".");
  19720. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19721. svr.wait_until_ready();
  19722. Client cli(HOST, PORT);
  19723. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19724. ASSERT_TRUE(res1);
  19725. ASSERT_EQ(200, res1->status);
  19726. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19727. // If-Modified-Since with invalid format should not result in 304
  19728. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19729. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19730. ASSERT_TRUE(res_bad);
  19731. EXPECT_EQ(200, res_bad->status);
  19732. // If-Range with invalid date format should be treated as mismatch -> full
  19733. // content (200)
  19734. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19735. {"If-Range", "invalid-date"}};
  19736. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19737. ASSERT_TRUE(res_ifrange);
  19738. EXPECT_EQ(200, res_ifrange->status);
  19739. svr.stop();
  19740. t.join();
  19741. std::remove(fname);
  19742. }
  19743. TEST(ETagTest, IfRangeWithMalformedETag) {
  19744. using namespace httplib;
  19745. const char *fname = "ifrange_malformed.txt";
  19746. const std::string content = "0123456789";
  19747. {
  19748. std::ofstream ofs(fname);
  19749. ofs << content;
  19750. ASSERT_TRUE(ofs.good());
  19751. }
  19752. Server svr;
  19753. svr.set_mount_point("/static", ".");
  19754. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19755. svr.wait_until_ready();
  19756. Client cli(HOST, PORT);
  19757. // First request: get ETag
  19758. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19759. ASSERT_TRUE(res1);
  19760. ASSERT_EQ(200, res1->status);
  19761. ASSERT_TRUE(res1->has_header("ETag"));
  19762. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19763. // full content (200)
  19764. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19765. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19766. ASSERT_TRUE(res2);
  19767. EXPECT_EQ(200, res2->status);
  19768. EXPECT_EQ(content, res2->body);
  19769. svr.stop();
  19770. t.join();
  19771. std::remove(fname);
  19772. }
  19773. TEST(ETagTest, ExtremeLargeDateValues) {
  19774. using namespace httplib;
  19775. const char *fname = "ims_extreme_date.txt";
  19776. const char *content = "ims-extreme-date";
  19777. {
  19778. std::ofstream ofs(fname);
  19779. ofs << content;
  19780. ASSERT_TRUE(ofs.good());
  19781. }
  19782. Server svr;
  19783. svr.set_mount_point("/static", ".");
  19784. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19785. svr.wait_until_ready();
  19786. Client cli(HOST, PORT);
  19787. auto res1 = cli.Get(std::string("/static/") + fname);
  19788. ASSERT_TRUE(res1);
  19789. ASSERT_EQ(200, res1->status);
  19790. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19791. // Extremely large year that may overflow date parsing routines.
  19792. Headers h_large_date = {
  19793. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19794. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19795. ASSERT_TRUE(res_bad);
  19796. // Expect server to treat this as invalid/mismatch and return full content
  19797. EXPECT_EQ(200, res_bad->status);
  19798. // If-Range with extremely large date should be treated as mismatch -> full
  19799. // content (200)
  19800. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19801. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19802. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19803. ASSERT_TRUE(res_ifrange);
  19804. EXPECT_EQ(200, res_ifrange->status);
  19805. svr.stop();
  19806. t.join();
  19807. std::remove(fname);
  19808. }
  19809. TEST(ETagTest, NegativeFileModificationTime) {
  19810. using namespace httplib;
  19811. const char *fname = "ims_negative_mtime.txt";
  19812. const std::string content = "negative-mtime";
  19813. {
  19814. std::ofstream ofs(fname);
  19815. ofs << content;
  19816. ASSERT_TRUE(ofs.good());
  19817. }
  19818. // Try to set file mtime to a negative value. This may fail on some
  19819. // platforms/filesystems; if it fails, the test will still verify server
  19820. // behaves safely by performing a regular conditional request.
  19821. #if defined(__APPLE__) || defined(__linux__)
  19822. bool set_negative = false;
  19823. do {
  19824. struct timeval times[2];
  19825. // access time: now
  19826. times[0].tv_sec = time(nullptr);
  19827. times[0].tv_usec = 0;
  19828. // modification time: negative (e.g., -1)
  19829. times[1].tv_sec = -1;
  19830. times[1].tv_usec = 0;
  19831. if (utimes(fname, times) == 0) { set_negative = true; }
  19832. } while (0);
  19833. #else
  19834. bool set_negative = false;
  19835. #endif
  19836. Server svr;
  19837. svr.set_mount_point("/static", ".");
  19838. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19839. svr.wait_until_ready();
  19840. Client cli(HOST, PORT);
  19841. auto res1 = cli.Get(std::string("/static/") + fname);
  19842. ASSERT_TRUE(res1);
  19843. ASSERT_EQ(200, res1->status);
  19844. bool has_last_modified = res1->has_header("Last-Modified");
  19845. std::string last_modified;
  19846. if (has_last_modified) {
  19847. last_modified = res1->get_header_value("Last-Modified");
  19848. }
  19849. if (set_negative) {
  19850. // If we successfully set a negative mtime, ensure server returns a
  19851. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19852. // with an old date and ensure server handles it without crash.
  19853. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19854. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19855. ASSERT_TRUE(res2);
  19856. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19857. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19858. } else {
  19859. // Could not set negative mtime on this platform; fall back to verifying
  19860. // that normal invalid/malformed dates are treated safely (non-304).
  19861. Headers h_bad_date = {
  19862. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19863. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19864. ASSERT_TRUE(res_bad);
  19865. EXPECT_EQ(200, res_bad->status);
  19866. }
  19867. svr.stop();
  19868. t.join();
  19869. std::remove(fname);
  19870. }
  19871. //==============================================================================
  19872. // Integration Tests with Server
  19873. //==============================================================================
  19874. class SSEIntegrationTest : public ::testing::Test {
  19875. protected:
  19876. void SetUp() override {
  19877. stop_server_.store(false);
  19878. events_.clear();
  19879. server_ = httplib::detail::make_unique<Server>();
  19880. setup_server();
  19881. start_server();
  19882. }
  19883. void TearDown() override {
  19884. stop_server_.store(true);
  19885. event_cv_.notify_all();
  19886. server_->stop();
  19887. if (server_thread_.joinable()) { server_thread_.join(); }
  19888. }
  19889. void setup_server() {
  19890. // Simple SSE endpoint
  19891. server_->Get("/events", [this](const Request &req, Response &res) {
  19892. auto last_id = req.get_header_value("Last-Event-ID");
  19893. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19894. res.set_chunked_content_provider(
  19895. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19896. std::unique_lock<std::mutex> lock(event_mutex_);
  19897. if (event_cv_.wait_for(
  19898. lock, std::chrono::milliseconds(200), [this] {
  19899. return !events_.empty() || stop_server_.load();
  19900. })) {
  19901. if (stop_server_.load()) { return false; }
  19902. if (!events_.empty()) {
  19903. std::string event = events_.front();
  19904. events_.erase(events_.begin());
  19905. sink.write(event.data(), event.size());
  19906. return true;
  19907. }
  19908. }
  19909. return !stop_server_.load();
  19910. });
  19911. });
  19912. // Endpoint that returns error
  19913. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19914. res.status = 500;
  19915. res.set_content("Internal Server Error", "text/plain");
  19916. });
  19917. // Endpoint for custom event types
  19918. server_->Get("/custom-events", [](const Request &, Response &res) {
  19919. res.set_chunked_content_provider(
  19920. "text/event-stream", [](size_t offset, DataSink &sink) {
  19921. if (offset == 0) {
  19922. std::string event = "event: update\ndata: updated\n\n"
  19923. "event: delete\ndata: deleted\n\n";
  19924. sink.write(event.data(), event.size());
  19925. }
  19926. return false; // End stream after sending
  19927. });
  19928. });
  19929. }
  19930. void start_server() {
  19931. port_ = server_->bind_to_any_port(HOST);
  19932. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19933. // Wait for server to start
  19934. while (!server_->is_running()) {
  19935. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19936. }
  19937. }
  19938. int get_port() const { return port_; }
  19939. void send_event(const std::string &event) {
  19940. std::lock_guard<std::mutex> lock(event_mutex_);
  19941. events_.push_back(event);
  19942. event_cv_.notify_all();
  19943. }
  19944. std::unique_ptr<Server> server_;
  19945. std::thread server_thread_;
  19946. std::mutex event_mutex_;
  19947. std::condition_variable event_cv_;
  19948. std::vector<std::string> events_;
  19949. std::atomic<bool> stop_server_{false};
  19950. std::string last_received_event_id_;
  19951. int port_ = 0;
  19952. };
  19953. //==============================================================================
  19954. // SSE Parsing Tests
  19955. //==============================================================================
  19956. class SSEParsingTest : public SSEIntegrationTest {
  19957. protected:
  19958. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19959. // A trailing sentinel event tells when the whole stream has been parsed.
  19960. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19961. auto body = stream + "event: end\ndata: end\n\n";
  19962. server_->Get("/parse", [body](const Request &, Response &res) {
  19963. res.set_content(body, "text/event-stream");
  19964. });
  19965. return collect("/parse");
  19966. }
  19967. // Runs SSEClient against path until an "end" event arrives and returns the
  19968. // messages dispatched before it
  19969. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19970. Client client(HOST, get_port());
  19971. sse::SSEClient sse(client, path);
  19972. std::mutex mutex;
  19973. std::condition_variable cv;
  19974. std::vector<sse::SSEMessage> messages;
  19975. auto done = false;
  19976. sse.on_message([&](const sse::SSEMessage &msg) {
  19977. std::lock_guard<std::mutex> lock(mutex);
  19978. // Ignore a replay from a reconnect that races with stop()
  19979. if (!done) { messages.push_back(msg); }
  19980. });
  19981. sse.on_event("end", [&](const sse::SSEMessage &) {
  19982. std::lock_guard<std::mutex> lock(mutex);
  19983. done = true;
  19984. cv.notify_all();
  19985. });
  19986. sse.set_reconnect_interval(100);
  19987. sse.start_async();
  19988. {
  19989. std::unique_lock<std::mutex> lock(mutex);
  19990. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19991. }
  19992. sse.stop();
  19993. EXPECT_TRUE(done);
  19994. return messages;
  19995. }
  19996. };
  19997. TEST_F(SSEParsingTest, SingleLineData) {
  19998. auto msgs = parse("data: hello\n\n");
  19999. ASSERT_EQ(msgs.size(), 1u);
  20000. EXPECT_EQ(msgs[0].data, "hello");
  20001. EXPECT_EQ(msgs[0].event, "message");
  20002. }
  20003. TEST_F(SSEParsingTest, MultiLineData) {
  20004. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20005. ASSERT_EQ(msgs.size(), 1u);
  20006. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20007. }
  20008. TEST_F(SSEParsingTest, CustomEventType) {
  20009. auto msgs = parse("event: update\ndata: payload\n\n");
  20010. ASSERT_EQ(msgs.size(), 1u);
  20011. EXPECT_EQ(msgs[0].event, "update");
  20012. EXPECT_EQ(msgs[0].data, "payload");
  20013. }
  20014. TEST_F(SSEParsingTest, EventIdHandling) {
  20015. auto msgs = parse("id: 12345\ndata: test\n\n");
  20016. ASSERT_EQ(msgs.size(), 1u);
  20017. EXPECT_EQ(msgs[0].id, "12345");
  20018. }
  20019. TEST_F(SSEParsingTest, EmptyEventId) {
  20020. auto msgs = parse("id:\ndata: test\n\n");
  20021. ASSERT_EQ(msgs.size(), 1u);
  20022. EXPECT_EQ(msgs[0].id, "");
  20023. }
  20024. TEST_F(SSEParsingTest, CommentsIgnored) {
  20025. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20026. ASSERT_EQ(msgs.size(), 1u);
  20027. EXPECT_EQ(msgs[0].data, "hello");
  20028. EXPECT_EQ(msgs[0].event, "message");
  20029. }
  20030. TEST_F(SSEParsingTest, ColonInValue) {
  20031. auto msgs = parse("data: hello:world:test\n\n");
  20032. ASSERT_EQ(msgs.size(), 1u);
  20033. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20034. }
  20035. TEST_F(SSEParsingTest, FieldNameOnly) {
  20036. // A line without a colon is a field name with an empty value
  20037. auto msgs = parse("data\n\n");
  20038. ASSERT_EQ(msgs.size(), 1u);
  20039. EXPECT_EQ(msgs[0].data, "");
  20040. }
  20041. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20042. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20043. ASSERT_EQ(msgs.size(), 1u);
  20044. EXPECT_EQ(msgs[0].event, "update");
  20045. EXPECT_EQ(msgs[0].data, "hello");
  20046. }
  20047. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20048. auto msgs = parse("data\r\n\r\n");
  20049. ASSERT_EQ(msgs.size(), 1u);
  20050. EXPECT_EQ(msgs[0].data, "");
  20051. }
  20052. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20053. auto msgs = parse("event: update\rdata: hello\r\r");
  20054. ASSERT_EQ(msgs.size(), 1u);
  20055. EXPECT_EQ(msgs[0].event, "update");
  20056. EXPECT_EQ(msgs[0].data, "hello");
  20057. }
  20058. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20059. // Chunk boundaries fall inside every \r\n and right before the first one
  20060. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20061. "\n\r", "\nevent: end\ndata: end\n\n"};
  20062. server_->Get("/split", [chunks](const Request &, Response &res) {
  20063. auto i = std::make_shared<size_t>(0);
  20064. res.set_chunked_content_provider(
  20065. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20066. if (*i == chunks.size()) {
  20067. sink.done();
  20068. } else {
  20069. sink.write(chunks[*i].data(), chunks[*i].size());
  20070. (*i)++;
  20071. }
  20072. return true;
  20073. });
  20074. });
  20075. auto msgs = collect("/split");
  20076. ASSERT_EQ(msgs.size(), 1u);
  20077. EXPECT_EQ(msgs[0].event, "update");
  20078. EXPECT_EQ(msgs[0].data, "hello");
  20079. }
  20080. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20081. // Only a BOM at the start of the stream is ignored
  20082. auto msgs = parse("\xEF\xBB\xBF"
  20083. "data: first\n\n"
  20084. "\xEF\xBB\xBF"
  20085. "data: second\n\n");
  20086. ASSERT_EQ(msgs.size(), 1u);
  20087. EXPECT_EQ(msgs[0].data, "first");
  20088. }
  20089. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20090. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20091. ASSERT_EQ(msgs.size(), 1u);
  20092. EXPECT_EQ(msgs[0].data, "hello");
  20093. EXPECT_EQ(msgs[0].event, "message");
  20094. }
  20095. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20096. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20097. ASSERT_EQ(msgs.size(), 2u);
  20098. EXPECT_EQ(msgs[0].data, "hello");
  20099. EXPECT_EQ(msgs[1].data, "hello");
  20100. }
  20101. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20102. // An event without data is not dispatched, and its type must not leak
  20103. // into the next event
  20104. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20105. ASSERT_EQ(msgs.size(), 1u);
  20106. EXPECT_EQ(msgs[0].event, "message");
  20107. EXPECT_EQ(msgs[0].data, "hello");
  20108. }
  20109. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20110. // The first connection sends only an id; the second echoes back the
  20111. // Last-Event-ID it was reconnected with
  20112. std::atomic<int> connection_count{0};
  20113. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20114. if (connection_count++ == 0) {
  20115. res.set_content("id: 42\n\n", "text/event-stream");
  20116. } else {
  20117. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20118. "\n\nevent: end\ndata: end\n\n",
  20119. "text/event-stream");
  20120. }
  20121. });
  20122. auto msgs = collect("/id-only");
  20123. ASSERT_EQ(msgs.size(), 1u);
  20124. EXPECT_EQ(msgs[0].data, "42");
  20125. }
  20126. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20127. // The first connection sets an id and then clears it with an empty one; the
  20128. // second reports whether it was reconnected with a Last-Event-ID
  20129. std::atomic<int> connection_count{0};
  20130. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20131. if (connection_count++ == 0) {
  20132. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20133. "text/event-stream");
  20134. } else {
  20135. res.set_content(
  20136. std::string("data: ") +
  20137. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20138. "\n\nevent: end\ndata: end\n\n",
  20139. "text/event-stream");
  20140. }
  20141. });
  20142. auto msgs = collect("/id-clear");
  20143. ASSERT_EQ(msgs.size(), 3u);
  20144. EXPECT_EQ(msgs[0].id, "1");
  20145. EXPECT_EQ(msgs[1].id, "");
  20146. EXPECT_EQ(msgs[2].data, "not sent");
  20147. }
  20148. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20149. // The first connection sets an id and then sends ids that cannot be carried
  20150. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20151. // with
  20152. std::atomic<int> connection_count{0};
  20153. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20154. if (connection_count++ == 0) {
  20155. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20156. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20157. "text/event-stream");
  20158. } else {
  20159. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20160. "\n\nevent: end\ndata: end\n\n",
  20161. "text/event-stream");
  20162. }
  20163. });
  20164. auto msgs = collect("/id-unsendable");
  20165. ASSERT_EQ(msgs.size(), 1u);
  20166. EXPECT_EQ(msgs[0].data, "42");
  20167. }
  20168. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20169. auto msgs = parse("event: notification\nid: evt-42\n"
  20170. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20171. ASSERT_EQ(msgs.size(), 1u);
  20172. EXPECT_EQ(msgs[0].event, "notification");
  20173. EXPECT_EQ(msgs[0].id, "evt-42");
  20174. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20175. }
  20176. TEST(SSEMessageTest, Clear) {
  20177. sse::SSEMessage msg;
  20178. msg.event = "custom";
  20179. msg.data = "some data";
  20180. msg.id = "123";
  20181. msg.clear();
  20182. EXPECT_EQ(msg.event, "message");
  20183. EXPECT_EQ(msg.data, "");
  20184. EXPECT_EQ(msg.id, "");
  20185. }
  20186. //==============================================================================
  20187. // SSE Integration Tests
  20188. //==============================================================================
  20189. // Test: Successful connection and on_open callback
  20190. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20191. // Add a simple endpoint that sends one event and closes
  20192. server_->Get("/simple-event", [](const Request &, Response &res) {
  20193. res.set_chunked_content_provider(
  20194. "text/event-stream", [](size_t offset, DataSink &sink) {
  20195. if (offset == 0) {
  20196. std::string event = "data: hello\n\n";
  20197. sink.write(event.data(), event.size());
  20198. }
  20199. return false; // Close stream after sending
  20200. });
  20201. });
  20202. Client client("localhost", get_port());
  20203. sse::SSEClient sse(client, "/simple-event");
  20204. std::atomic<bool> open_called{false};
  20205. std::atomic<bool> message_received{false};
  20206. sse.on_open([&open_called]() { open_called.store(true); });
  20207. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20208. if (msg.data == "hello") { message_received.store(true); }
  20209. });
  20210. sse.set_reconnect_interval(100);
  20211. sse.set_max_reconnect_attempts(1);
  20212. // Start async
  20213. sse.start_async();
  20214. // Wait for message to be processed
  20215. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20216. sse.stop();
  20217. EXPECT_TRUE(open_called.load());
  20218. EXPECT_TRUE(message_received.load());
  20219. }
  20220. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20221. // A data line that never ends.
  20222. server_->Get("/endless-line", [](const Request &, Response &res) {
  20223. res.set_chunked_content_provider(
  20224. "text/event-stream", [](size_t offset, DataSink &sink) {
  20225. if (offset == 0) { sink.write("data: ", 6); }
  20226. std::string chunk(64 * 1024, 'A');
  20227. return sink.write(chunk.data(), chunk.size());
  20228. });
  20229. });
  20230. Client client("localhost", get_port());
  20231. // A stream that may run forever, so that only the event is bounded.
  20232. client.set_payload_max_length(0);
  20233. sse::SSEClient sse(client, "/endless-line");
  20234. std::atomic<bool> too_long{false};
  20235. sse.on_error([&](Error err) {
  20236. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20237. });
  20238. sse.set_max_reconnect_attempts(1);
  20239. sse.start_async();
  20240. for (int i = 0; i < 500 && !too_long; i++) {
  20241. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20242. }
  20243. sse.stop();
  20244. EXPECT_TRUE(too_long);
  20245. }
  20246. // Test: on_message callback
  20247. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20248. // Endpoint that sends multiple events then closes
  20249. server_->Get("/multi-event", [](const Request &, Response &res) {
  20250. res.set_chunked_content_provider(
  20251. "text/event-stream", [](size_t offset, DataSink &sink) {
  20252. if (offset == 0) {
  20253. std::string events = "data: message1\n\ndata: message2\n\n";
  20254. sink.write(events.data(), events.size());
  20255. }
  20256. return false;
  20257. });
  20258. });
  20259. Client client("localhost", get_port());
  20260. sse::SSEClient sse(client, "/multi-event");
  20261. std::vector<std::string> received_messages;
  20262. std::mutex messages_mutex;
  20263. sse.on_message([&](const sse::SSEMessage &msg) {
  20264. std::lock_guard<std::mutex> lock(messages_mutex);
  20265. received_messages.push_back(msg.data);
  20266. });
  20267. sse.set_reconnect_interval(100);
  20268. sse.set_max_reconnect_attempts(1);
  20269. sse.start_async();
  20270. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20271. sse.stop();
  20272. std::lock_guard<std::mutex> lock(messages_mutex);
  20273. EXPECT_GE(received_messages.size(), 2u);
  20274. if (received_messages.size() >= 2) {
  20275. EXPECT_EQ(received_messages[0], "message1");
  20276. EXPECT_EQ(received_messages[1], "message2");
  20277. }
  20278. }
  20279. // Test: on_event for specific types
  20280. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20281. Client client("localhost", get_port());
  20282. sse::SSEClient sse(client, "/custom-events");
  20283. std::atomic<bool> update_received{false};
  20284. std::atomic<bool> delete_received{false};
  20285. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20286. if (msg.data == "updated") { update_received.store(true); }
  20287. });
  20288. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20289. if (msg.data == "deleted") { delete_received.store(true); }
  20290. });
  20291. sse.set_max_reconnect_attempts(1);
  20292. sse.start_async();
  20293. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20294. sse.stop();
  20295. EXPECT_TRUE(update_received.load());
  20296. EXPECT_TRUE(delete_received.load());
  20297. }
  20298. // Test: on_error callback on connection failure
  20299. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20300. // Connect to a non-existent port
  20301. Client client("localhost", 59999);
  20302. sse::SSEClient sse(client, "/events");
  20303. std::atomic<bool> error_called{false};
  20304. Error received_error = Error::Success;
  20305. sse.on_error([&](Error err) {
  20306. error_called.store(true);
  20307. received_error = err;
  20308. });
  20309. sse.set_reconnect_interval(50);
  20310. sse.set_max_reconnect_attempts(1);
  20311. sse.start_async();
  20312. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20313. sse.stop();
  20314. EXPECT_TRUE(error_called.load());
  20315. EXPECT_NE(received_error, Error::Success);
  20316. }
  20317. // Test: Last-Event-ID header sent on reconnect
  20318. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20319. // Endpoint that sends event with ID
  20320. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20321. res.set_chunked_content_provider(
  20322. "text/event-stream", [](size_t offset, DataSink &sink) {
  20323. if (offset == 0) {
  20324. std::string event = "id: evt-123\ndata: test\n\n";
  20325. sink.write(event.data(), event.size());
  20326. }
  20327. return false;
  20328. });
  20329. });
  20330. Client client("localhost", get_port());
  20331. sse::SSEClient sse(client, "/event-with-id");
  20332. std::atomic<bool> id_received{false};
  20333. sse.on_message([&](const sse::SSEMessage &msg) {
  20334. if (!msg.id.empty()) { id_received.store(true); }
  20335. });
  20336. sse.set_reconnect_interval(100);
  20337. sse.set_max_reconnect_attempts(1);
  20338. sse.start_async();
  20339. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20340. sse.stop();
  20341. EXPECT_TRUE(id_received.load());
  20342. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20343. }
  20344. // Test: Manual stop
  20345. TEST_F(SSEIntegrationTest, ManualStop) {
  20346. // Endpoint that sends one event and stays open briefly
  20347. std::atomic<bool> handler_running{true};
  20348. server_->Get("/stay-open", [&handler_running](const Request &,
  20349. Response &res) {
  20350. res.set_chunked_content_provider(
  20351. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20352. if (offset == 0) {
  20353. std::string event = "data: connected\n\n";
  20354. sink.write(event.data(), event.size());
  20355. }
  20356. // Keep connection open while handler_running is true
  20357. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20358. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20359. }
  20360. return false;
  20361. });
  20362. });
  20363. Client client("localhost", get_port());
  20364. sse::SSEClient sse(client, "/stay-open");
  20365. std::atomic<bool> connected{false};
  20366. sse.on_open([&connected]() { connected.store(true); });
  20367. sse.set_reconnect_interval(100);
  20368. sse.set_max_reconnect_attempts(1);
  20369. sse.start_async();
  20370. // Wait for connection to establish
  20371. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20372. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20373. }
  20374. EXPECT_TRUE(connected.load());
  20375. EXPECT_TRUE(sse.is_connected());
  20376. // Signal handler to stop
  20377. handler_running.store(false);
  20378. // Stop SSE client
  20379. sse.stop();
  20380. EXPECT_FALSE(sse.is_connected());
  20381. }
  20382. // Test: SSEClient with custom headers
  20383. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20384. // Setup a server endpoint that checks for custom header
  20385. std::atomic<bool> header_received{false};
  20386. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20387. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20388. header_received.store(true);
  20389. }
  20390. res.set_chunked_content_provider("text/event-stream",
  20391. [](size_t, DataSink &) { return false; });
  20392. });
  20393. Client client("localhost", get_port());
  20394. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20395. sse::SSEClient sse(client, "/header-check", headers);
  20396. sse.set_max_reconnect_attempts(1);
  20397. sse.start_async();
  20398. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20399. sse.stop();
  20400. EXPECT_TRUE(header_received.load());
  20401. }
  20402. // Test: Reconnect interval configuration
  20403. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20404. Client client("localhost", get_port());
  20405. sse::SSEClient sse(client, "/events");
  20406. auto &result = sse.set_reconnect_interval(500);
  20407. // Builder pattern should return reference to self
  20408. EXPECT_EQ(&result, &sse);
  20409. }
  20410. // Test: Max reconnect attempts
  20411. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20412. // Connect to non-existent port to force reconnects
  20413. Client client("localhost", 59998);
  20414. sse::SSEClient sse(client, "/events");
  20415. std::atomic<int> error_count{0};
  20416. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20417. sse.set_reconnect_interval(50);
  20418. sse.set_max_reconnect_attempts(2);
  20419. auto start = std::chrono::steady_clock::now();
  20420. sse.start(); // Blocking call
  20421. auto end = std::chrono::steady_clock::now();
  20422. // Should have stopped after 2 failed attempts
  20423. EXPECT_GE(error_count.load(), 2);
  20424. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20425. auto duration =
  20426. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20427. #ifdef _WIN32
  20428. // Windows is much slower for socket connection failures
  20429. EXPECT_LT(duration.count(), 7000);
  20430. #else
  20431. EXPECT_LT(duration.count(), 1000);
  20432. #endif
  20433. }
  20434. // Test: Multi-line data in integration
  20435. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20436. // Endpoint with multi-line data
  20437. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20438. res.set_chunked_content_provider(
  20439. "text/event-stream", [](size_t offset, DataSink &sink) {
  20440. if (offset == 0) {
  20441. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20442. sink.write(event.data(), event.size());
  20443. }
  20444. return false;
  20445. });
  20446. });
  20447. Client client("localhost", get_port());
  20448. sse::SSEClient sse(client, "/multiline-data");
  20449. std::string received_data;
  20450. std::mutex data_mutex;
  20451. sse.on_message([&](const sse::SSEMessage &msg) {
  20452. std::lock_guard<std::mutex> lock(data_mutex);
  20453. received_data = msg.data;
  20454. });
  20455. sse.set_reconnect_interval(100);
  20456. sse.set_max_reconnect_attempts(1);
  20457. sse.start_async();
  20458. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20459. sse.stop();
  20460. std::lock_guard<std::mutex> lock(data_mutex);
  20461. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20462. }
  20463. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20464. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20465. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20466. DataSink &sink) {
  20467. if (offset == 0) {
  20468. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20469. sink.write(events.data(), events.size());
  20470. }
  20471. return false;
  20472. });
  20473. });
  20474. Client client("localhost", get_port());
  20475. sse::SSEClient sse(client, "/empty-data-lines");
  20476. std::mutex mutex;
  20477. std::condition_variable cv;
  20478. std::vector<std::string> received;
  20479. sse.on_message([&](const sse::SSEMessage &msg) {
  20480. std::lock_guard<std::mutex> lock(mutex);
  20481. received.push_back(msg.data);
  20482. cv.notify_all();
  20483. });
  20484. sse.set_max_reconnect_attempts(1);
  20485. sse.start_async();
  20486. {
  20487. std::unique_lock<std::mutex> lock(mutex);
  20488. cv.wait_for(lock, std::chrono::seconds(2),
  20489. [&] { return received.size() >= 3; });
  20490. }
  20491. sse.stop();
  20492. ASSERT_GE(received.size(), 3u);
  20493. EXPECT_EQ(received[0], "");
  20494. EXPECT_EQ(received[1], "\nhello");
  20495. EXPECT_EQ(received[2], "");
  20496. }
  20497. // Test: Auto-reconnect after server disconnection
  20498. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20499. std::atomic<int> connection_count{0};
  20500. std::atomic<int> message_count{0};
  20501. // Endpoint that sends one event and closes, forcing reconnect
  20502. server_->Get("/reconnect-test",
  20503. [&connection_count](const Request &, Response &res) {
  20504. connection_count.fetch_add(1);
  20505. res.set_chunked_content_provider(
  20506. "text/event-stream", [](size_t offset, DataSink &sink) {
  20507. if (offset == 0) {
  20508. std::string event = "data: hello\n\n";
  20509. sink.write(event.data(), event.size());
  20510. }
  20511. return false; // Close connection after sending
  20512. });
  20513. });
  20514. Client client("localhost", get_port());
  20515. sse::SSEClient sse(client, "/reconnect-test");
  20516. sse.on_message([&message_count](const sse::SSEMessage &) {
  20517. message_count.fetch_add(1);
  20518. });
  20519. sse.set_reconnect_interval(100);
  20520. sse.set_max_reconnect_attempts(3);
  20521. sse.start_async();
  20522. // Wait long enough for multiple reconnects
  20523. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20524. sse.stop();
  20525. // Should have connected multiple times (initial + reconnects)
  20526. EXPECT_GE(connection_count.load(), 2);
  20527. // Should have received messages from multiple connections
  20528. EXPECT_GE(message_count.load(), 2);
  20529. }
  20530. // Test: A retry field that is not all ASCII digits is ignored
  20531. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20532. std::atomic<int> connection_count{0};
  20533. server_->Get("/bad-retry",
  20534. [&connection_count](const Request &, Response &res) {
  20535. connection_count.fetch_add(1);
  20536. res.set_chunked_content_provider(
  20537. "text/event-stream", [](size_t offset, DataSink &sink) {
  20538. if (offset == 0) {
  20539. std::string event = "retry: -1\ndata: hello\n\n";
  20540. sink.write(event.data(), event.size());
  20541. }
  20542. return false;
  20543. });
  20544. });
  20545. Client client("localhost", get_port());
  20546. sse::SSEClient sse(client, "/bad-retry");
  20547. sse.set_reconnect_interval(10000);
  20548. sse.start_async();
  20549. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20550. sse.stop();
  20551. EXPECT_EQ(connection_count.load(), 1);
  20552. }
  20553. // Test: A retry field of all ASCII digits sets the reconnection time
  20554. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20555. std::mutex mutex;
  20556. std::condition_variable cv;
  20557. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20558. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20559. {
  20560. std::lock_guard<std::mutex> lock(mutex);
  20561. connected_at.push_back(std::chrono::steady_clock::now());
  20562. cv.notify_all();
  20563. }
  20564. res.set_chunked_content_provider(
  20565. "text/event-stream", [](size_t offset, DataSink &sink) {
  20566. if (offset == 0) {
  20567. std::string event = "retry: 0\ndata: hello\n\n";
  20568. sink.write(event.data(), event.size());
  20569. }
  20570. return false;
  20571. });
  20572. });
  20573. Client client("localhost", get_port());
  20574. sse::SSEClient sse(client, "/zero-retry");
  20575. sse.set_reconnect_interval(10000);
  20576. sse.start_async();
  20577. {
  20578. std::unique_lock<std::mutex> lock(mutex);
  20579. cv.wait_for(lock, std::chrono::seconds(5),
  20580. [&] { return connected_at.size() >= 2; });
  20581. }
  20582. sse.stop();
  20583. // The server-supplied interval is applied, but never below 100ms, so
  20584. // "retry: 0" does not cause a busy reconnect loop
  20585. std::lock_guard<std::mutex> lock(mutex);
  20586. ASSERT_GE(connected_at.size(), 2u);
  20587. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20588. connected_at[1] - connected_at[0])
  20589. .count();
  20590. EXPECT_GE(interval_ms, 100);
  20591. }
  20592. // Test: Last-Event-ID sent on reconnect
  20593. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20594. std::atomic<int> connection_count{0};
  20595. std::vector<std::string> received_last_event_ids;
  20596. std::mutex id_mutex;
  20597. // Endpoint that checks Last-Event-ID header and sends event with ID
  20598. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20599. int conn = connection_count.fetch_add(1);
  20600. // Capture the Last-Event-ID header from each connection
  20601. {
  20602. std::lock_guard<std::mutex> lock(id_mutex);
  20603. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20604. }
  20605. res.set_chunked_content_provider(
  20606. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20607. if (offset == 0) {
  20608. std::string event =
  20609. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20610. sink.write(event.data(), event.size());
  20611. }
  20612. return false;
  20613. });
  20614. });
  20615. Client client("localhost", get_port());
  20616. sse::SSEClient sse(client, "/reconnect-with-id");
  20617. sse.set_reconnect_interval(100);
  20618. sse.set_max_reconnect_attempts(3);
  20619. sse.start_async();
  20620. // Wait for at least 2 connections
  20621. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20622. sse.stop();
  20623. // Verify behavior
  20624. std::lock_guard<std::mutex> lock(id_mutex);
  20625. EXPECT_GE(received_last_event_ids.size(), 2u);
  20626. // First connection should have no Last-Event-ID
  20627. if (!received_last_event_ids.empty()) {
  20628. EXPECT_EQ(received_last_event_ids[0], "");
  20629. }
  20630. // Second connection should have Last-Event-ID from first connection
  20631. if (received_last_event_ids.size() >= 2) {
  20632. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20633. }
  20634. }
  20635. // Test: set_headers updates headers used on reconnect
  20636. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20637. std::vector<std::string> received_tokens;
  20638. std::mutex token_mutex;
  20639. // Endpoint that captures Authorization header
  20640. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20641. {
  20642. std::lock_guard<std::mutex> lock(token_mutex);
  20643. received_tokens.push_back(req.get_header_value("Authorization"));
  20644. }
  20645. res.set_chunked_content_provider(
  20646. "text/event-stream", [](size_t offset, DataSink &sink) {
  20647. if (offset == 0) {
  20648. std::string event = "data: hello\n\n";
  20649. sink.write(event.data(), event.size());
  20650. }
  20651. return false; // Close connection to trigger reconnect
  20652. });
  20653. });
  20654. Client client("localhost", get_port());
  20655. Headers headers = {{"Authorization", "Bearer old-token"}};
  20656. sse::SSEClient sse(client, "/auth-check", headers);
  20657. // Update headers on each successful connection
  20658. sse.on_open(
  20659. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20660. sse.set_reconnect_interval(100);
  20661. sse.set_max_reconnect_attempts(3);
  20662. sse.start_async();
  20663. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20664. sse.stop();
  20665. std::lock_guard<std::mutex> lock(token_mutex);
  20666. ASSERT_GE(received_tokens.size(), 2u);
  20667. // First connection uses original header
  20668. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20669. // Second connection uses updated header from set_headers
  20670. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20671. }
  20672. // Test: 401 allows reconnection (so on_error can refresh headers)
  20673. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20674. std::atomic<int> connection_count{0};
  20675. // Endpoint: returns 401 on first attempt, 200 on second
  20676. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20677. int conn = connection_count.fetch_add(1);
  20678. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20679. res.status = StatusCode::Unauthorized_401;
  20680. res.set_content("Unauthorized", "text/plain");
  20681. return;
  20682. }
  20683. res.set_chunked_content_provider(
  20684. "text/event-stream", [](size_t offset, DataSink &sink) {
  20685. if (offset == 0) {
  20686. std::string event = "data: authenticated\n\n";
  20687. sink.write(event.data(), event.size());
  20688. }
  20689. return false;
  20690. });
  20691. });
  20692. Client client("localhost", get_port());
  20693. Headers headers = {{"Authorization", "Bearer expired"}};
  20694. sse::SSEClient sse(client, "/auth-retry", headers);
  20695. std::atomic<bool> message_received{false};
  20696. // Refresh token on error
  20697. sse.on_error(
  20698. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20699. sse.on_message([&](const sse::SSEMessage &msg) {
  20700. if (msg.data == "authenticated") { message_received.store(true); }
  20701. });
  20702. sse.set_reconnect_interval(100);
  20703. sse.set_max_reconnect_attempts(3);
  20704. sse.start_async();
  20705. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20706. sse.stop();
  20707. // Should have reconnected after 401 and succeeded with new token
  20708. EXPECT_GE(connection_count.load(), 2);
  20709. EXPECT_TRUE(message_received.load());
  20710. }
  20711. TEST(Issue2318Test, EmptyHostString) {
  20712. {
  20713. httplib::Client cli_empty("", PORT);
  20714. auto res = cli_empty.Get("/");
  20715. ASSERT_FALSE(res);
  20716. EXPECT_EQ(httplib::Error::Connection, res.error());
  20717. }
  20718. {
  20719. httplib::Client cli(" ", PORT);
  20720. auto res = cli.Get("/");
  20721. ASSERT_FALSE(res);
  20722. EXPECT_EQ(httplib::Error::Connection, res.error());
  20723. }
  20724. }
  20725. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20726. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20727. Server svr;
  20728. // Set a small payload limit (1KB)
  20729. svr.set_payload_max_length(1024);
  20730. svr.Post("/test", [&](const Request &req, Response &res) {
  20731. res.set_content("Body size: " + std::to_string(req.body.size()),
  20732. "text/plain");
  20733. });
  20734. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20735. auto se = detail::scope_exit([&] {
  20736. svr.stop();
  20737. listen_thread.join();
  20738. });
  20739. svr.wait_until_ready();
  20740. // Create data that compresses well but exceeds limit when decompressed
  20741. // 8KB of repeated null bytes compresses to a very small size
  20742. std::string original_data(8 * 1024, '\0');
  20743. // Compress the data using gzip
  20744. std::string compressed_data;
  20745. detail::gzip_compressor compressor;
  20746. compressor.compress(original_data.data(), original_data.size(), true,
  20747. [&](const char *data, size_t size) {
  20748. compressed_data.append(data, size);
  20749. return true;
  20750. });
  20751. // Verify compression worked (compressed should be much smaller)
  20752. ASSERT_LT(compressed_data.size(), original_data.size());
  20753. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20754. // Send compressed data with Content-Encoding: gzip
  20755. Client cli(HOST, PORT);
  20756. Headers headers = {{"Content-Encoding", "gzip"}};
  20757. auto res =
  20758. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20759. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20761. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20762. }
  20763. #endif
  20764. // ============================================================================
  20765. // OpenSSL-Specific Tests
  20766. // ============================================================================
  20767. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20768. X509 *readCertificate(const std::string &strFileName) {
  20769. std::ifstream inStream(strFileName);
  20770. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20771. std::istreambuf_iterator<char>());
  20772. if (strCertPEM.empty()) return (nullptr);
  20773. BIO *pbCert = BIO_new(BIO_s_mem());
  20774. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20775. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20776. BIO_free(pbCert);
  20777. return (pCert);
  20778. }
  20779. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20780. std::ifstream inStream(strFileName);
  20781. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20782. std::istreambuf_iterator<char>());
  20783. if (strPrivateKeyPEM.empty()) return (nullptr);
  20784. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20785. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20786. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20787. BIO_free(pbPrivKey);
  20788. return (pPrivateKey);
  20789. }
  20790. TEST(BindServerTest, UpdateCerts) {
  20791. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20792. int port = svr.bind_to_any_port("0.0.0.0");
  20793. ASSERT_TRUE(svr.is_valid());
  20794. ASSERT_TRUE(port > 0);
  20795. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20796. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20797. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20798. ASSERT_TRUE(cert != nullptr);
  20799. ASSERT_TRUE(ca_cert != nullptr);
  20800. ASSERT_TRUE(key != nullptr);
  20801. X509_STORE *cert_store = X509_STORE_new();
  20802. X509_STORE_add_cert(cert_store, ca_cert);
  20803. // svr.update_certs(cert, key, cert_store); // deprecated
  20804. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20805. CLIENT_CA_CERT_FILE);
  20806. ASSERT_TRUE(svr.is_valid());
  20807. svr.stop();
  20808. X509_STORE_free(cert_store);
  20809. X509_free(cert);
  20810. X509_free(ca_cert);
  20811. EVP_PKEY_free(key);
  20812. }
  20813. // Test that update_certs() updates client CA list correctly
  20814. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20815. // Start with file-based constructor
  20816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20817. ASSERT_TRUE(svr.is_valid());
  20818. // Initially no client CA list should be set
  20819. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20820. ASSERT_TRUE(ssl_ctx != nullptr);
  20821. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20822. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20823. EXPECT_EQ(0, count_before);
  20824. // Now update with client CA (PEM string)
  20825. std::string cert_pem, key_pem, ca_pem;
  20826. read_file(SERVER_CERT_FILE, cert_pem);
  20827. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20828. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20829. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20830. ASSERT_TRUE(svr.is_valid());
  20831. // Now client CA list should be set
  20832. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20833. ASSERT_TRUE(ca_list_after != nullptr);
  20834. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20835. }
  20836. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20837. // Test that the file-path SSLServer constructor properly sets the client CA
  20838. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20840. ASSERT_TRUE(svr.is_valid());
  20841. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20842. ASSERT_TRUE(ssl_ctx != nullptr);
  20843. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20844. ASSERT_TRUE(ca_list != nullptr);
  20845. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20846. }
  20847. #endif
  20848. // ============================================================================
  20849. // MbedTLS-Specific Tests
  20850. // ============================================================================
  20851. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20852. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20853. using namespace httplib::tls;
  20854. // Track if callback was invoked
  20855. bool callback_invoked = false;
  20856. // The callback receives void* ctx which is actually MbedTlsContext*
  20857. // We can access the mbedtls_ssl_config via the context
  20858. auto setup_callback = [&callback_invoked](void *ctx) {
  20859. callback_invoked = true;
  20860. // Cast to MbedTlsContext* to access the ssl config
  20861. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20862. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20863. // Use static variables to hold certificate data (simplified for test)
  20864. static mbedtls_x509_crt own_cert;
  20865. static mbedtls_pk_context own_key;
  20866. static mbedtls_x509_crt ca_chain;
  20867. static bool initialized = false;
  20868. if (!initialized) {
  20869. mbedtls_x509_crt_init(&own_cert);
  20870. mbedtls_pk_init(&own_key);
  20871. mbedtls_x509_crt_init(&ca_chain);
  20872. // Load server certificate
  20873. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20874. return false;
  20875. }
  20876. // Load server private key.
  20877. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20878. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20879. #if MBEDTLS_VERSION_MAJOR == 3
  20880. ,
  20881. mbedtls_ctr_drbg_random, nullptr
  20882. #endif
  20883. ) != 0) {
  20884. return false;
  20885. }
  20886. // Load CA chain for client verification
  20887. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20888. return false;
  20889. }
  20890. initialized = true;
  20891. }
  20892. // Configure the SSL config
  20893. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20894. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20895. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20896. // Set minimum TLS version using mbedTLS native API
  20897. #if MBEDTLS_VERSION_MAJOR >= 3
  20898. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20899. #else
  20900. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20901. MBEDTLS_SSL_MINOR_VERSION_3);
  20902. #endif
  20903. return true;
  20904. };
  20905. SSLServer svr(setup_callback);
  20906. ASSERT_TRUE(svr.is_valid());
  20907. ASSERT_TRUE(callback_invoked);
  20908. svr.Get("/test", [&](const Request &req, Response &res) {
  20909. res.set_content("test", "text/plain");
  20910. auto cert = req.peer_cert();
  20911. ASSERT_TRUE(static_cast<bool>(cert));
  20912. auto common_name = cert.subject_cn();
  20913. EXPECT_EQ("Common Name", common_name);
  20914. });
  20915. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20916. auto se = detail::scope_exit([&] {
  20917. svr.stop();
  20918. t.join();
  20919. ASSERT_FALSE(svr.is_running());
  20920. });
  20921. svr.wait_until_ready();
  20922. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20923. cli.enable_server_certificate_verification(false);
  20924. cli.set_connection_timeout(30);
  20925. auto res = cli.Get("/test");
  20926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20927. ASSERT_EQ(StatusCode::OK_200, res->status);
  20928. }
  20929. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20930. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20931. // keep-alive SSL session, which reads through that config in
  20932. // mbedtls_ssl_close_notify.
  20933. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20934. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20935. ASSERT_TRUE(svr.is_valid());
  20936. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20937. res.set_content("test", "text/plain");
  20938. });
  20939. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20940. auto se = detail::scope_exit([&] {
  20941. svr.stop();
  20942. t.join();
  20943. ASSERT_FALSE(svr.is_running());
  20944. });
  20945. svr.wait_until_ready();
  20946. {
  20947. SSLClient cli(HOST, PORT);
  20948. cli.enable_server_certificate_verification(false);
  20949. cli.set_keep_alive(true);
  20950. auto res = cli.Get("/test");
  20951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20952. ASSERT_EQ(StatusCode::OK_200, res->status);
  20953. // cli is destructed here with the keep-alive SSL session still open.
  20954. }
  20955. }
  20956. #endif
  20957. // WebSocket Tests
  20958. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20959. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20960. // defining the meaning of these bits has been negotiated.
  20961. auto make_frame = [](uint8_t first_byte) {
  20962. std::string frame;
  20963. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20964. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20965. frame += "Hello";
  20966. return frame;
  20967. };
  20968. // RSV1 set (0x40)
  20969. {
  20970. detail::BufferStream strm;
  20971. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20972. ws::Opcode opcode;
  20973. std::string payload;
  20974. bool fin;
  20975. EXPECT_EQ(
  20976. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20977. ws::impl::FrameRead::Fail);
  20978. }
  20979. // RSV2 set (0x20)
  20980. {
  20981. detail::BufferStream strm;
  20982. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20983. ws::Opcode opcode;
  20984. std::string payload;
  20985. bool fin;
  20986. EXPECT_EQ(
  20987. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20988. ws::impl::FrameRead::Fail);
  20989. }
  20990. // RSV3 set (0x10)
  20991. {
  20992. detail::BufferStream strm;
  20993. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20994. ws::Opcode opcode;
  20995. std::string payload;
  20996. bool fin;
  20997. EXPECT_EQ(
  20998. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20999. ws::impl::FrameRead::Fail);
  21000. }
  21001. // No RSV bits set - should succeed
  21002. {
  21003. detail::BufferStream strm;
  21004. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21005. ws::Opcode opcode;
  21006. std::string payload;
  21007. bool fin;
  21008. EXPECT_EQ(
  21009. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21010. ws::impl::FrameRead::Ok);
  21011. EXPECT_EQ(ws::Opcode::Text, opcode);
  21012. EXPECT_EQ("Hello", payload);
  21013. EXPECT_TRUE(fin);
  21014. }
  21015. }
  21016. TEST(WebSocketTest, ControlFrameValidation) {
  21017. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21018. // payload length <= 125.
  21019. // Ping with FIN=0 - must be rejected
  21020. {
  21021. detail::BufferStream strm;
  21022. std::string frame;
  21023. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21024. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21025. strm.write(frame.data(), frame.size());
  21026. ws::Opcode opcode;
  21027. std::string payload;
  21028. bool fin;
  21029. EXPECT_EQ(
  21030. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21031. ws::impl::FrameRead::Fail);
  21032. }
  21033. // Close with FIN=0 - must be rejected
  21034. {
  21035. detail::BufferStream strm;
  21036. std::string frame;
  21037. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21038. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21039. strm.write(frame.data(), frame.size());
  21040. ws::Opcode opcode;
  21041. std::string payload;
  21042. bool fin;
  21043. EXPECT_EQ(
  21044. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21045. ws::impl::FrameRead::Fail);
  21046. }
  21047. // Ping with payload_len=126 (extended length) - must be rejected
  21048. {
  21049. detail::BufferStream strm;
  21050. std::string frame;
  21051. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21052. frame += static_cast<char>(126); // payload_len=126 (>125)
  21053. frame += static_cast<char>(0x00); // extended length high byte
  21054. frame += static_cast<char>(126); // extended length low byte
  21055. frame += std::string(126, 'x');
  21056. strm.write(frame.data(), frame.size());
  21057. ws::Opcode opcode;
  21058. std::string payload;
  21059. bool fin;
  21060. EXPECT_EQ(
  21061. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21062. ws::impl::FrameRead::Fail);
  21063. }
  21064. // Ping with FIN=1 and payload_len=125 - should succeed
  21065. {
  21066. detail::BufferStream strm;
  21067. std::string frame;
  21068. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21069. frame += static_cast<char>(125); // payload_len=125
  21070. frame += std::string(125, 'x');
  21071. strm.write(frame.data(), frame.size());
  21072. ws::Opcode opcode;
  21073. std::string payload;
  21074. bool fin;
  21075. EXPECT_EQ(
  21076. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21077. ws::impl::FrameRead::Ok);
  21078. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21079. EXPECT_EQ(125u, payload.size());
  21080. EXPECT_TRUE(fin);
  21081. }
  21082. }
  21083. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21084. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21085. // length MUST be 0.
  21086. // MSB set - must be rejected
  21087. {
  21088. detail::BufferStream strm;
  21089. std::string frame;
  21090. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21091. frame += static_cast<char>(127); // 64-bit extended length
  21092. frame += static_cast<char>(0x80); // MSB set (invalid)
  21093. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21094. strm.write(frame.data(), frame.size());
  21095. ws::Opcode opcode;
  21096. std::string payload;
  21097. bool fin;
  21098. EXPECT_EQ(
  21099. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21100. ws::impl::FrameRead::Fail);
  21101. }
  21102. // MSB clear - should pass length parsing (will be rejected by max_len,
  21103. // but that's a different check; use a small length to verify)
  21104. {
  21105. detail::BufferStream strm;
  21106. std::string frame;
  21107. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21108. frame += static_cast<char>(127); // 64-bit extended length
  21109. frame += std::string(7, '\0'); // high bytes = 0
  21110. frame += static_cast<char>(0x03); // length = 3
  21111. frame += "abc";
  21112. strm.write(frame.data(), frame.size());
  21113. ws::Opcode opcode;
  21114. std::string payload;
  21115. bool fin;
  21116. EXPECT_EQ(
  21117. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21118. ws::impl::FrameRead::Ok);
  21119. EXPECT_EQ(ws::Opcode::Text, opcode);
  21120. EXPECT_EQ("abc", payload);
  21121. }
  21122. }
  21123. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21124. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21125. // Valid UTF-8
  21126. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21127. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21128. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21129. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21130. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21131. // Invalid UTF-8
  21132. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21133. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21134. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21135. EXPECT_FALSE(
  21136. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21137. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21138. }
  21139. TEST(WebSocketTest, ConnectAndDisconnect) {
  21140. Server svr;
  21141. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21142. std::string msg;
  21143. while (ws.read(msg)) {}
  21144. });
  21145. auto port = svr.bind_to_any_port(HOST);
  21146. std::thread t([&]() { svr.listen_after_bind(); });
  21147. svr.wait_until_ready();
  21148. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21149. auto res = client.connect();
  21150. ASSERT_TRUE(res);
  21151. EXPECT_EQ(Error::Success, res.error());
  21152. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21153. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21154. EXPECT_TRUE(client.is_open());
  21155. client.close();
  21156. EXPECT_FALSE(client.is_open());
  21157. svr.stop();
  21158. t.join();
  21159. }
  21160. TEST(WebSocketTest, ValidURL) {
  21161. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21162. EXPECT_TRUE(ws1.is_valid());
  21163. ws::WebSocketClient ws2("ws://example.com/path");
  21164. EXPECT_TRUE(ws2.is_valid());
  21165. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21166. EXPECT_TRUE(ws3.is_valid());
  21167. #ifdef CPPHTTPLIB_SSL_ENABLED
  21168. ws::WebSocketClient wss1("wss://example.com/path");
  21169. EXPECT_TRUE(wss1.is_valid());
  21170. ws::WebSocketClient wss2("wss://example.com:443/path");
  21171. EXPECT_TRUE(wss2.is_valid());
  21172. #endif
  21173. }
  21174. TEST(WebSocketTest, InvalidURL) {
  21175. // No scheme
  21176. ws::WebSocketClient ws1("localhost:8080/path");
  21177. EXPECT_FALSE(ws1.is_valid());
  21178. // No path
  21179. ws::WebSocketClient ws2("ws://localhost:8080");
  21180. EXPECT_FALSE(ws2.is_valid());
  21181. // Empty string
  21182. ws::WebSocketClient ws3("");
  21183. EXPECT_FALSE(ws3.is_valid());
  21184. // Missing host
  21185. ws::WebSocketClient ws4("ws://:8080/path");
  21186. EXPECT_FALSE(ws4.is_valid());
  21187. // Port number overflow — should not crash
  21188. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21189. EXPECT_FALSE(ws5.is_valid());
  21190. // Port out of range
  21191. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21192. EXPECT_FALSE(ws6.is_valid());
  21193. }
  21194. TEST(WebSocketTest, UnsupportedScheme) {
  21195. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21196. ws::WebSocketClient ws1("http://localhost:8080/path");
  21197. EXPECT_FALSE(ws1.is_valid());
  21198. ws::WebSocketClient ws2("https://localhost:8080/path");
  21199. EXPECT_FALSE(ws2.is_valid());
  21200. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21201. EXPECT_FALSE(ws3.is_valid());
  21202. #else
  21203. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21204. std::invalid_argument);
  21205. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21206. std::invalid_argument);
  21207. #endif
  21208. }
  21209. TEST(WebSocketTest, ConnectWhenInvalid) {
  21210. ws::WebSocketClient ws("not a valid url");
  21211. EXPECT_FALSE(ws.is_valid());
  21212. auto res = ws.connect();
  21213. EXPECT_FALSE(res);
  21214. EXPECT_EQ(Error::Connection, res.error());
  21215. EXPECT_EQ(-1, res.status());
  21216. }
  21217. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21218. // Grab a port that is free, then close it again so nothing listens there
  21219. Server svr;
  21220. auto port = svr.bind_to_any_port(HOST);
  21221. svr.stop();
  21222. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21223. auto res = client.connect();
  21224. ASSERT_FALSE(res);
  21225. EXPECT_EQ(Error::Connection, res.error());
  21226. EXPECT_EQ(-1, res.status());
  21227. }
  21228. TEST(WebSocketTest, DefaultPort) {
  21229. ws::WebSocketClient ws1("ws://example.com/path");
  21230. EXPECT_TRUE(ws1.is_valid());
  21231. // ws:// defaults to port 80 (verified by successful parse)
  21232. #ifdef CPPHTTPLIB_SSL_ENABLED
  21233. ws::WebSocketClient ws2("wss://example.com/path");
  21234. EXPECT_TRUE(ws2.is_valid());
  21235. // wss:// defaults to port 443 (verified by successful parse)
  21236. #endif
  21237. }
  21238. TEST(WebSocketTest, IPv6LiteralAddress) {
  21239. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21240. EXPECT_TRUE(ws1.is_valid());
  21241. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21242. EXPECT_TRUE(ws2.is_valid());
  21243. }
  21244. TEST(WebSocketTest, ComplexPath) {
  21245. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21246. EXPECT_TRUE(ws1.is_valid());
  21247. ws::WebSocketClient ws2("ws://localhost:8080/");
  21248. EXPECT_TRUE(ws2.is_valid());
  21249. }
  21250. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21251. Server svr;
  21252. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21253. std::string msg;
  21254. while (ws.read(msg)) {}
  21255. });
  21256. auto port = svr.bind_to_any_port(HOST);
  21257. std::thread t([&]() { svr.listen_after_bind(); });
  21258. svr.wait_until_ready();
  21259. auto another_host = "example.com";
  21260. auto wrong_ip = "192.0.2.1";
  21261. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21262. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21263. ASSERT_TRUE(client.connect());
  21264. EXPECT_TRUE(client.is_open());
  21265. client.close();
  21266. svr.stop();
  21267. t.join();
  21268. }
  21269. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21270. Server svr;
  21271. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21272. std::string msg;
  21273. while (ws.read(msg)) {}
  21274. });
  21275. auto port = svr.bind_to_any_port(HOST);
  21276. std::thread t([&]() { svr.listen_after_bind(); });
  21277. svr.wait_until_ready();
  21278. auto wrong_ip = "192.0.2.1";
  21279. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21280. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21281. client.set_connection_timeout(1);
  21282. client.set_read_timeout(1);
  21283. client.set_write_timeout(1);
  21284. EXPECT_FALSE(client.connect());
  21285. EXPECT_FALSE(client.is_open());
  21286. svr.stop();
  21287. t.join();
  21288. }
  21289. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21290. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21291. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21292. // (RFC 6761) is only a map key and the Host header value.
  21293. auto host = "target.invalid";
  21294. Server svr;
  21295. std::string received_host;
  21296. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21297. received_host = req.get_header_value("Host");
  21298. std::string msg;
  21299. while (ws.read(msg)) {}
  21300. });
  21301. auto port = svr.bind_to_any_port(HOST);
  21302. std::thread t([&]() { svr.listen_after_bind(); });
  21303. // ASSERT_* below returns from the test body, which would leave t joinable
  21304. // and make ~thread call std::terminate.
  21305. auto se = detail::scope_exit([&] {
  21306. svr.stop();
  21307. if (t.joinable()) { t.join(); }
  21308. });
  21309. svr.wait_until_ready();
  21310. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21311. std::to_string(port) + "/ws");
  21312. client.set_hostname_addr_map({{host, HOST}});
  21313. ASSERT_TRUE(client.connect());
  21314. EXPECT_TRUE(client.is_open());
  21315. client.close();
  21316. svr.stop();
  21317. t.join();
  21318. // The mapping only redirects the connection; the identity stays host_.
  21319. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21320. }
  21321. class WebSocketIntegrationTest : public ::testing::Test {
  21322. protected:
  21323. void SetUp() override {
  21324. server_ = httplib::detail::make_unique<Server>();
  21325. setup_server();
  21326. start_server();
  21327. }
  21328. void TearDown() override {
  21329. server_->stop();
  21330. if (server_thread_.joinable()) { server_thread_.join(); }
  21331. }
  21332. void setup_server() {
  21333. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21334. std::string msg;
  21335. ws::ReadResult ret;
  21336. while ((ret = ws.read(msg))) {
  21337. if (ret == ws::Binary) {
  21338. ws.send(msg.data(), msg.size());
  21339. } else {
  21340. ws.send(msg);
  21341. }
  21342. }
  21343. });
  21344. server_->WebSocket("/ws-echo-string",
  21345. [](const Request &, ws::WebSocket &ws) {
  21346. std::string msg;
  21347. while (ws.read(msg)) {
  21348. ws.send("echo: " + msg);
  21349. }
  21350. });
  21351. server_->WebSocket(
  21352. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21353. // Echo back request metadata
  21354. ws.send("path:" + req.path);
  21355. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21356. std::string msg;
  21357. while (ws.read(msg)) {}
  21358. });
  21359. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21360. std::string msg;
  21361. ws.read(msg); // wait for a message
  21362. ws.close();
  21363. });
  21364. server_->WebSocket("/ws-close-status",
  21365. [](const Request &, ws::WebSocket &ws) {
  21366. std::string msg;
  21367. ws.read(msg); // wait for a message
  21368. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21369. });
  21370. server_->WebSocket(
  21371. "/ws-subprotocol",
  21372. [](const Request &, ws::WebSocket &ws) {
  21373. std::string msg;
  21374. while (ws.read(msg)) {
  21375. ws.send(msg);
  21376. }
  21377. },
  21378. [](const std::vector<std::string> &protocols) -> std::string {
  21379. for (const auto &p : protocols) {
  21380. if (p == "graphql-ws") { return p; }
  21381. }
  21382. return "";
  21383. });
  21384. server_->WebSocket(
  21385. "/ws-subprotocol-unoffered",
  21386. [](const Request &, ws::WebSocket &ws) {
  21387. std::string msg;
  21388. while (ws.read(msg)) {
  21389. ws.send(msg);
  21390. }
  21391. },
  21392. [](const std::vector<std::string> &) -> std::string {
  21393. return "admin";
  21394. });
  21395. }
  21396. void start_server() {
  21397. port_ = server_->bind_to_any_port(HOST);
  21398. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21399. server_->wait_until_ready();
  21400. }
  21401. std::unique_ptr<Server> server_;
  21402. std::thread server_thread_;
  21403. int port_ = 0;
  21404. };
  21405. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21406. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21407. "/ws-echo");
  21408. ASSERT_TRUE(client.connect());
  21409. ASSERT_TRUE(client.is_open());
  21410. ASSERT_TRUE(client.send("Hello WebSocket"));
  21411. std::string msg;
  21412. EXPECT_EQ(ws::Text, client.read(msg));
  21413. EXPECT_EQ("Hello WebSocket", msg);
  21414. client.close();
  21415. }
  21416. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21417. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21418. "/ws-echo");
  21419. ASSERT_TRUE(client.connect());
  21420. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21421. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21422. std::string msg;
  21423. EXPECT_EQ(ws::Binary, client.read(msg));
  21424. EXPECT_EQ(binary_data, msg);
  21425. client.close();
  21426. }
  21427. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21428. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21429. "/ws-echo");
  21430. ASSERT_TRUE(client.connect());
  21431. for (int i = 0; i < 10; i++) {
  21432. auto text = "message " + std::to_string(i);
  21433. ASSERT_TRUE(client.send(text));
  21434. std::string msg;
  21435. ASSERT_TRUE(client.read(msg));
  21436. EXPECT_EQ(text, msg);
  21437. }
  21438. client.close();
  21439. }
  21440. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21441. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21442. "/ws-close");
  21443. ASSERT_TRUE(client.connect());
  21444. // Send a message to trigger the server to close
  21445. ASSERT_TRUE(client.send("trigger close"));
  21446. // The server will close, so read should return false
  21447. std::string msg;
  21448. EXPECT_FALSE(client.read(msg));
  21449. EXPECT_FALSE(client.is_open());
  21450. }
  21451. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21452. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21453. "/ws-echo");
  21454. ASSERT_TRUE(client.connect());
  21455. // 128KB message
  21456. std::string large_data(128 * 1024, 'X');
  21457. ASSERT_TRUE(client.send(large_data));
  21458. std::string msg;
  21459. ASSERT_TRUE(client.read(msg));
  21460. EXPECT_EQ(large_data, msg);
  21461. client.close();
  21462. }
  21463. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21464. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21465. "/ws-echo");
  21466. ASSERT_TRUE(client.connect());
  21467. const int num_threads = 4;
  21468. std::vector<std::thread> threads;
  21469. std::atomic<int> send_count{0};
  21470. for (int t = 0; t < num_threads; t++) {
  21471. threads.emplace_back([&client, &send_count, t]() {
  21472. for (int i = 0; i < 5; i++) {
  21473. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21474. if (client.send(text)) { send_count++; }
  21475. }
  21476. });
  21477. }
  21478. for (auto &th : threads) {
  21479. th.join();
  21480. }
  21481. int received = 0;
  21482. std::string msg;
  21483. while (received < send_count.load()) {
  21484. if (!client.read(msg)) { break; }
  21485. received++;
  21486. }
  21487. EXPECT_EQ(send_count.load(), received);
  21488. client.close();
  21489. }
  21490. TEST_F(WebSocketIntegrationTest, ReadString) {
  21491. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21492. "/ws-echo-string");
  21493. ASSERT_TRUE(client.connect());
  21494. ASSERT_TRUE(client.send("hello"));
  21495. std::string msg;
  21496. ASSERT_TRUE(client.read(msg));
  21497. EXPECT_EQ("echo: hello", msg);
  21498. ASSERT_TRUE(client.send("world"));
  21499. ASSERT_TRUE(client.read(msg));
  21500. EXPECT_EQ("echo: world", msg);
  21501. client.close();
  21502. }
  21503. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21504. Headers headers = {{"X-Test-Header", "test-value"}};
  21505. ws::WebSocketClient client(
  21506. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21507. ASSERT_TRUE(client.connect());
  21508. std::string msg;
  21509. ASSERT_TRUE(client.read(msg));
  21510. EXPECT_EQ("path:/ws-request-info", msg);
  21511. ASSERT_TRUE(client.read(msg));
  21512. EXPECT_EQ("header:test-value", msg);
  21513. client.close();
  21514. }
  21515. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21516. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21517. "/ws-echo");
  21518. client.set_read_timeout(1, 0); // 1 second
  21519. ASSERT_TRUE(client.connect());
  21520. // Don't send anything — server echo handler waits for a message, so read()
  21521. // should time out. The connection survives it: nothing was consumed.
  21522. std::string msg;
  21523. EXPECT_EQ(client.read(msg), ws::Timeout);
  21524. EXPECT_TRUE(client.is_open());
  21525. // And it is still usable afterwards.
  21526. EXPECT_TRUE(client.send("after timeout"));
  21527. EXPECT_EQ(client.read(msg), ws::Text);
  21528. EXPECT_EQ(msg, "after timeout");
  21529. }
  21530. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21531. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21532. "/ws-echo");
  21533. client.set_read_timeout(1, 0);
  21534. ASSERT_TRUE(client.connect());
  21535. ASSERT_TRUE(client.send("first"));
  21536. std::string msg;
  21537. ASSERT_EQ(client.read(msg), ws::Text);
  21538. ASSERT_EQ(msg, "first");
  21539. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21540. // not be used with a read timeout: it would reprocess the previous message.
  21541. EXPECT_EQ(client.read(msg), ws::Timeout);
  21542. EXPECT_EQ(msg, "first");
  21543. }
  21544. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21545. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21546. "/ws-echo");
  21547. ASSERT_TRUE(client.connect());
  21548. // Setting it once the connection is open reaches the live stream, not just
  21549. // the seed for the next connect().
  21550. client.set_read_timeout(1, 0);
  21551. std::string msg;
  21552. EXPECT_EQ(client.read(msg), ws::Timeout);
  21553. EXPECT_TRUE(client.is_open());
  21554. }
  21555. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21556. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21557. "/ws-echo");
  21558. client.set_read_timeout(5, 0);
  21559. ASSERT_TRUE(client.connect());
  21560. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21561. // The server should reject it and close the connection.
  21562. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21563. client.send(oversized);
  21564. // The server's read() should have failed due to payload limit,
  21565. // so our read() should return false (connection closed).
  21566. std::string msg;
  21567. EXPECT_FALSE(client.read(msg));
  21568. }
  21569. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21570. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21571. "/ws-echo");
  21572. client.set_read_timeout(10, 0);
  21573. ASSERT_TRUE(client.connect());
  21574. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21575. // This should succeed.
  21576. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21577. ASSERT_TRUE(client.send(at_limit));
  21578. std::string msg;
  21579. ASSERT_TRUE(client.read(msg));
  21580. EXPECT_EQ(at_limit.size(), msg.size());
  21581. client.close();
  21582. }
  21583. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21584. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21585. "/nonexistent");
  21586. auto res = client.connect();
  21587. EXPECT_FALSE(res);
  21588. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21589. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21590. EXPECT_FALSE(client.is_open());
  21591. }
  21592. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21593. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21594. "/ws-echo");
  21595. ASSERT_TRUE(client.connect());
  21596. ASSERT_TRUE(client.send(""));
  21597. std::string msg;
  21598. EXPECT_EQ(ws::Text, client.read(msg));
  21599. EXPECT_EQ("", msg);
  21600. client.close();
  21601. }
  21602. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21603. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21604. "/ws-echo");
  21605. // First connection
  21606. ASSERT_TRUE(client.connect());
  21607. ASSERT_TRUE(client.send("first"));
  21608. std::string msg;
  21609. ASSERT_TRUE(client.read(msg));
  21610. EXPECT_EQ("first", msg);
  21611. client.close();
  21612. EXPECT_FALSE(client.is_open());
  21613. // Reconnect using the same client object
  21614. ASSERT_TRUE(client.connect());
  21615. ASSERT_TRUE(client.is_open());
  21616. ASSERT_TRUE(client.send("second"));
  21617. ASSERT_TRUE(client.read(msg));
  21618. EXPECT_EQ("second", msg);
  21619. client.close();
  21620. }
  21621. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21622. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21623. "/ws-close-status");
  21624. ASSERT_TRUE(client.connect());
  21625. // Trigger the server to close with GoingAway status
  21626. ASSERT_TRUE(client.send("trigger"));
  21627. // read() should return false after receiving the close frame
  21628. std::string msg;
  21629. EXPECT_FALSE(client.read(msg));
  21630. EXPECT_FALSE(client.is_open());
  21631. }
  21632. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21633. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21634. "/ws-echo");
  21635. ASSERT_TRUE(client.connect());
  21636. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21637. EXPECT_FALSE(client.is_open());
  21638. }
  21639. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21640. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21641. ws::WebSocketClient client(
  21642. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21643. ASSERT_TRUE(client.connect());
  21644. // Server should have selected graphql-ws
  21645. EXPECT_EQ("graphql-ws", client.subprotocol());
  21646. client.close();
  21647. }
  21648. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21649. Headers headers;
  21650. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21651. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21652. ws::WebSocketClient client(
  21653. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21654. ASSERT_TRUE(client.connect());
  21655. // The offer on the second field line counts too, so graphql-ws is selected
  21656. EXPECT_EQ("graphql-ws", client.subprotocol());
  21657. client.close();
  21658. }
  21659. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21660. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21661. ws::WebSocketClient client(
  21662. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21663. ASSERT_TRUE(client.connect());
  21664. // Server should not have selected any subprotocol
  21665. EXPECT_TRUE(client.subprotocol().empty());
  21666. client.close();
  21667. }
  21668. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21669. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21670. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21671. "/ws-subprotocol-unoffered",
  21672. headers);
  21673. ASSERT_TRUE(client.connect());
  21674. EXPECT_TRUE(client.subprotocol().empty());
  21675. client.close();
  21676. }
  21677. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21678. // Connect without requesting any subprotocol
  21679. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21680. "/ws-subprotocol");
  21681. ASSERT_TRUE(client.connect());
  21682. EXPECT_TRUE(client.subprotocol().empty());
  21683. client.close();
  21684. }
  21685. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21686. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21687. "/ws-echo");
  21688. client.set_tcp_nodelay(true);
  21689. client.set_connection_timeout(3, 0);
  21690. bool socket_options_called = false;
  21691. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21692. ASSERT_TRUE(client.connect());
  21693. ASSERT_TRUE(client.is_open());
  21694. EXPECT_TRUE(socket_options_called);
  21695. ASSERT_TRUE(client.send("hello"));
  21696. std::string msg;
  21697. auto result = client.read(msg);
  21698. EXPECT_EQ(result, ws::ReadResult::Text);
  21699. EXPECT_EQ(msg, "hello");
  21700. client.close();
  21701. }
  21702. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21703. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21704. "/ws-echo");
  21705. client.set_connection_timeout(std::chrono::seconds(3));
  21706. client.set_write_timeout(std::chrono::seconds(3));
  21707. // A sub-second remainder exercises the seconds/microseconds split.
  21708. client.set_read_timeout(std::chrono::milliseconds(1500));
  21709. ASSERT_TRUE(client.connect());
  21710. auto start = std::chrono::steady_clock::now();
  21711. std::string msg;
  21712. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21713. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21714. std::chrono::steady_clock::now() - start)
  21715. .count();
  21716. // Above 1s so that dropping the microseconds half of the split fails here.
  21717. // Ignoring the setter altogether would not reach this line at all: a client
  21718. // waits forever by default.
  21719. EXPECT_GE(elapsed, 1400);
  21720. EXPECT_LT(elapsed, 30000);
  21721. }
  21722. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21723. Server svr;
  21724. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21725. if (!req.has_header("Authorization")) {
  21726. res.status = StatusCode::Unauthorized_401;
  21727. res.set_content("Unauthorized", "text/plain");
  21728. return Server::HandlerResponse::Handled;
  21729. }
  21730. return Server::HandlerResponse::Unhandled;
  21731. });
  21732. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21733. std::string msg;
  21734. while (ws.read(msg)) {
  21735. ws.send(msg);
  21736. }
  21737. });
  21738. auto port = svr.bind_to_any_port("localhost");
  21739. std::thread t([&]() { svr.listen_after_bind(); });
  21740. svr.wait_until_ready();
  21741. // Without Authorization header - should be rejected before upgrade
  21742. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21743. EXPECT_FALSE(client1.connect());
  21744. // The rejection is framed like any other HTTP response
  21745. {
  21746. Client cli("localhost", port);
  21747. Headers headers = {{"Upgrade", "websocket"},
  21748. {"Connection", "Upgrade"},
  21749. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21750. {"Sec-WebSocket-Version", "13"}};
  21751. auto res = cli.Get("/ws", headers);
  21752. ASSERT_TRUE(res);
  21753. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21754. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21755. EXPECT_EQ("Unauthorized", res->body);
  21756. }
  21757. // With Authorization header - should succeed
  21758. Headers headers = {{"Authorization", "Bearer token123"}};
  21759. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21760. headers);
  21761. ASSERT_TRUE(client2.connect());
  21762. ASSERT_TRUE(client2.send("hello"));
  21763. std::string msg;
  21764. ASSERT_TRUE(client2.read(msg));
  21765. EXPECT_EQ("hello", msg);
  21766. client2.close();
  21767. svr.stop();
  21768. t.join();
  21769. }
  21770. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21771. Server svr;
  21772. std::atomic<int> pre_request_calls{0};
  21773. std::atomic<bool> route_matched{false};
  21774. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21775. pre_request_calls++;
  21776. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21777. if (req.get_header_value("Authorization") != "Bearer token123") {
  21778. res.status = StatusCode::Unauthorized_401;
  21779. res.set_content("Unauthorized", "text/plain");
  21780. return Server::HandlerResponse::Handled;
  21781. }
  21782. return Server::HandlerResponse::Unhandled;
  21783. });
  21784. std::atomic<bool> handler_called{false};
  21785. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21786. handler_called = true;
  21787. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21788. });
  21789. auto port = svr.bind_to_any_port("localhost");
  21790. std::thread t([&]() { svr.listen_after_bind(); });
  21791. svr.wait_until_ready();
  21792. // Without Authorization header - should be rejected before upgrade
  21793. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21794. "/ws/1");
  21795. EXPECT_FALSE(client1.connect());
  21796. EXPECT_FALSE(handler_called);
  21797. EXPECT_EQ(1, pre_request_calls);
  21798. EXPECT_TRUE(route_matched);
  21799. // The rejection is an ordinary HTTP response, not a protocol switch
  21800. {
  21801. Client cli("localhost", port);
  21802. Headers headers = {{"Upgrade", "websocket"},
  21803. {"Connection", "Upgrade"},
  21804. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21805. {"Sec-WebSocket-Version", "13"}};
  21806. auto res = cli.Get("/ws/1", headers);
  21807. ASSERT_TRUE(res);
  21808. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21809. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21810. EXPECT_EQ("Unauthorized", res->body);
  21811. }
  21812. EXPECT_FALSE(handler_called);
  21813. // With Authorization header - should succeed
  21814. Headers headers = {{"Authorization", "Bearer token123"}};
  21815. ws::WebSocketClient client2(
  21816. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21817. ASSERT_TRUE(client2.connect());
  21818. std::string msg;
  21819. ASSERT_TRUE(client2.read(msg));
  21820. EXPECT_EQ("/ws/:id 2", msg);
  21821. EXPECT_TRUE(handler_called);
  21822. client2.close();
  21823. svr.stop();
  21824. t.join();
  21825. }
  21826. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21827. Server svr;
  21828. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21829. // A read timeout is how a handler gets control back. Without it, a handler
  21830. // parked in read() can never write on the connection it is reading.
  21831. ws.set_read_timeout(std::chrono::milliseconds(100));
  21832. std::string msg;
  21833. while (ws.is_open()) {
  21834. auto r = ws.read(msg);
  21835. if (r == httplib::ws::Timeout) {
  21836. ws.send("tick");
  21837. continue;
  21838. }
  21839. if (r == httplib::ws::Fail) { break; }
  21840. ws.send(msg);
  21841. }
  21842. });
  21843. auto port = svr.bind_to_any_port("localhost");
  21844. std::thread t([&]() { svr.listen_after_bind(); });
  21845. svr.wait_until_ready();
  21846. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21847. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21848. ASSERT_TRUE(client.connect());
  21849. // The client sends nothing, so anything it receives came out of the
  21850. // handler's timeout path.
  21851. std::string msg;
  21852. ASSERT_EQ(client.read(msg), ws::Text);
  21853. EXPECT_EQ("tick", msg);
  21854. client.close();
  21855. svr.stop();
  21856. t.join();
  21857. }
  21858. // Stream::read may return fewer bytes than asked for. This is that contract at
  21859. // its worst -- one byte per call -- which is what a frame header straddling a
  21860. // read buffer's boundary looks like to the frame parser.
  21861. class WsByteAtATimeStream : public Stream {
  21862. public:
  21863. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21864. bool is_readable() const override { return true; }
  21865. bool wait_readable() const override { return true; }
  21866. bool wait_writable() const override { return true; }
  21867. ssize_t read(char *ptr, size_t size) override {
  21868. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21869. *ptr = data_[pos_++];
  21870. return 1;
  21871. }
  21872. ssize_t write(const char *, size_t size) override {
  21873. return static_cast<ssize_t>(size);
  21874. }
  21875. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21876. ip = "127.0.0.1";
  21877. port = 0;
  21878. }
  21879. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21880. ip = "127.0.0.1";
  21881. port = 0;
  21882. }
  21883. socket_t socket() const override { return INVALID_SOCKET; }
  21884. time_t duration() const override { return 0; }
  21885. private:
  21886. std::string data_;
  21887. size_t pos_ = 0;
  21888. };
  21889. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21890. // The payload uses the 16-bit extended length, so the header, the length
  21891. // and the mask key are all multi-byte fields here. Each used to be read
  21892. // with a single read() call, which fails as soon as one is split. The
  21893. // payload is also a little over one read chunk, so it is read in two.
  21894. std::string body;
  21895. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21896. body += static_cast<char>(i % 251);
  21897. }
  21898. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21899. std::string frame;
  21900. frame += static_cast<char>(0x81); // FIN + Text
  21901. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21902. frame += static_cast<char>(body.size() >> 8);
  21903. frame += static_cast<char>(body.size() & 0xff);
  21904. for (size_t i = 0; i < 4; i++) {
  21905. frame += static_cast<char>(mask[i]);
  21906. }
  21907. for (size_t i = 0; i < body.size(); i++) {
  21908. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21909. }
  21910. WsByteAtATimeStream strm(frame);
  21911. ws::Opcode opcode;
  21912. std::string payload;
  21913. bool fin = false;
  21914. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21915. /*expect_masked=*/true, body.size()),
  21916. ws::impl::FrameRead::Ok);
  21917. EXPECT_TRUE(fin);
  21918. EXPECT_EQ(opcode, ws::Opcode::Text);
  21919. EXPECT_EQ(payload, body);
  21920. }
  21921. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  21922. std::string body(2000, 'x');
  21923. std::string frame;
  21924. frame += static_cast<char>(0x82); // FIN + Binary
  21925. frame += static_cast<char>(126); // 16-bit length follows
  21926. frame += static_cast<char>(body.size() >> 8);
  21927. frame += static_cast<char>(body.size() & 0xff);
  21928. frame += body;
  21929. detail::BufferStream strm;
  21930. strm.write(frame.data(), frame.size());
  21931. ws::Opcode opcode;
  21932. std::string payload;
  21933. bool fin;
  21934. EXPECT_EQ(
  21935. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  21936. ws::impl::FrameRead::Ok);
  21937. EXPECT_EQ(body, payload);
  21938. }
  21939. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21940. // The header announces the largest payload allowed, and only 3 bytes of it
  21941. // ever arrive.
  21942. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21943. std::string frame;
  21944. frame += static_cast<char>(0x82); // FIN + Binary
  21945. frame += static_cast<char>(127); // 64-bit length follows
  21946. for (int shift = 56; shift >= 0; shift -= 8) {
  21947. frame += static_cast<char>((len >> shift) & 0xff);
  21948. }
  21949. frame += "abc";
  21950. detail::BufferStream strm;
  21951. strm.write(frame.data(), frame.size());
  21952. ws::Opcode opcode;
  21953. std::string payload;
  21954. bool fin;
  21955. EXPECT_EQ(
  21956. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21957. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21958. ws::impl::FrameRead::Fail);
  21959. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21960. }
  21961. TEST(WebSocketTest, QueryStringInHandshake) {
  21962. Server svr;
  21963. std::mutex mtx;
  21964. std::string received_target;
  21965. std::string received_token;
  21966. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21967. {
  21968. std::lock_guard<std::mutex> lock(mtx);
  21969. received_target = req.target;
  21970. if (req.has_param("token")) {
  21971. received_token = req.get_param_value("token");
  21972. }
  21973. }
  21974. std::string msg;
  21975. while (ws.read(msg)) {
  21976. ws.send(msg);
  21977. }
  21978. });
  21979. auto port = svr.bind_to_any_port("localhost");
  21980. std::thread t([&]() { svr.listen_after_bind(); });
  21981. svr.wait_until_ready();
  21982. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21983. "/ws?token=ABC&session=123");
  21984. ASSERT_TRUE(client.connect());
  21985. // Round-trip ensures the handler has run and captured the request.
  21986. ASSERT_TRUE(client.send("hello"));
  21987. std::string msg;
  21988. ASSERT_TRUE(client.read(msg));
  21989. EXPECT_EQ("hello", msg);
  21990. client.close();
  21991. {
  21992. std::lock_guard<std::mutex> lock(mtx);
  21993. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21994. EXPECT_EQ("ABC", received_token);
  21995. }
  21996. svr.stop();
  21997. t.join();
  21998. }
  21999. // Run a handshake against a throwaway server and hand the request the server
  22000. // received back to the caller, so tests can assert on the headers the client
  22001. // actually put on the wire.
  22002. static void capture_websocket_handshake_request(
  22003. const Headers &client_headers,
  22004. std::function<void(const Request &, int port)> verify) {
  22005. Server svr;
  22006. std::mutex mtx;
  22007. Request received;
  22008. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22009. {
  22010. std::lock_guard<std::mutex> lock(mtx);
  22011. received = req;
  22012. }
  22013. std::string msg;
  22014. while (ws.read(msg)) {
  22015. ws.send(msg);
  22016. }
  22017. });
  22018. auto port = svr.bind_to_any_port("localhost");
  22019. std::thread t([&]() { svr.listen_after_bind(); });
  22020. auto se = detail::scope_exit([&] {
  22021. svr.stop();
  22022. t.join();
  22023. });
  22024. svr.wait_until_ready();
  22025. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22026. client_headers);
  22027. ASSERT_TRUE(client.connect());
  22028. ASSERT_TRUE(client.send("hello"));
  22029. std::string msg;
  22030. ASSERT_TRUE(client.read(msg));
  22031. client.close();
  22032. {
  22033. std::lock_guard<std::mutex> lock(mtx);
  22034. verify(received, port);
  22035. }
  22036. }
  22037. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22038. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22039. // Non-default port must be present in the Host header. Default ports
  22040. // (80/443) are omitted; that logic is covered by
  22041. // MakeHostAndPortStringTest.
  22042. EXPECT_EQ("localhost:" + std::to_string(port),
  22043. req.get_header_value("Host"));
  22044. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22045. req.get_header_value("User-Agent"));
  22046. EXPECT_FALSE(req.has_header("Accept"));
  22047. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22048. EXPECT_FALSE(req.has_header("Content-Length"));
  22049. });
  22050. }
  22051. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22052. capture_websocket_handshake_request(
  22053. {{"Host", "example.com"},
  22054. {"User-Agent", "custom-agent"},
  22055. {"X-Custom", "value"}},
  22056. [](const Request &req, int) {
  22057. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22058. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22059. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22060. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22061. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22062. });
  22063. }
  22064. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22065. capture_websocket_handshake_request(
  22066. {{"Upgrade", "bogus"},
  22067. {"Connection", "close"},
  22068. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22069. {"Sec-WebSocket-Version", "8"}},
  22070. [](const Request &req, int) {
  22071. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22072. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22073. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22074. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22075. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22076. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22077. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22078. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22079. req.get_header_value("Sec-WebSocket-Key"));
  22080. });
  22081. }
  22082. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22083. // A header the client refuses to send must abort the handshake before any
  22084. // part of it reaches the wire; a lone request line would otherwise sit in
  22085. // the peer's buffer as a truncated request.
  22086. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22087. ASSERT_NE(INVALID_SOCKET, srv);
  22088. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22089. sockaddr_in addr{};
  22090. addr.sin_family = AF_INET;
  22091. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22092. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22093. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22094. ASSERT_EQ(0, ::listen(srv, 1));
  22095. sockaddr_in bound{};
  22096. socklen_t bound_len = sizeof(bound);
  22097. ASSERT_EQ(
  22098. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22099. auto port = ntohs(bound.sin_port);
  22100. ssize_t received = -1;
  22101. std::thread t([&] {
  22102. // Bound every blocking call so a regression fails the test with a bad
  22103. // value instead of hanging the suite.
  22104. fd_set rfds;
  22105. FD_ZERO(&rfds);
  22106. FD_SET(srv, &rfds);
  22107. timeval tv{5, 0};
  22108. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22109. 0) {
  22110. return;
  22111. }
  22112. sockaddr_in cli_addr{};
  22113. socklen_t cli_len = sizeof(cli_addr);
  22114. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22115. if (cli == INVALID_SOCKET) { return; }
  22116. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22117. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22118. char buf[4096];
  22119. received = ::recv(cli, buf, sizeof(buf), 0);
  22120. });
  22121. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22122. // connect() has already shut the socket down by the time it returns false,
  22123. // so the peer sees EOF without waiting for the client to be destroyed.
  22124. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22125. {{"X-Bad", "a\r\nInjected: 1"}});
  22126. EXPECT_FALSE(client.connect());
  22127. t.join();
  22128. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22129. EXPECT_EQ(0, received);
  22130. }
  22131. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22132. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22133. // contains "upgrade" as a substring is a different token and must not
  22134. // start a WebSocket handshake.
  22135. auto make_request = [](const std::vector<std::string> &connection_values) {
  22136. Request req;
  22137. req.method = "GET";
  22138. req.headers.emplace("Upgrade", "websocket");
  22139. for (const auto &value : connection_values) {
  22140. req.headers.emplace("Connection", value);
  22141. }
  22142. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22143. req.headers.emplace("Sec-WebSocket-Version", "13");
  22144. return req;
  22145. };
  22146. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22147. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22148. EXPECT_TRUE(
  22149. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22150. EXPECT_TRUE(
  22151. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22152. EXPECT_TRUE(
  22153. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22154. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22155. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22156. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22157. EXPECT_FALSE(
  22158. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22159. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22160. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22161. }
  22162. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22163. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22164. // asks recipients to match each protocol-name case-insensitively, and RFC
  22165. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22166. // client naming websocket alongside another protocol, or on a second field
  22167. // line, is offering websocket; a value that merely contains "websocket" as a
  22168. // substring is a different protocol name and is not.
  22169. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22170. Request req;
  22171. req.method = "GET";
  22172. for (const auto &value : upgrade_values) {
  22173. req.headers.emplace("Upgrade", value);
  22174. }
  22175. req.headers.emplace("Connection", "Upgrade");
  22176. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22177. req.headers.emplace("Sec-WebSocket-Version", "13");
  22178. return req;
  22179. };
  22180. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22181. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22182. EXPECT_TRUE(
  22183. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22184. EXPECT_TRUE(
  22185. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22186. EXPECT_TRUE(
  22187. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22188. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22189. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22190. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22191. EXPECT_FALSE(
  22192. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22193. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22194. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22195. }
  22196. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22197. Server svr;
  22198. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22199. auto port = svr.bind_to_any_port("localhost");
  22200. std::thread t([&]() { svr.listen_after_bind(); });
  22201. auto se = detail::scope_exit([&] {
  22202. svr.stop();
  22203. t.join();
  22204. });
  22205. svr.wait_until_ready();
  22206. Headers headers = {{"Upgrade", "websocket"},
  22207. {"Connection", "notupgrade"},
  22208. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22209. {"Sec-WebSocket-Version", "13"}};
  22210. Client cli("localhost", port);
  22211. auto res = cli.Get("/ws", headers);
  22212. // The route exists only as a WebSocket route, so a request that fails the
  22213. // handshake check falls through to ordinary routing.
  22214. ASSERT_TRUE(res);
  22215. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22216. }
  22217. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22218. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22219. // Connection value is the only thing left for the client to reject.
  22220. Server svr;
  22221. svr.Get("/ws", [](const Request &req, Response &res) {
  22222. res.status = StatusCode::SwitchingProtocol_101;
  22223. res.set_header("Upgrade", "websocket");
  22224. res.set_header("Connection", "notupgrade");
  22225. res.set_header("Sec-WebSocket-Accept",
  22226. detail::websocket_accept_key(
  22227. req.get_header_value("Sec-WebSocket-Key")));
  22228. });
  22229. auto port = svr.bind_to_any_port("localhost");
  22230. std::thread t([&]() { svr.listen_after_bind(); });
  22231. auto se = detail::scope_exit([&] {
  22232. svr.stop();
  22233. t.join();
  22234. });
  22235. svr.wait_until_ready();
  22236. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22237. auto res = client.connect();
  22238. EXPECT_FALSE(res);
  22239. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22240. EXPECT_FALSE(client.is_open());
  22241. }
  22242. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22243. Server svr;
  22244. svr.Get("/ws", [](const Request &req, Response &res) {
  22245. res.status = StatusCode::SwitchingProtocol_101;
  22246. res.set_header("Upgrade", "websocket");
  22247. res.set_header("Connection", "Upgrade");
  22248. res.set_header("Sec-WebSocket-Accept",
  22249. detail::websocket_accept_key(
  22250. req.get_header_value("Sec-WebSocket-Key")));
  22251. res.set_header("Sec-WebSocket-Protocol", "admin");
  22252. });
  22253. auto port = svr.bind_to_any_port("localhost");
  22254. std::thread t([&]() { svr.listen_after_bind(); });
  22255. auto se = detail::scope_exit([&] {
  22256. svr.stop();
  22257. t.join();
  22258. });
  22259. svr.wait_until_ready();
  22260. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22261. // Server selects a subprotocol the client never offered
  22262. {
  22263. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22264. ws::WebSocketClient client(url, headers);
  22265. auto res = client.connect();
  22266. EXPECT_FALSE(res);
  22267. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22268. EXPECT_FALSE(client.is_open());
  22269. EXPECT_TRUE(client.subprotocol().empty());
  22270. }
  22271. // Client offered none but the server named one anyway
  22272. {
  22273. ws::WebSocketClient client(url);
  22274. auto res = client.connect();
  22275. EXPECT_FALSE(res);
  22276. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22277. EXPECT_FALSE(client.is_open());
  22278. EXPECT_TRUE(client.subprotocol().empty());
  22279. }
  22280. }
  22281. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22282. // The socket path doubles as the URL host, so it must not contain '/'.
  22283. const char *shard = getenv("GTEST_SHARD_INDEX");
  22284. const std::string sock_path =
  22285. shard ? std::string("httplib-ws-") + shard + ".sock"
  22286. : std::string("httplib-ws.sock");
  22287. std::remove(sock_path.c_str());
  22288. Server svr;
  22289. std::mutex mtx;
  22290. std::string received_host;
  22291. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22292. {
  22293. std::lock_guard<std::mutex> lock(mtx);
  22294. received_host = req.get_header_value("Host");
  22295. }
  22296. std::string msg;
  22297. while (ws.read(msg)) {
  22298. ws.send(msg);
  22299. }
  22300. });
  22301. svr.set_address_family(AF_UNIX);
  22302. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22303. auto se = detail::scope_exit([&] {
  22304. svr.stop();
  22305. t.join();
  22306. std::remove(sock_path.c_str());
  22307. });
  22308. svr.wait_until_ready();
  22309. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22310. client.set_address_family(AF_UNIX);
  22311. ASSERT_TRUE(client.connect());
  22312. ASSERT_TRUE(client.send("hello"));
  22313. std::string msg;
  22314. ASSERT_TRUE(client.read(msg));
  22315. client.close();
  22316. {
  22317. std::lock_guard<std::mutex> lock(mtx);
  22318. // There is no host:port for a Unix socket, so the same "localhost"
  22319. // placeholder the HTTP client uses is expected.
  22320. EXPECT_EQ("localhost", received_host);
  22321. }
  22322. }
  22323. // Two threads must never parse WebSocket frames from the same stream.
  22324. // close() used to read the peer's Close reply with its own frame read, so it
  22325. // raced a reader thread that was in the middle of a payload: the payload loop
  22326. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22327. // so bytes taken by close() were replaced with bytes from further along the
  22328. // stream. The message kept its length and silently changed content.
  22329. //
  22330. // The raw peer below sends a frame header plus part of the payload, waits for
  22331. // the handler to call close(), and only then sends the rest. Whichever thread
  22332. // would win the race for those bytes, the message must arrive intact, because
  22333. // close() must not touch the stream while read() owns it.
  22334. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22335. #ifndef _WIN32
  22336. signal(SIGPIPE, SIG_IGN);
  22337. #endif
  22338. const size_t payload_len = 120; // fits the 7-bit length field
  22339. const size_t prefix_len = 8;
  22340. const int attempts = 8;
  22341. std::string expected(payload_len, '\0');
  22342. for (size_t i = 0; i < payload_len; i++) {
  22343. expected[i] = static_cast<char>('a' + i % 26);
  22344. }
  22345. std::atomic<bool> peer_stalled{false};
  22346. std::atomic<bool> handler_done{false};
  22347. std::mutex received_mutex;
  22348. std::vector<std::string> received;
  22349. // Bound every wait, so a regression fails the test instead of hanging the
  22350. // suite.
  22351. auto wait_for = [](const std::atomic<bool> &flag) {
  22352. for (int i = 0; i < 500 && !flag; i++) {
  22353. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22354. }
  22355. };
  22356. Server svr;
  22357. svr.set_websocket_ping_interval(0);
  22358. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22359. std::thread reader([&]() {
  22360. std::string msg;
  22361. while (ws.read(msg)) {
  22362. std::lock_guard<std::mutex> guard(received_mutex);
  22363. received.push_back(msg);
  22364. }
  22365. });
  22366. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22367. // inside read_websocket_frame() when close() runs.
  22368. wait_for(peer_stalled);
  22369. ws.close();
  22370. reader.join();
  22371. handler_done = true;
  22372. });
  22373. auto port = svr.bind_to_any_port("127.0.0.1");
  22374. std::thread t([&]() { svr.listen_after_bind(); });
  22375. auto se = detail::scope_exit([&] {
  22376. svr.stop();
  22377. t.join();
  22378. });
  22379. svr.wait_until_ready();
  22380. auto send_bytes = [](socket_t s, const std::string &data) {
  22381. #ifdef _WIN32
  22382. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22383. #else
  22384. auto n = ::send(s, data.data(), data.size(), 0);
  22385. #endif
  22386. return n == static_cast<decltype(n)>(data.size());
  22387. };
  22388. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22389. // Every length used here fits the 7-bit length field.
  22390. auto masked_header = [](uint8_t first_byte, size_t len) {
  22391. std::string h;
  22392. h += static_cast<char>(first_byte);
  22393. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22394. h.append(4, '\0'); // mask key
  22395. return h;
  22396. };
  22397. for (int attempt = 0; attempt < attempts; attempt++) {
  22398. peer_stalled = false;
  22399. handler_done = false;
  22400. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22401. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22402. auto se_sock = detail::scope_exit([&] {
  22403. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22404. });
  22405. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22406. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22407. sockaddr_in addr{};
  22408. addr.sin_family = AF_INET;
  22409. addr.sin_port = htons(static_cast<uint16_t>(port));
  22410. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22411. ASSERT_EQ(
  22412. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22413. << "attempt " << attempt;
  22414. ASSERT_TRUE(send_bytes(sock,
  22415. "GET /ws HTTP/1.1\r\n"
  22416. "Host: 127.0.0.1\r\n"
  22417. "Upgrade: websocket\r\n"
  22418. "Connection: Upgrade\r\n"
  22419. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22420. "Sec-WebSocket-Version: 13\r\n"
  22421. "\r\n"))
  22422. << "attempt " << attempt;
  22423. std::string response;
  22424. while (response.find("\r\n\r\n") == std::string::npos) {
  22425. char buf[512];
  22426. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22427. if (n <= 0) { break; }
  22428. response.append(buf, static_cast<size_t>(n));
  22429. }
  22430. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22431. << "attempt " << attempt;
  22432. // Send the header of a Binary message but only the first prefix_len bytes
  22433. // of its payload, leaving the reader thread stalled inside the payload.
  22434. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22435. expected.substr(0, prefix_len)))
  22436. << "attempt " << attempt;
  22437. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22438. peer_stalled = true;
  22439. // Let close() send its Close frame and park in its own read before the
  22440. // rest of the payload arrives, so both threads are waiting for it.
  22441. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22442. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22443. close_frame += static_cast<char>(0x03); // status 1000
  22444. close_frame += static_cast<char>(0xE8);
  22445. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22446. << "attempt " << attempt;
  22447. // Closing the peer releases the reader thread even on the buggy path,
  22448. // where it waits for bytes another thread already consumed.
  22449. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22450. detail::close_socket(sock);
  22451. sock = INVALID_SOCKET;
  22452. wait_for(handler_done);
  22453. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22454. }
  22455. std::lock_guard<std::mutex> guard(received_mutex);
  22456. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22457. << "a message in flight when close() ran was dropped";
  22458. for (size_t i = 0; i < received.size(); i++) {
  22459. EXPECT_EQ(expected, received[i]) << "message " << i;
  22460. }
  22461. }
  22462. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22463. std::atomic<bool> done{false};
  22464. std::string received;
  22465. Server svr;
  22466. svr.set_websocket_ping_interval(0);
  22467. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22468. std::string msg;
  22469. if (ws.read(msg) == ws::Binary) { received = msg; }
  22470. done = true;
  22471. });
  22472. auto port = svr.bind_to_any_port("127.0.0.1");
  22473. std::thread t([&]() { svr.listen_after_bind(); });
  22474. auto se = detail::scope_exit([&] {
  22475. svr.stop();
  22476. t.join();
  22477. });
  22478. svr.wait_until_ready();
  22479. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22480. ASSERT_NE(INVALID_SOCKET, sock);
  22481. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22482. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22483. sockaddr_in addr{};
  22484. addr.sin_family = AF_INET;
  22485. addr.sin_port = htons(static_cast<uint16_t>(port));
  22486. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22487. ASSERT_EQ(0,
  22488. ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22489. // Frames with an all-zero mask key, so the payload goes out verbatim.
  22490. auto frame = [](uint8_t first_byte, const std::string &payload) {
  22491. std::string f;
  22492. f += static_cast<char>(first_byte);
  22493. f += static_cast<char>(0x80 | payload.size());
  22494. f.append(4, '\0');
  22495. return f + payload;
  22496. };
  22497. std::string data = "GET /ws HTTP/1.1\r\n"
  22498. "Host: 127.0.0.1\r\n"
  22499. "Upgrade: websocket\r\n"
  22500. "Connection: Upgrade\r\n"
  22501. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22502. "Sec-WebSocket-Version: 13\r\n"
  22503. "\r\n";
  22504. data += frame(0x02, "Hel"); // Binary, more to come
  22505. data += frame(0x89, "p"); // FIN + Ping
  22506. data += frame(0x80, "lo"); // FIN + Continuation
  22507. #ifdef _WIN32
  22508. ::send(sock, data.data(), static_cast<int>(data.size()), 0);
  22509. #else
  22510. ::send(sock, data.data(), data.size(), 0);
  22511. #endif
  22512. for (int i = 0; i < 500 && !done; i++) {
  22513. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22514. }
  22515. ASSERT_TRUE(done);
  22516. EXPECT_EQ("Hello", received);
  22517. }
  22518. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22519. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22520. protected:
  22521. void SetUp() override {
  22522. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22523. SERVER_PRIVATE_KEY_FILE);
  22524. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22525. std::string msg;
  22526. ws::ReadResult ret;
  22527. while ((ret = ws.read(msg))) {
  22528. if (ret == ws::Binary) {
  22529. ws.send(msg.data(), msg.size());
  22530. } else {
  22531. ws.send(msg);
  22532. }
  22533. }
  22534. });
  22535. port_ = server_->bind_to_any_port(HOST);
  22536. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22537. server_->wait_until_ready();
  22538. }
  22539. void TearDown() override {
  22540. server_->stop();
  22541. if (server_thread_.joinable()) { server_thread_.join(); }
  22542. }
  22543. std::unique_ptr<SSLServer> server_;
  22544. std::thread server_thread_;
  22545. int port_ = 0;
  22546. };
  22547. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22548. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22549. "/ws-echo");
  22550. client.enable_server_certificate_verification(false);
  22551. ASSERT_TRUE(client.connect());
  22552. ASSERT_TRUE(client.is_open());
  22553. ASSERT_TRUE(client.send("Hello WSS"));
  22554. std::string msg;
  22555. EXPECT_EQ(ws::Text, client.read(msg));
  22556. EXPECT_EQ("Hello WSS", msg);
  22557. client.close();
  22558. }
  22559. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22560. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22561. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22562. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22563. // client (without calling close() first) is the only path that runs
  22564. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22565. // bug exactly.
  22566. //
  22567. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22568. // when linked against an instrumented libssl; run under Valgrind to catch it
  22569. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22570. // suite (the freed session otherwise stalls on the close handshake) — this test
  22571. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22572. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22573. {
  22574. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22575. "/ws-echo");
  22576. client.enable_server_certificate_verification(false);
  22577. client.set_read_timeout(2, 0);
  22578. client.set_write_timeout(2, 0);
  22579. ASSERT_TRUE(client.connect());
  22580. ASSERT_TRUE(client.is_open());
  22581. ASSERT_TRUE(client.send("still open"));
  22582. // Intentionally do NOT call client.close(): leaving scope runs
  22583. // shutdown_and_close() with the WebSocket still open, which must send the
  22584. // close frame while the TLS session is still alive.
  22585. }
  22586. }
  22587. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22588. // shutdown_and_close() at the start of connect(), reproducing the same
  22589. // use-after-free within the test body rather than at scope exit. The second
  22590. // connect must succeed and echo, proving the close handshake ran over a live
  22591. // session. See the note above about memory-tool requirements.
  22592. TEST_F(WebSocketSSLIntegrationTest,
  22593. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22594. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22595. "/ws-echo");
  22596. client.enable_server_certificate_verification(false);
  22597. client.set_read_timeout(2, 0);
  22598. client.set_write_timeout(2, 0);
  22599. ASSERT_TRUE(client.connect());
  22600. ASSERT_TRUE(client.is_open());
  22601. ASSERT_TRUE(client.send("still open"));
  22602. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22603. // the still-open connection, which must not touch a freed TLS session.
  22604. ASSERT_TRUE(client.connect());
  22605. ASSERT_TRUE(client.is_open());
  22606. ASSERT_TRUE(client.send("after reconnect"));
  22607. std::string msg;
  22608. EXPECT_EQ(ws::Text, client.read(msg));
  22609. EXPECT_EQ("after reconnect", msg);
  22610. client.close();
  22611. }
  22612. #endif
  22613. #ifdef CPPHTTPLIB_SSL_ENABLED
  22614. class WebSocketSSLCATest : public ::testing::Test {
  22615. protected:
  22616. void SetUp() override {
  22617. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22618. SERVER_PRIVATE_KEY_FILE);
  22619. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22620. std::string msg;
  22621. while (ws.read(msg)) {
  22622. ws.send(msg);
  22623. }
  22624. });
  22625. port_ = server_->bind_to_any_port("127.0.0.1");
  22626. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22627. server_->wait_until_ready();
  22628. }
  22629. void TearDown() override {
  22630. server_->stop();
  22631. if (server_thread_.joinable()) { server_thread_.join(); }
  22632. }
  22633. std::string url() const {
  22634. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22635. }
  22636. std::unique_ptr<SSLServer> server_;
  22637. std::thread server_thread_;
  22638. int port_ = 0;
  22639. };
  22640. // A custom CA loaded as PEM verifies the server with full certificate
  22641. // verification enabled
  22642. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22643. ws::WebSocketClient client(url());
  22644. std::string cert;
  22645. read_file(SERVER_CERT2_FILE, cert);
  22646. client.load_ca_cert_store(cert.c_str(), cert.size());
  22647. ASSERT_TRUE(client.connect());
  22648. ASSERT_TRUE(client.send("hello"));
  22649. std::string msg;
  22650. EXPECT_EQ(ws::Text, client.read(msg));
  22651. EXPECT_EQ("hello", msg);
  22652. client.close();
  22653. }
  22654. // A custom CA that does not cover the server must fail verification (the
  22655. // custom CA is exclusive; system certs are not loaded alongside it)
  22656. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22657. ws::WebSocketClient client(url());
  22658. std::string cert;
  22659. read_file(CLIENT_CA_CERT_FILE, cert);
  22660. client.load_ca_cert_store(cert.c_str(), cert.size());
  22661. auto res = client.connect();
  22662. ASSERT_FALSE(res);
  22663. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22664. EXPECT_EQ(-1, res.status());
  22665. EXPECT_NE(0u, res.ssl_backend_error());
  22666. }
  22667. // The same CA as a file path rather than PEM in memory
  22668. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22669. ws::WebSocketClient client(url());
  22670. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22671. ASSERT_TRUE(client.connect());
  22672. ASSERT_TRUE(client.send("hello"));
  22673. std::string msg;
  22674. EXPECT_EQ(ws::Text, client.read(msg));
  22675. EXPECT_EQ("hello", msg);
  22676. client.close();
  22677. }
  22678. // ...and a CA file that does not cover the server still fails, so it is the
  22679. // path above that decides the outcome
  22680. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22681. ws::WebSocketClient client(url());
  22682. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22683. ASSERT_FALSE(client.connect());
  22684. }
  22685. // Regression test: reconnecting with a native custom CA store used to reuse
  22686. // a store handle the previous TLS context had already freed (use-after-free
  22687. // under the OpenSSL backend). The context now lives as long as the client.
  22688. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22689. ws::WebSocketClient client(url());
  22690. std::string cert;
  22691. read_file(SERVER_CERT2_FILE, cert);
  22692. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22693. ASSERT_TRUE(client.connect());
  22694. client.close();
  22695. ASSERT_TRUE(client.connect());
  22696. ASSERT_TRUE(client.send("again"));
  22697. std::string msg;
  22698. EXPECT_EQ(ws::Text, client.read(msg));
  22699. EXPECT_EQ("again", msg);
  22700. client.close();
  22701. }
  22702. // Regression test: a certificate with a trusted chain but no identity match
  22703. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22704. // verification entirely for IP hosts, so this connection succeeded there.
  22705. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22706. // chain verification while the identity check must still fail.
  22707. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22709. ASSERT_TRUE(svr.is_valid());
  22710. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22711. std::string msg;
  22712. while (ws.read(msg)) {
  22713. ws.send(msg);
  22714. }
  22715. });
  22716. auto port = svr.bind_to_any_port("127.0.0.1");
  22717. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22718. auto se = detail::scope_exit([&] {
  22719. svr.stop();
  22720. t.join();
  22721. });
  22722. svr.wait_until_ready();
  22723. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22724. "/echo");
  22725. std::string cert;
  22726. read_file(SERVER_CERT_FILE, cert);
  22727. client.load_ca_cert_store(cert.c_str(), cert.size());
  22728. ASSERT_FALSE(client.connect());
  22729. }
  22730. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22731. // SNI, so nothing binds the host name to the TLS session. These bind the
  22732. // server to "localhost" instead, the only shape that exercises the SNI and
  22733. // hostname-verification path with certificate verification left enabled.
  22734. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22735. protected:
  22736. void Start(const char *cert_file) {
  22737. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22738. SERVER_PRIVATE_KEY_FILE);
  22739. ASSERT_TRUE(server_->is_valid());
  22740. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22741. std::string msg;
  22742. while (ws.read(msg)) {
  22743. ws.send(msg);
  22744. }
  22745. });
  22746. port_ = server_->bind_to_any_port("localhost");
  22747. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22748. server_->wait_until_ready();
  22749. }
  22750. void TearDown() override {
  22751. if (server_) { server_->stop(); }
  22752. if (server_thread_.joinable()) { server_thread_.join(); }
  22753. }
  22754. std::string url() const {
  22755. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22756. }
  22757. std::unique_ptr<SSLServer> server_;
  22758. std::thread server_thread_;
  22759. int port_ = 0;
  22760. };
  22761. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22762. // out and the connection is usable
  22763. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22764. Start(SERVER_CERT2_FILE);
  22765. ws::WebSocketClient client(url());
  22766. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22767. ASSERT_TRUE(client.connect());
  22768. ASSERT_TRUE(client.send("hello"));
  22769. std::string msg;
  22770. EXPECT_EQ(ws::Text, client.read(msg));
  22771. EXPECT_EQ("hello", msg);
  22772. client.close();
  22773. }
  22774. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22775. // while the identity check must still reject "localhost"
  22776. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22777. Start(SERVER_CERT_FILE);
  22778. ws::WebSocketClient client(url());
  22779. client.set_ca_cert_path(SERVER_CERT_FILE);
  22780. auto res = client.connect();
  22781. ASSERT_FALSE(res);
  22782. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22783. EXPECT_EQ(-1, res.status());
  22784. }
  22785. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22786. // disabled: the chain is still checked, only the identity check is skipped
  22787. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22788. Start(SERVER_CERT_FILE);
  22789. ws::WebSocketClient client(url());
  22790. client.set_ca_cert_path(SERVER_CERT_FILE);
  22791. client.enable_server_hostname_verification(false);
  22792. ASSERT_TRUE(client.connect());
  22793. ASSERT_TRUE(client.send("hello"));
  22794. std::string msg;
  22795. EXPECT_EQ(ws::Text, client.read(msg));
  22796. EXPECT_EQ("hello", msg);
  22797. client.close();
  22798. }
  22799. // A CA that did not sign the server certificate fails the chain, even though
  22800. // the name would match
  22801. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22802. Start(SERVER_CERT2_FILE);
  22803. ws::WebSocketClient client(url());
  22804. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22805. ASSERT_FALSE(client.connect());
  22806. }
  22807. // With verification disabled, neither the chain nor the name is checked
  22808. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22809. Start(SERVER_CERT_FILE);
  22810. ws::WebSocketClient client(url());
  22811. client.enable_server_certificate_verification(false);
  22812. ASSERT_TRUE(client.connect());
  22813. ASSERT_TRUE(client.send("hello"));
  22814. std::string msg;
  22815. EXPECT_EQ(ws::Text, client.read(msg));
  22816. EXPECT_EQ("hello", msg);
  22817. client.close();
  22818. }
  22819. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22820. protected:
  22821. void SetUp() override {
  22822. server_ = httplib::detail::make_unique<SSLServer>(
  22823. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22824. ASSERT_TRUE(server_->is_valid());
  22825. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22826. std::string msg;
  22827. while (ws.read(msg)) {
  22828. ws.send(msg);
  22829. }
  22830. });
  22831. port_ = server_->bind_to_any_port("localhost");
  22832. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22833. server_->wait_until_ready();
  22834. }
  22835. void TearDown() override {
  22836. server_->stop();
  22837. if (server_thread_.joinable()) { server_thread_.join(); }
  22838. }
  22839. std::string url() const {
  22840. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22841. }
  22842. void ConnectWithClientCert(const std::string &client_cert_file,
  22843. const std::string &client_private_key_file,
  22844. const char *private_key_password) {
  22845. std::string cert_pem, key_pem;
  22846. read_file(client_cert_file, cert_pem);
  22847. read_file(client_private_key_file, key_pem);
  22848. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22849. key_pem.c_str(), key_pem.size(),
  22850. private_key_password};
  22851. ws::WebSocketClient client(url(), pem);
  22852. ASSERT_TRUE(client.is_valid());
  22853. client.enable_server_certificate_verification(false);
  22854. ASSERT_TRUE(client.connect());
  22855. ASSERT_TRUE(client.send("hello"));
  22856. std::string msg;
  22857. EXPECT_EQ(ws::Text, client.read(msg));
  22858. EXPECT_EQ("hello", msg);
  22859. client.close();
  22860. }
  22861. std::unique_ptr<SSLServer> server_;
  22862. std::thread server_thread_;
  22863. int port_ = 0;
  22864. };
  22865. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22866. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22867. }
  22868. // Control for the tests above: the fixture's server really does require a
  22869. // client certificate, so it is the PEM the constructor installed that decides
  22870. // the outcome.
  22871. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22872. ws::WebSocketClient client(url());
  22873. ASSERT_TRUE(client.is_valid());
  22874. client.enable_server_certificate_verification(false);
  22875. EXPECT_FALSE(client.connect());
  22876. }
  22877. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22878. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22879. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22880. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22881. }
  22882. #endif
  22883. #if !defined(_WIN32)
  22884. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22885. auto secret_dir = std::string("./symlink_test_secret");
  22886. auto served_dir = std::string("./symlink_test_served");
  22887. auto secret_file = secret_dir + "/secret.txt";
  22888. auto symlink_path = served_dir + "/escape";
  22889. // Setup: create directories and files
  22890. mkdir(secret_dir.c_str(), 0755);
  22891. mkdir(served_dir.c_str(), 0755);
  22892. {
  22893. std::ofstream ofs(secret_file);
  22894. ofs << "SECRET_DATA";
  22895. }
  22896. // Create symlink using absolute path so it resolves correctly
  22897. #ifdef PATH_MAX
  22898. char abs_secret[PATH_MAX];
  22899. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22900. #else
  22901. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22902. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22903. ASSERT_NE(nullptr, abs_secret);
  22904. #endif
  22905. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22906. auto se = detail::scope_exit([&] {
  22907. unlink(symlink_path.c_str());
  22908. unlink(secret_file.c_str());
  22909. rmdir(served_dir.c_str());
  22910. rmdir(secret_dir.c_str());
  22911. });
  22912. Server svr;
  22913. svr.set_mount_point("/", served_dir);
  22914. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22915. auto se2 = detail::scope_exit([&] {
  22916. svr.stop();
  22917. listen_thread.join();
  22918. });
  22919. svr.wait_until_ready();
  22920. Client cli("localhost", PORT);
  22921. // Symlink pointing outside base dir should be blocked
  22922. auto res = cli.Get("/escape/secret.txt");
  22923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22924. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22925. }
  22926. #endif
  22927. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22928. // "GET /smuggled" request), reads the first response, and only then sends the
  22929. // embedded request as the body. Returns how many times /smuggled ran.
  22930. //
  22931. // The body is sent AFTER receiving the first response (as in the original
  22932. // PoC) so that the stream_line_reader cannot buffer it together with the
  22933. // headers of the first request.
  22934. static int count_smuggled_requests(const std::string &outer_head,
  22935. std::string &first_response) {
  22936. Server svr;
  22937. svr.set_mount_point("/", "./www");
  22938. std::atomic<int> smuggled_count(0);
  22939. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22940. smuggled_count++;
  22941. res.set_content("oops", "text/plain");
  22942. });
  22943. svr.Post("/post", [&](const Request &req, Response &res) {
  22944. res.set_content(req.body, "text/plain");
  22945. });
  22946. auto port = svr.bind_to_any_port("localhost");
  22947. thread t = thread([&] { svr.listen_after_bind(); });
  22948. auto se = detail::scope_exit([&] {
  22949. svr.stop();
  22950. t.join();
  22951. });
  22952. svr.wait_until_ready();
  22953. auto error = Error::Success;
  22954. auto sock = detail::create_client_socket(
  22955. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22956. /*connection_timeout_sec=*/2, 0,
  22957. /*read_timeout_sec=*/2, 0,
  22958. /*write_timeout_sec=*/2, 0, std::string(), error);
  22959. EXPECT_NE(INVALID_SOCKET, sock);
  22960. if (sock == INVALID_SOCKET) { return -1; }
  22961. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22962. // The "smuggled" request will be sent as the body of the outer request
  22963. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22964. "Host: localhost\r\n"
  22965. "Connection: close\r\n"
  22966. "\r\n";
  22967. auto head = outer_head;
  22968. auto len = std::to_string(smuggled.size());
  22969. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22970. pos = head.find("{len}", pos + len.size())) {
  22971. head.replace(pos, 5, len);
  22972. }
  22973. // Step 1: Send only the outer request headers (no body yet)
  22974. auto sent = send(sock, head.data(), head.size(), 0);
  22975. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22976. // Step 2: Read the first response
  22977. char buf[4096];
  22978. for (;;) {
  22979. auto n = recv(sock, buf, sizeof(buf), 0);
  22980. if (n <= 0) break;
  22981. first_response.append(buf, static_cast<size_t>(n));
  22982. // Stop once we have a complete response (headers + body)
  22983. auto hdr_end = first_response.find("\r\n\r\n");
  22984. if (hdr_end != std::string::npos) {
  22985. // Check for Content-Length to know when the body is complete
  22986. auto cl_pos = first_response.find("Content-Length:");
  22987. if (cl_pos != std::string::npos) {
  22988. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22989. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22990. auto cl = std::stoul(
  22991. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22992. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22993. } else {
  22994. break; // No Content-Length, assume headers-only response
  22995. }
  22996. }
  22997. }
  22998. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22999. // vulnerable server the keep-alive loop reads this as a second request. The
  23000. // server may already have closed the connection, so the result is ignored.
  23001. send(sock, smuggled.data(), smuggled.size(), 0);
  23002. // Half-close so that a server which drained the body sees EOF and closes,
  23003. // instead of the read below waiting for the read timeout.
  23004. #ifdef _WIN32
  23005. ::shutdown(sock, SD_SEND);
  23006. #else
  23007. ::shutdown(sock, SHUT_WR);
  23008. #endif
  23009. // Step 4: Read until the server closes the connection
  23010. for (;;) {
  23011. auto n = recv(sock, buf, sizeof(buf), 0);
  23012. if (n <= 0) break;
  23013. }
  23014. return smuggled_count.load();
  23015. }
  23016. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23017. // A GET request with Content-Length to a static file handler must have its
  23018. // body drained before the keep-alive connection is reused. Otherwise the
  23019. // unread body bytes are interpreted as the next HTTP request.
  23020. std::string first_response;
  23021. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23022. "Host: localhost\r\n"
  23023. "Content-Length: {len}\r\n"
  23024. "\r\n",
  23025. first_response));
  23026. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23027. }
  23028. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23029. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23030. // be answered with 400 and the connection closed. Treating it as "no body"
  23031. // leaves the body to be parsed as the next request.
  23032. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23033. const char *targets[] = {
  23034. "GET /file", // handler that never reads the body
  23035. "GET /not-found", // no handler matches (404)
  23036. "POST /post", // handler that reads the body
  23037. };
  23038. for (auto target : targets) {
  23039. for (auto value : values) {
  23040. std::string first_response;
  23041. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23042. " HTTP/1.1\r\n"
  23043. "Host: localhost\r\n"
  23044. "Content-Length: " +
  23045. value + "\r\n\r\n",
  23046. first_response))
  23047. << target << " with Content-Length: " << value;
  23048. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23049. << target << " with Content-Length: " << value;
  23050. }
  23051. }
  23052. }
  23053. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23054. // A 400 for an unparseable request line leaves the rest of the message
  23055. // unread, so the connection must be closed rather than reused.
  23056. std::string first_response;
  23057. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23058. "Host: localhost\r\n"
  23059. "Content-Length: {len}\r\n"
  23060. "\r\n",
  23061. first_response));
  23062. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23063. }
  23064. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23065. // Same as above for a header block that fails to parse.
  23066. std::string first_response;
  23067. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23068. "Host: localhost\r\n"
  23069. "Bad Header\r\n"
  23070. "Content-Length: {len}\r\n"
  23071. "\r\n",
  23072. first_response));
  23073. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23074. }
  23075. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23076. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23077. // server must not read another request on that connection, even when the
  23078. // request had no body to drain.
  23079. std::string first_response;
  23080. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23081. "Host: localhost\r\n"
  23082. "\r\n",
  23083. first_response));
  23084. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23085. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23086. }
  23087. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23088. // A content reader that stops early leaves the stream inside the body.
  23089. // Draining the whole Content-Length from there, or reading the body again,
  23090. // reads into the next request, and whatever follows is parsed as a request
  23091. // of its own.
  23092. Server svr;
  23093. std::atomic<int> smuggled_count(0);
  23094. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23095. svr.Post("/upload", [](const Request &req, Response &res,
  23096. const ContentReader &content_reader) {
  23097. // Stop at the last chunk, so the whole body has been read however it
  23098. // arrives.
  23099. auto length = req.get_header_value_u64("Content-Length");
  23100. size_t total = 0;
  23101. auto consumed = content_reader([&](const char *, size_t n) {
  23102. total += n;
  23103. return total < length;
  23104. });
  23105. EXPECT_FALSE(consumed);
  23106. if (req.has_param("retry")) {
  23107. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23108. }
  23109. // Replace the 400 the aborted read set, which would close the connection.
  23110. res.set_redirect("/done");
  23111. });
  23112. auto port = svr.bind_to_any_port(HOST);
  23113. thread t = thread([&] { svr.listen_after_bind(); });
  23114. auto se = detail::scope_exit([&] {
  23115. svr.stop();
  23116. t.join();
  23117. });
  23118. svr.wait_until_ready();
  23119. // A front end sees the second request as a POST whose body is the GET. The
  23120. // first body is as long as the POST's headers, so draining it again reads
  23121. // exactly those and leaves the GET to be parsed next.
  23122. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23123. "Host: localhost\r\n"
  23124. "\r\n";
  23125. std::string second_head = "POST /post HTTP/1.1\r\n"
  23126. "Host: localhost\r\n"
  23127. "Content-Length: " +
  23128. std::to_string(inner.size()) +
  23129. "\r\n"
  23130. "\r\n";
  23131. for (auto target : {"/upload", "/upload?retry"}) {
  23132. smuggled_count = 0;
  23133. std::string request = "POST " + std::string(target) +
  23134. " HTTP/1.1\r\n"
  23135. "Host: localhost\r\n"
  23136. "Content-Length: " +
  23137. std::to_string(second_head.size()) +
  23138. "\r\n"
  23139. "\r\n" +
  23140. std::string(second_head.size(), 'A') + second_head +
  23141. inner;
  23142. std::string response;
  23143. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23144. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23145. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23146. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23147. EXPECT_EQ(0, smuggled_count.load()) << target;
  23148. }
  23149. }
  23150. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23151. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23152. // must be rejected with 400 Bad Request.
  23153. Server svr;
  23154. svr.Post("/test", [&](const Request &, Response &res) {
  23155. res.set_content("ok", "text/plain");
  23156. });
  23157. thread t = thread([&] { svr.listen(HOST, PORT); });
  23158. auto se = detail::scope_exit([&] {
  23159. svr.stop();
  23160. t.join();
  23161. ASSERT_FALSE(svr.is_running());
  23162. });
  23163. svr.wait_until_ready();
  23164. // Exact "chunked"
  23165. {
  23166. auto req = "POST /test HTTP/1.1\r\n"
  23167. "Host: localhost\r\n"
  23168. "Content-Length: 5\r\n"
  23169. "Transfer-Encoding: chunked\r\n"
  23170. "Connection: close\r\n"
  23171. "\r\n"
  23172. "hello";
  23173. std::string response;
  23174. ASSERT_TRUE(send_request(1, req, &response));
  23175. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23176. response.substr(0, response.find("\r\n")));
  23177. }
  23178. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23179. {
  23180. auto req = "POST /test HTTP/1.1\r\n"
  23181. "Host: localhost\r\n"
  23182. "Content-Length: 5\r\n"
  23183. "Transfer-Encoding: gzip, chunked\r\n"
  23184. "Connection: close\r\n"
  23185. "\r\n"
  23186. "hello";
  23187. std::string response;
  23188. ASSERT_TRUE(send_request(1, req, &response));
  23189. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23190. response.substr(0, response.find("\r\n")));
  23191. }
  23192. }
  23193. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23194. Server svr;
  23195. svr.Post("/test", [&](const Request &, Response &res) {
  23196. res.set_content("ok", "text/plain");
  23197. });
  23198. thread t = thread([&] { svr.listen(HOST, PORT); });
  23199. auto se = detail::scope_exit([&] {
  23200. svr.stop();
  23201. t.join();
  23202. ASSERT_FALSE(svr.is_running());
  23203. });
  23204. svr.wait_until_ready();
  23205. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23206. // length cannot be determined, so the server must answer 400 and close
  23207. // rather than treat the request as bodyless and leave the body in the
  23208. // socket for the next request to pick up.
  23209. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23210. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23211. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23212. std::string response;
  23213. ASSERT_TRUE(send_request(1, req, &response));
  23214. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23215. response.substr(0, response.find("\r\n")))
  23216. << transfer_encoding;
  23217. }
  23218. // RFC 9110 5.3: the codings may also be split across several
  23219. // Transfer-Encoding lines, which combine in the order they were received.
  23220. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23221. // just like the single-line "chunked, gzip" above.
  23222. {
  23223. auto req = "POST /test HTTP/1.1\r\n"
  23224. "Host: localhost\r\n"
  23225. "Transfer-Encoding: chunked\r\n"
  23226. "Transfer-Encoding: gzip\r\n"
  23227. "\r\n"
  23228. "0\r\n\r\n";
  23229. std::string response;
  23230. ASSERT_TRUE(send_request(1, req, &response));
  23231. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23232. response.substr(0, response.find("\r\n")));
  23233. }
  23234. // A sequence ending in chunked stays valid.
  23235. auto req = "POST /test HTTP/1.1\r\n"
  23236. "Host: localhost\r\n"
  23237. "Transfer-Encoding: gzip, chunked\r\n"
  23238. "Connection: close\r\n"
  23239. "\r\n"
  23240. "0\r\n\r\n";
  23241. std::string response;
  23242. ASSERT_TRUE(send_request(1, req, &response));
  23243. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23244. // ...including when it is spread over several lines.
  23245. auto split_req = "POST /test HTTP/1.1\r\n"
  23246. "Host: localhost\r\n"
  23247. "Transfer-Encoding: gzip\r\n"
  23248. "Transfer-Encoding: chunked\r\n"
  23249. "Connection: close\r\n"
  23250. "\r\n"
  23251. "0\r\n\r\n";
  23252. std::string split_response;
  23253. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23254. EXPECT_EQ("HTTP/1.1 200 OK",
  23255. split_response.substr(0, split_response.find("\r\n")));
  23256. }
  23257. // Regression for issue #2450: a DELETE without Content-Length on a
  23258. // keep-alive connection must not let the post-response drain consume the
  23259. // next request's bytes.
  23260. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23261. Server svr;
  23262. std::atomic<int> delete_count(0);
  23263. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23264. delete_count++;
  23265. res.status = StatusCode::NoContent_204;
  23266. });
  23267. auto port = svr.bind_to_any_port(HOST);
  23268. thread t = thread([&] { svr.listen_after_bind(); });
  23269. auto se = detail::scope_exit([&] {
  23270. svr.stop();
  23271. t.join();
  23272. });
  23273. svr.wait_until_ready();
  23274. auto error = Error::Success;
  23275. auto sock = detail::create_client_socket(
  23276. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23277. /*connection_timeout_sec=*/2, 0,
  23278. /*read_timeout_sec=*/2, 0,
  23279. /*write_timeout_sec=*/2, 0, std::string(), error);
  23280. ASSERT_NE(INVALID_SOCKET, sock);
  23281. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23282. auto send_request_and_read_response = [&](const std::string &req,
  23283. std::string &out) -> bool {
  23284. auto sent = send(sock, req.data(), req.size(), 0);
  23285. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23286. char buf[4096];
  23287. for (;;) {
  23288. auto n = recv(sock, buf, sizeof(buf), 0);
  23289. if (n <= 0) { return !out.empty(); }
  23290. out.append(buf, static_cast<size_t>(n));
  23291. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23292. }
  23293. };
  23294. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23295. "Host: localhost\r\n"
  23296. "\r\n";
  23297. std::string resp1;
  23298. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23299. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23300. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23301. "Host: localhost\r\n"
  23302. "Connection: close\r\n"
  23303. "\r\n";
  23304. std::string resp2;
  23305. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23306. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23307. EXPECT_EQ(2, delete_count.load());
  23308. }
  23309. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23310. Server svr;
  23311. svr.Post("/ingest", [&](const Request &, Response &res,
  23312. const ContentReader &content_reader) {
  23313. auto consumed = content_reader([](const char *, size_t) { return false; });
  23314. EXPECT_FALSE(consumed);
  23315. res.status = StatusCode::Conflict_409;
  23316. res.set_header("Connection", "close");
  23317. });
  23318. auto port = svr.bind_to_any_port(HOST);
  23319. thread t = thread([&] { svr.listen_after_bind(); });
  23320. auto se = detail::scope_exit([&] {
  23321. svr.stop();
  23322. t.join();
  23323. });
  23324. svr.wait_until_ready();
  23325. auto error = Error::Success;
  23326. auto sock = detail::create_client_socket(
  23327. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23328. /*connection_timeout_sec=*/2, 0,
  23329. /*read_timeout_sec=*/1, 0,
  23330. /*write_timeout_sec=*/2, 0, std::string(), error);
  23331. ASSERT_NE(INVALID_SOCKET, sock);
  23332. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23333. std::string request = "POST /ingest HTTP/1.1\r\n"
  23334. "Host: localhost\r\n"
  23335. "Transfer-Encoding: chunked\r\n"
  23336. "\r\n"
  23337. "4\r\n"
  23338. "data\r\n";
  23339. auto sent = send(sock, request.data(), request.size(), 0);
  23340. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23341. std::string response;
  23342. ssize_t received = 0;
  23343. do {
  23344. char buf[4096];
  23345. received = recv(sock, buf, sizeof(buf), 0);
  23346. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23347. } while (received > 0);
  23348. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23349. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23350. EXPECT_EQ(0, received);
  23351. }
  23352. namespace no_proxy_test {
  23353. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23354. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23355. // calling listen().
  23356. class ScopedServer {
  23357. public:
  23358. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23359. ~ScopedServer() {
  23360. svr_.stop();
  23361. if (th_.joinable()) { th_.join(); }
  23362. }
  23363. Server &svr() { return svr_; }
  23364. int port() const { return port_; }
  23365. void listen() {
  23366. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23367. svr_.wait_until_ready();
  23368. }
  23369. private:
  23370. Server svr_;
  23371. std::thread th_;
  23372. int port_ = 0;
  23373. };
  23374. class ProxyAndTargetServers {
  23375. public:
  23376. ProxyAndTargetServers() {
  23377. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23378. proxy_hits_++;
  23379. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23380. res.set_content("via-proxy", "text/plain");
  23381. });
  23382. target_.Get(".*", [this](const Request &req, Response &res) {
  23383. target_hits_++;
  23384. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23385. res.set_content("direct", "text/plain");
  23386. });
  23387. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23388. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23389. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23390. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23391. proxy_mock_.wait_until_ready();
  23392. target_.wait_until_ready();
  23393. }
  23394. ~ProxyAndTargetServers() {
  23395. proxy_mock_.stop();
  23396. target_.stop();
  23397. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23398. if (target_thread_.joinable()) { target_thread_.join(); }
  23399. }
  23400. Server &proxy_mock() { return proxy_mock_; }
  23401. Server &target() { return target_; }
  23402. int proxy_port() const { return proxy_port_; }
  23403. int target_port() const { return target_port_; }
  23404. int proxy_hits() const { return proxy_hits_.load(); }
  23405. int target_hits() const { return target_hits_.load(); }
  23406. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23407. void reset_counters() {
  23408. proxy_hits_ = 0;
  23409. target_hits_ = 0;
  23410. last_had_proxy_authz_ = false;
  23411. }
  23412. private:
  23413. Server proxy_mock_;
  23414. Server target_;
  23415. std::thread proxy_thread_;
  23416. std::thread target_thread_;
  23417. int proxy_port_ = 0;
  23418. int target_port_ = 0;
  23419. std::atomic<int> proxy_hits_{0};
  23420. std::atomic<int> target_hits_{0};
  23421. std::atomic<bool> last_had_proxy_authz_{false};
  23422. };
  23423. inline std::unique_ptr<Client> make_client(const std::string &host,
  23424. ProxyAndTargetServers &s) {
  23425. auto cli = detail::make_unique<Client>(host, s.target_port());
  23426. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23427. cli->set_proxy("127.0.0.1", s.proxy_port());
  23428. return cli;
  23429. }
  23430. } // namespace no_proxy_test
  23431. using no_proxy_test::make_client;
  23432. using no_proxy_test::ProxyAndTargetServers;
  23433. TEST(NoProxyTest, ExactHostnameBypasses) {
  23434. ProxyAndTargetServers s;
  23435. auto cli = make_client("example.com", s);
  23436. cli->set_no_proxy({"example.com"});
  23437. auto res = cli->Get("/");
  23438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23439. EXPECT_EQ(0, s.proxy_hits());
  23440. EXPECT_EQ(1, s.target_hits());
  23441. }
  23442. TEST(NoProxyTest, SubdomainBypasses) {
  23443. ProxyAndTargetServers s;
  23444. auto cli = make_client("foo.example.com", s);
  23445. cli->set_no_proxy({"example.com"});
  23446. auto res = cli->Get("/");
  23447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23448. EXPECT_EQ(0, s.proxy_hits());
  23449. EXPECT_EQ(1, s.target_hits());
  23450. }
  23451. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23452. // Regression guard: "evilexample.com" must not be considered a subdomain
  23453. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23454. // check would let traffic bypass the proxy and leak credentials direct
  23455. // to the attacker host.
  23456. ProxyAndTargetServers s;
  23457. auto cli = make_client("evilexample.com", s);
  23458. cli->set_no_proxy({"example.com"});
  23459. auto res = cli->Get("/");
  23460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23461. EXPECT_GE(s.proxy_hits(), 1);
  23462. EXPECT_EQ(0, s.target_hits());
  23463. }
  23464. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23465. ProxyAndTargetServers s;
  23466. auto cli = make_client("example.com.evil.com", s);
  23467. cli->set_no_proxy({"example.com"});
  23468. auto res = cli->Get("/");
  23469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23470. EXPECT_GE(s.proxy_hits(), 1);
  23471. EXPECT_EQ(0, s.target_hits());
  23472. }
  23473. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23474. ProxyAndTargetServers s;
  23475. auto cli = make_client("example.com", s);
  23476. cli->set_no_proxy({".example.com"});
  23477. auto res = cli->Get("/");
  23478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23479. EXPECT_EQ(0, s.proxy_hits());
  23480. EXPECT_EQ(1, s.target_hits());
  23481. }
  23482. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23483. ProxyAndTargetServers s;
  23484. auto cli = make_client("Example.COM", s);
  23485. cli->set_no_proxy({"EXAMPLE.com"});
  23486. auto res = cli->Get("/");
  23487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23488. EXPECT_EQ(0, s.proxy_hits());
  23489. EXPECT_EQ(1, s.target_hits());
  23490. }
  23491. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23492. ProxyAndTargetServers s;
  23493. auto cli = make_client("example.com.", s);
  23494. cli->set_no_proxy({"example.com"});
  23495. auto res = cli->Get("/");
  23496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23497. EXPECT_EQ(0, s.proxy_hits());
  23498. EXPECT_EQ(1, s.target_hits());
  23499. }
  23500. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23501. // Trailing dots must be normalized on BOTH sides — host and entry.
  23502. // An implementation that only strips the host-side trailing dot would
  23503. // fail to match host "example.com" against entry "example.com." because
  23504. // a literal substring search would compare 11 chars against 12.
  23505. ProxyAndTargetServers s;
  23506. auto cli = make_client("example.com", s);
  23507. cli->set_no_proxy({"example.com."});
  23508. auto res = cli->Get("/");
  23509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23510. EXPECT_EQ(0, s.proxy_hits());
  23511. EXPECT_EQ(1, s.target_hits());
  23512. }
  23513. TEST(NoProxyTest, WildcardBypassesEverything) {
  23514. ProxyAndTargetServers s;
  23515. auto cli = make_client("anything.invalid.test", s);
  23516. cli->set_no_proxy({"*"});
  23517. auto res = cli->Get("/");
  23518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23519. EXPECT_EQ(0, s.proxy_hits());
  23520. EXPECT_EQ(1, s.target_hits());
  23521. }
  23522. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23523. ProxyAndTargetServers s;
  23524. Client cli("127.0.0.1", s.target_port());
  23525. cli.set_proxy("127.0.0.1", s.proxy_port());
  23526. cli.set_no_proxy({"127.0.0.1"});
  23527. auto res = cli.Get("/");
  23528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23529. EXPECT_EQ(0, s.proxy_hits());
  23530. EXPECT_EQ(1, s.target_hits());
  23531. }
  23532. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23533. ProxyAndTargetServers s;
  23534. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23535. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23536. cli.set_proxy("127.0.0.1", s.proxy_port());
  23537. cli.set_no_proxy({"::1"});
  23538. auto res = cli.Get("/");
  23539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23540. EXPECT_EQ(0, s.proxy_hits());
  23541. EXPECT_EQ(1, s.target_hits());
  23542. }
  23543. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23544. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23545. // must still be recognized as IPv6 for CIDR matching. Implementations
  23546. // that detect IPv6 only when the host begins with '[' would parse the
  23547. // host as a hostname and miss the match.
  23548. ProxyAndTargetServers s;
  23549. Client cli("fe80::1", s.target_port());
  23550. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23551. cli.set_proxy("127.0.0.1", s.proxy_port());
  23552. cli.set_no_proxy({"fe80::/10"});
  23553. auto res = cli.Get("/");
  23554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23555. EXPECT_EQ(0, s.proxy_hits());
  23556. EXPECT_EQ(1, s.target_hits());
  23557. }
  23558. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23559. ProxyAndTargetServers s;
  23560. Client cli("::1", s.target_port());
  23561. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23562. cli.set_proxy("127.0.0.1", s.proxy_port());
  23563. cli.set_no_proxy({"[::1]"});
  23564. auto res = cli.Get("/");
  23565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23566. EXPECT_EQ(0, s.proxy_hits());
  23567. EXPECT_EQ(1, s.target_hits());
  23568. }
  23569. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23570. ProxyAndTargetServers s;
  23571. Client cli("fe80::1", s.target_port());
  23572. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23573. cli.set_proxy("127.0.0.1", s.proxy_port());
  23574. cli.set_no_proxy({"[fe80::]/10"});
  23575. auto res = cli.Get("/");
  23576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23577. EXPECT_EQ(0, s.proxy_hits());
  23578. EXPECT_EQ(1, s.target_hits());
  23579. }
  23580. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23581. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23582. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23583. // tricks via address-family conversion.
  23584. ProxyAndTargetServers s;
  23585. Client cli("::ffff:127.0.0.1", s.target_port());
  23586. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23587. cli.set_proxy("127.0.0.1", s.proxy_port());
  23588. cli.set_no_proxy({"127.0.0.1"});
  23589. auto res = cli.Get("/");
  23590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23591. EXPECT_GE(s.proxy_hits(), 1);
  23592. EXPECT_EQ(0, s.target_hits());
  23593. }
  23594. TEST(NoProxyTest, IPv4CidrMatch) {
  23595. ProxyAndTargetServers s;
  23596. Client cli("127.0.0.1", s.target_port());
  23597. cli.set_proxy("127.0.0.1", s.proxy_port());
  23598. cli.set_no_proxy({"127.0.0.0/8"});
  23599. auto res = cli.Get("/");
  23600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23601. EXPECT_EQ(0, s.proxy_hits());
  23602. EXPECT_EQ(1, s.target_hits());
  23603. }
  23604. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23605. ProxyAndTargetServers s;
  23606. Client cli("127.0.0.1", s.target_port());
  23607. cli.set_proxy("127.0.0.1", s.proxy_port());
  23608. cli.set_no_proxy({"10.0.0.0/8"});
  23609. auto res = cli.Get("/");
  23610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23611. EXPECT_GE(s.proxy_hits(), 1);
  23612. EXPECT_EQ(0, s.target_hits());
  23613. }
  23614. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23615. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23616. // IPv4 target matches.
  23617. ProxyAndTargetServers s;
  23618. Client cli("127.0.0.1", s.target_port());
  23619. cli.set_proxy("127.0.0.1", s.proxy_port());
  23620. cli.set_no_proxy({"0.0.0.0/0"});
  23621. auto res = cli.Get("/");
  23622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23623. EXPECT_EQ(0, s.proxy_hits());
  23624. EXPECT_EQ(1, s.target_hits());
  23625. }
  23626. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23627. ProxyAndTargetServers s;
  23628. Client cli("127.0.0.1", s.target_port());
  23629. cli.set_proxy("127.0.0.1", s.proxy_port());
  23630. cli.set_no_proxy({"127.0.0.1"});
  23631. auto res = cli.Get("/");
  23632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23633. EXPECT_EQ(0, s.proxy_hits());
  23634. EXPECT_EQ(1, s.target_hits());
  23635. }
  23636. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23637. ProxyAndTargetServers s;
  23638. Client cli("127.0.0.1", s.target_port());
  23639. cli.set_proxy("127.0.0.1", s.proxy_port());
  23640. cli.set_no_proxy({"127.0.0.0/33"});
  23641. auto res = cli.Get("/");
  23642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23643. EXPECT_GE(s.proxy_hits(), 1);
  23644. EXPECT_EQ(0, s.target_hits());
  23645. }
  23646. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23647. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23648. ProxyAndTargetServers s;
  23649. Client cli("127.0.0.1", s.target_port());
  23650. cli.set_proxy("127.0.0.1", s.proxy_port());
  23651. cli.set_no_proxy({"127.0.0.1/"});
  23652. auto res = cli.Get("/");
  23653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23654. EXPECT_GE(s.proxy_hits(), 1);
  23655. EXPECT_EQ(0, s.target_hits());
  23656. }
  23657. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23658. ProxyAndTargetServers s;
  23659. auto cli = make_client("internal.corp", s);
  23660. cli->set_proxy_basic_auth("u", "p");
  23661. cli->set_no_proxy({"internal.corp"});
  23662. auto res = cli->Get("/");
  23663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23664. EXPECT_EQ(1, s.target_hits());
  23665. EXPECT_EQ(0, s.proxy_hits());
  23666. EXPECT_FALSE(s.last_had_proxy_authz())
  23667. << "Proxy-Authorization must not be sent direct to the target";
  23668. }
  23669. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23670. ProxyAndTargetServers s;
  23671. auto cli = make_client("public.example", s);
  23672. cli->set_proxy_basic_auth("u", "p");
  23673. cli->set_no_proxy({"internal.corp"}); // does not match
  23674. auto res = cli->Get("/");
  23675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23676. EXPECT_GE(s.proxy_hits(), 1);
  23677. EXPECT_TRUE(s.last_had_proxy_authz());
  23678. }
  23679. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23680. std::atomic<int> hits{0};
  23681. std::atomic<int> hits_with_authz{0};
  23682. no_proxy_test::ScopedServer proxy_mock;
  23683. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23684. hits++;
  23685. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23686. if (req.target.find("/redir") != std::string::npos) {
  23687. res.set_redirect("http://other.example/landed");
  23688. } else {
  23689. res.set_content("via-proxy", "text/plain");
  23690. }
  23691. });
  23692. proxy_mock.listen();
  23693. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23694. hits = 0;
  23695. hits_with_authz = 0;
  23696. Client cli("public.example", 80);
  23697. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23698. cli.set_proxy_basic_auth(c.first, c.second);
  23699. cli.set_follow_location(true);
  23700. // The redirect to another host goes through the proxy as well
  23701. auto res = cli.Get("/redir");
  23702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23703. EXPECT_EQ(2, hits.load());
  23704. EXPECT_EQ(2, hits_with_authz.load());
  23705. }
  23706. }
  23707. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23708. ProxyAndTargetServers s;
  23709. auto cli = make_client("anything.test", s);
  23710. auto res = cli->Get("/");
  23711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23712. EXPECT_GE(s.proxy_hits(), 1);
  23713. EXPECT_EQ(0, s.target_hits());
  23714. }
  23715. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23716. ProxyAndTargetServers s;
  23717. auto cli = make_client("example.com", s);
  23718. cli->set_no_proxy({"example.com:8080"});
  23719. auto res = cli->Get("/");
  23720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23721. EXPECT_GE(s.proxy_hits(), 1);
  23722. EXPECT_EQ(0, s.target_hits());
  23723. }
  23724. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23725. ProxyAndTargetServers s;
  23726. auto cli = make_client("anything.test", s);
  23727. cli->set_no_proxy({"", " ", "\t"});
  23728. auto res = cli->Get("/");
  23729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23730. EXPECT_GE(s.proxy_hits(), 1);
  23731. EXPECT_EQ(0, s.target_hits());
  23732. }
  23733. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23734. // An entry with leading/trailing whitespace must still match — env-style
  23735. // values are commonly pasted with stray spaces and an implementation
  23736. // that feeds the raw token directly to inet_pton would fail to match
  23737. // valid CIDRs because of the spaces.
  23738. ProxyAndTargetServers s;
  23739. Client cli("127.0.0.1", s.target_port());
  23740. cli.set_proxy("127.0.0.1", s.proxy_port());
  23741. cli.set_no_proxy({" 127.0.0.0/8 "});
  23742. auto res = cli.Get("/");
  23743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23744. EXPECT_EQ(0, s.proxy_hits());
  23745. EXPECT_EQ(1, s.target_hits());
  23746. }
  23747. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23748. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23749. // go direct and must NOT carry Proxy-Authorization.
  23750. std::atomic<int> proxy_hits{0};
  23751. std::atomic<int> target_hits{0};
  23752. std::atomic<bool> target_saw_authz{false};
  23753. no_proxy_test::ScopedServer proxy_mock, target;
  23754. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23755. proxy_hits++;
  23756. res.status = 302;
  23757. res.set_header("Location", "http://127.0.0.1:" +
  23758. std::to_string(target.port()) + "/landed");
  23759. });
  23760. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23761. target_hits++;
  23762. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23763. res.set_content("direct", "text/plain");
  23764. });
  23765. proxy_mock.listen();
  23766. target.listen();
  23767. Client cli("public.example", target.port());
  23768. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23769. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23770. cli.set_proxy_basic_auth("u", "p");
  23771. cli.set_no_proxy({"127.0.0.1"});
  23772. cli.set_follow_location(true);
  23773. auto res = cli.Get("/redir");
  23774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23775. EXPECT_GE(proxy_hits.load(), 1);
  23776. EXPECT_GE(target_hits.load(), 1);
  23777. EXPECT_FALSE(target_saw_authz.load());
  23778. }
  23779. #ifdef CPPHTTPLIB_SSL_ENABLED
  23780. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23781. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23782. // proxy creds would be sent to the (possibly hostile) origin.
  23783. std::atomic<int> target_hits{0};
  23784. std::atomic<bool> target_saw_proxy_authz{false};
  23785. no_proxy_test::ScopedServer target;
  23786. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23787. target_hits++;
  23788. if (req.has_header("Proxy-Authorization")) {
  23789. target_saw_proxy_authz = true;
  23790. }
  23791. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23792. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23793. "nonce=\"abc\", algorithm=MD5");
  23794. });
  23795. target.listen();
  23796. // The proxy address is set to the target's port: the bypass MUST kick in;
  23797. // if it doesn't, the test still routes "via proxy" to the same server and
  23798. // the Proxy-Authorization assertion below catches the leak.
  23799. Client cli("evil.example", target.port());
  23800. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23801. cli.set_proxy("127.0.0.1", target.port());
  23802. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23803. cli.set_no_proxy({"evil.example"});
  23804. auto res = cli.Get("/x");
  23805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23806. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23807. EXPECT_EQ(1, target_hits.load());
  23808. EXPECT_FALSE(target_saw_proxy_authz.load());
  23809. }
  23810. #endif
  23811. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23812. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23813. std::atomic<int> proxy_hits{0};
  23814. std::atomic<int> bypass_hits{0};
  23815. std::atomic<bool> proxy_saw_c_url{false};
  23816. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23817. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23818. proxy_hits++;
  23819. if (req.path.find("/start") != std::string::npos) {
  23820. res.status = 302;
  23821. res.set_header("Location", "http://127.0.0.1:" +
  23822. std::to_string(bypass_server.port()) +
  23823. "/middle");
  23824. return;
  23825. }
  23826. if (req.path.find("/end") != std::string::npos) {
  23827. proxy_saw_c_url = true;
  23828. res.set_content("c-via-proxy", "text/plain");
  23829. return;
  23830. }
  23831. res.set_content("unexpected", "text/plain");
  23832. });
  23833. // public.example's "advertised" port is arbitrary (the request never lands
  23834. // there — it goes through the proxy), but use a dynamic value to stay
  23835. // friendly with sharded parallel runs.
  23836. int public_port = bypass_server.port();
  23837. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23838. bypass_hits++;
  23839. res.status = 302;
  23840. res.set_header("Location", "http://public.example:" +
  23841. std::to_string(public_port) + "/end");
  23842. });
  23843. proxy_mock.listen();
  23844. bypass_server.listen();
  23845. Client cli("public.example", public_port);
  23846. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23847. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23848. cli.set_no_proxy({"127.0.0.1"});
  23849. cli.set_follow_location(true);
  23850. auto res = cli.Get("/start");
  23851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23852. EXPECT_EQ(StatusCode::OK_200, res->status);
  23853. EXPECT_EQ("c-via-proxy", res->body);
  23854. EXPECT_GE(proxy_hits.load(), 2);
  23855. EXPECT_GE(bypass_hits.load(), 1);
  23856. EXPECT_TRUE(proxy_saw_c_url.load());
  23857. }
  23858. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23859. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23860. // request reconnects to the correct endpoint.
  23861. std::atomic<int> proxy_hits{0};
  23862. std::atomic<int> target_hits{0};
  23863. no_proxy_test::ScopedServer proxy_mock, target;
  23864. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23865. proxy_hits++;
  23866. res.set_content("via-proxy", "text/plain");
  23867. });
  23868. target.svr().Get(".*", [&](const Request &, Response &res) {
  23869. target_hits++;
  23870. res.set_content("direct", "text/plain");
  23871. });
  23872. proxy_mock.listen();
  23873. target.listen();
  23874. Client cli("public.example", target.port());
  23875. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23876. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23877. cli.set_keep_alive(true);
  23878. auto res1 = cli.Get("/a");
  23879. ASSERT_TRUE(res1);
  23880. EXPECT_EQ("via-proxy", res1->body);
  23881. EXPECT_EQ(1, proxy_hits.load());
  23882. EXPECT_EQ(0, target_hits.load());
  23883. cli.set_no_proxy({"public.example"});
  23884. auto res2 = cli.Get("/b");
  23885. ASSERT_TRUE(res2);
  23886. EXPECT_EQ("direct", res2->body);
  23887. EXPECT_EQ(1, proxy_hits.load());
  23888. EXPECT_EQ(1, target_hits.load());
  23889. }
  23890. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23891. namespace proxy_tunnel_test {
  23892. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23893. class ScopedSSLServer {
  23894. public:
  23895. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23896. port_ = svr_.bind_to_any_port("127.0.0.1");
  23897. }
  23898. ~ScopedSSLServer() {
  23899. svr_.stop();
  23900. if (th_.joinable()) { th_.join(); }
  23901. }
  23902. SSLServer &svr() { return svr_; }
  23903. int port() const { return port_; }
  23904. void listen() {
  23905. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23906. svr_.wait_until_ready();
  23907. }
  23908. private:
  23909. SSLServer svr_;
  23910. std::thread th_;
  23911. int port_ = 0;
  23912. };
  23913. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23914. class ScopedConnectProxy {
  23915. public:
  23916. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23917. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23918. if (listen_fd_ < 0) { return; }
  23919. int yes = 1;
  23920. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23921. sockaddr_in a{};
  23922. a.sin_family = AF_INET;
  23923. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23924. a.sin_port = 0;
  23925. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23926. return;
  23927. }
  23928. socklen_t alen = sizeof(a);
  23929. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23930. 0) {
  23931. return;
  23932. }
  23933. port_ = ntohs(a.sin_port);
  23934. if (::listen(listen_fd_, 1) != 0) { return; }
  23935. th_ = std::thread([this] { run(); });
  23936. }
  23937. ~ScopedConnectProxy() {
  23938. stop_ = true;
  23939. if (listen_fd_ >= 0) {
  23940. ::shutdown(listen_fd_, SHUT_RDWR);
  23941. ::close(listen_fd_);
  23942. }
  23943. if (th_.joinable()) { th_.join(); }
  23944. }
  23945. int port() const { return port_; }
  23946. int connect_hits() const { return connect_hits_.load(); }
  23947. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23948. std::string connect_request() const {
  23949. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23950. return connect_request_;
  23951. }
  23952. private:
  23953. void run() {
  23954. while (!stop_.load()) {
  23955. fd_set rfds;
  23956. FD_ZERO(&rfds);
  23957. FD_SET(listen_fd_, &rfds);
  23958. timeval tv{0, 100 * 1000};
  23959. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23960. if (sel <= 0) { continue; }
  23961. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23962. if (client_fd < 0) { continue; }
  23963. std::string req;
  23964. char buf[2048];
  23965. while (req.find("\r\n\r\n") == std::string::npos) {
  23966. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23967. if (n <= 0) { break; }
  23968. req.append(buf, static_cast<size_t>(n));
  23969. }
  23970. if (req.compare(0, 7, "CONNECT") != 0) {
  23971. ::close(client_fd);
  23972. continue;
  23973. }
  23974. connect_hits_++;
  23975. {
  23976. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23977. connect_request_ = req;
  23978. }
  23979. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23980. ::send(client_fd, ok, std::strlen(ok), 0);
  23981. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23982. sockaddr_in o{};
  23983. o.sin_family = AF_INET;
  23984. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23985. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23986. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23987. 0) {
  23988. ::close(client_fd);
  23989. ::close(origin_fd);
  23990. continue;
  23991. }
  23992. auto forward = [](int from, int to) {
  23993. char b[8192];
  23994. for (;;) {
  23995. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23996. if (n <= 0) { break; }
  23997. ssize_t off = 0;
  23998. while (off < n) {
  23999. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24000. if (s <= 0) {
  24001. off = n;
  24002. break;
  24003. }
  24004. off += s;
  24005. }
  24006. }
  24007. ::shutdown(to, SHUT_WR);
  24008. };
  24009. std::thread t1([&] { forward(client_fd, origin_fd); });
  24010. std::thread t2([&] { forward(origin_fd, client_fd); });
  24011. t1.join();
  24012. t2.join();
  24013. ::close(client_fd);
  24014. ::close(origin_fd);
  24015. }
  24016. }
  24017. int forward_port_ = -1;
  24018. int listen_fd_ = -1;
  24019. int port_ = 0;
  24020. std::thread th_;
  24021. std::atomic<bool> stop_{false};
  24022. std::atomic<int> connect_hits_{0};
  24023. mutable std::mutex connect_request_mutex_;
  24024. std::string connect_request_;
  24025. };
  24026. // Sends one request through the CONNECT proxy to the TLS origin with a
  24027. // credential configured for each hop, and checks that each credential reaches
  24028. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24029. // origin's (every header in origin_headers) on the tunnelled request.
  24030. void CredentialsStayWithTheirHop(
  24031. const std::function<void(SSLClient &)> &set_credentials,
  24032. const std::string &scheme,
  24033. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24034. std::atomic<int> origin_hits{0};
  24035. std::atomic<bool> origin_saw_proxy_authz{false};
  24036. std::atomic<bool> origin_saw_headers{false};
  24037. ScopedSSLServer origin;
  24038. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24039. origin_hits++;
  24040. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24041. origin_saw_headers =
  24042. std::all_of(origin_headers.begin(), origin_headers.end(),
  24043. [&](const std::string &h) { return req.has_header(h); });
  24044. res.set_content("ok", "text/plain");
  24045. });
  24046. origin.listen();
  24047. ScopedConnectProxy proxy(origin.port());
  24048. ASSERT_NE(0, proxy.port());
  24049. // Pinned to 127.0.0.1 for the same reason as the test below.
  24050. SSLClient cli("127.0.0.1", origin.port());
  24051. cli.enable_server_certificate_verification(false);
  24052. cli.set_proxy("127.0.0.1", proxy.port());
  24053. set_credentials(cli);
  24054. auto res = cli.Get("/x");
  24055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24056. EXPECT_EQ(StatusCode::OK_200, res->status);
  24057. EXPECT_EQ(1, origin_hits.load());
  24058. EXPECT_EQ(1, proxy.connect_hits());
  24059. EXPECT_TRUE(origin_saw_headers.load());
  24060. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24061. << "Proxy-Authorization must not be sent inside the tunnel";
  24062. auto connect_req = proxy.connect_request();
  24063. EXPECT_NE(std::string::npos,
  24064. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24065. for (const auto &h : origin_headers) {
  24066. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24067. << h << " must not be sent to the proxy on CONNECT";
  24068. }
  24069. }
  24070. } // namespace proxy_tunnel_test
  24071. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24072. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24073. [](SSLClient &cli) {
  24074. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24075. cli.set_basic_auth("origin-user", "origin-pass");
  24076. },
  24077. "Basic");
  24078. }
  24079. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24080. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24081. [](SSLClient &cli) {
  24082. cli.set_proxy_bearer_token_auth("proxy-token");
  24083. cli.set_bearer_token_auth("origin-token");
  24084. },
  24085. "Bearer");
  24086. }
  24087. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24088. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24089. [](SSLClient &cli) {
  24090. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24091. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24092. {"Cookie", "sid=origin-session"},
  24093. {"X-Api-Key", "origin-key"}});
  24094. },
  24095. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24096. }
  24097. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24098. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24099. // retry; otherwise proxy creds would be sent to the origin.
  24100. std::atomic<int> origin_hits{0};
  24101. std::atomic<bool> origin_saw_proxy_authz{false};
  24102. proxy_tunnel_test::ScopedSSLServer origin;
  24103. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24104. origin_hits++;
  24105. if (req.has_header("Proxy-Authorization")) {
  24106. origin_saw_proxy_authz = true;
  24107. }
  24108. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24109. res.set_header("Proxy-Authenticate",
  24110. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24111. "algorithm=MD5");
  24112. });
  24113. origin.listen();
  24114. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24115. ASSERT_NE(0, proxy.port());
  24116. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24117. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24118. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24119. // and answer with its own status, making this test flaky.
  24120. SSLClient cli("127.0.0.1", origin.port());
  24121. cli.enable_server_certificate_verification(false);
  24122. cli.set_proxy("127.0.0.1", proxy.port());
  24123. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24124. auto res = cli.Get("/x");
  24125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24126. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24127. EXPECT_EQ(1, origin_hits.load());
  24128. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24129. EXPECT_EQ(1, proxy.connect_hits());
  24130. }
  24131. #endif