1
0

test.cc 949 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  396. // neighbours)
  397. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  398. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  399. }
  400. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  401. // A sign or whitespace inside the two-character escape window must not be
  402. // accepted as a valid percent-encoding; the sequence is passed through
  403. // literally, matching decode_uri_component / decode_path_component.
  404. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  405. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  406. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  407. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  408. // Well-formed escapes still decode.
  409. EXPECT_EQ("-", decode_query_component("%2D", false));
  410. EXPECT_EQ("A", decode_query_component("%41", false));
  411. }
  412. TEST(SanitizeFilenameTest, VariousPatterns) {
  413. // Path traversal
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  416. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  417. // Normal and edge cases
  418. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  419. EXPECT_EQ("filename.txt",
  420. httplib::sanitize_filename("/path/to/filename.txt"));
  421. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  422. EXPECT_EQ("", httplib::sanitize_filename(".."));
  423. EXPECT_EQ("", httplib::sanitize_filename(""));
  424. // Null bytes stripped
  425. EXPECT_EQ("safe.txt",
  426. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  427. // Whitespace-only rejected
  428. EXPECT_EQ("", httplib::sanitize_filename(" "));
  429. }
  430. // Forward declaration (see the base64_encode note below): split builds move the
  431. // definition into httplib.cc, so re-declaring it here lets the test link.
  432. namespace httplib {
  433. namespace detail {
  434. bool is_chunked_transfer_encoding(const Headers &headers);
  435. } // namespace detail
  436. } // namespace httplib
  437. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  438. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  439. auto make = [](std::initializer_list<const char *> lines) {
  440. Headers h;
  441. for (auto te : lines) {
  442. if (te) { h.emplace("Transfer-Encoding", te); }
  443. }
  444. return h;
  445. };
  446. // Sole coding, matched case-insensitively.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  450. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  454. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  459. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  460. // were received, into one list. Headers preserves that order, so the answer
  461. // is decided by the last coding of the last line and the order the lines
  462. // arrived in is significant.
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  466. // The split can fall anywhere in the list.
  467. EXPECT_TRUE(
  468. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  469. EXPECT_FALSE(
  470. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  471. // A trailing line naming no coding leaves the list ending in nothing, so it
  472. // must not inherit the chunked from the line before it.
  473. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  474. }
  475. // Forward declarations (see the base64_encode note below).
  476. namespace httplib {
  477. namespace detail {
  478. bool parse_status_line(const char *line, std::string &version, int &status,
  479. std::string &reason);
  480. std::string file_extension(const std::string &path);
  481. std::string
  482. find_content_type(const std::string &path,
  483. const std::map<std::string, std::string> &user_data,
  484. const std::string &default_content_type);
  485. bool can_compress_content_type(const std::string &content_type);
  486. bool is_prohibited_header_name(const std::string &name);
  487. #ifdef CPPHTTPLIB_SSL_ENABLED
  488. bool match_hostname(const std::string &pattern, const std::string &hostname);
  489. #endif
  490. } // namespace detail
  491. } // namespace httplib
  492. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  493. struct {
  494. const char *line;
  495. const char *version;
  496. int status;
  497. const char *reason;
  498. } cases[] = {
  499. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  500. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  501. // The reason phrase may be empty, or left out along with its space.
  502. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  503. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  504. };
  505. for (const auto &c : cases) {
  506. std::string version;
  507. int status = 0;
  508. std::string reason = "unset";
  509. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  510. << c.line;
  511. EXPECT_EQ(c.version, version);
  512. EXPECT_EQ(c.status, status);
  513. EXPECT_EQ(c.reason, reason);
  514. }
  515. }
  516. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  517. const char *lines[] = {
  518. "HTTP/2 200 OK\r\n",
  519. "HTTP/1.2 200 OK\r\n",
  520. "HTTP/1.1 20 OK\r\n",
  521. "HTTP/1.1 2000 OK\r\n",
  522. "HTTP/1.1 2x0 OK\r\n",
  523. "HTTP/1.1 200 OK\r\n",
  524. "HTTP/1.1 200OK\r\n",
  525. "HTTP/1.1 200 O\rK\r\n",
  526. "HTTP/1.1 200 OK",
  527. "HTTP/1.1 200 OK\r\nX",
  528. "",
  529. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  530. "HTTP/1.1 200 OK\n",
  531. #endif
  532. };
  533. for (auto line : lines) {
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  538. << line;
  539. }
  540. }
  541. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  542. // Long enough to overflow the stack when matched with std::regex.
  543. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  544. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  545. std::string version;
  546. int status = 0;
  547. std::string reason;
  548. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  549. EXPECT_EQ(200, status);
  550. EXPECT_EQ(long_reason, reason);
  551. }
  552. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  553. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  554. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  555. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  556. EXPECT_EQ("", detail::file_extension("noext"));
  557. EXPECT_EQ("", detail::file_extension("a."));
  558. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  559. EXPECT_EQ("", detail::file_extension("a.b-c"));
  560. // Long enough to overflow the stack when matched with std::regex.
  561. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  562. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  563. }
  564. #ifdef CPPHTTPLIB_SSL_ENABLED
  565. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  566. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  567. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  569. // A wildcard needs two labels after it, in the leftmost label only
  570. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  571. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  572. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  573. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  574. EXPECT_FALSE(
  575. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  576. // No name may have an empty label
  577. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  578. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  579. }
  580. #endif
  581. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  582. detail::case_ignore::hash hash;
  583. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  584. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  585. // Long enough to overflow the stack if hashed one call per character.
  586. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  587. }
  588. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  589. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  590. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  591. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  592. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  593. // Same 26-bit hash as html, svg and js.
  594. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  595. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  597. }
  598. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  599. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  600. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  601. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  602. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  603. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  604. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  605. // Same 26-bit hash as application/json.
  606. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  607. }
  608. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  609. Request req;
  610. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  611. EXPECT_TRUE(req.is_multipart_form_data());
  612. std::string boundary;
  613. EXPECT_TRUE(detail::parse_multipart_boundary(
  614. req.get_header_value("Content-Type"), boundary));
  615. EXPECT_EQ("x", boundary);
  616. }
  617. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  618. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  619. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  620. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  621. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  622. // Same 26-bit hash as REMOTE_ADDR.
  623. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  624. }
  625. // Forward declaration: in split builds split.py strips `inline` and moves the
  626. // definition into httplib.cc, so detail::base64_encode is not visible from the
  627. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  628. // in both header-only and split builds.
  629. namespace httplib {
  630. namespace detail {
  631. std::string base64_encode(const std::string &in);
  632. } // namespace detail
  633. } // namespace httplib
  634. TEST(Base64EncodeTest, KnownAnswers) {
  635. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  636. // where the accumulator's top bit is already set before the next shift.
  637. EXPECT_EQ("", detail::base64_encode(""));
  638. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  639. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  640. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  641. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  642. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  643. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  644. // High bytes keep the top bit set across several rounds.
  645. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  646. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  647. }
  648. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  649. string unescapedCharacters = "-_.!~*'()";
  650. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  651. }
  652. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  653. string reservedCharacters = ";,/?:@&=+$";
  654. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  655. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  656. }
  657. TEST(ClientQueryOrder, PreserveOrder) {
  658. // This test reproduces Issue #2259: client may reorder query parameters
  659. // when sending a GET request. The expected behavior is that the client
  660. // preserves the original query string order when the caller supplied it
  661. // as part of the path.
  662. Server svr;
  663. svr.Get("/", [&](const Request &req, Response &res) {
  664. // Echo back the raw target so the test can assert ordering
  665. res.set_content(req.target, "text/plain");
  666. });
  667. std::thread t{[&] { svr.listen(HOST, PORT); }};
  668. auto se = detail::scope_exit([&] {
  669. svr.stop();
  670. t.join();
  671. ASSERT_FALSE(svr.is_running());
  672. });
  673. svr.wait_until_ready();
  674. Client cli(HOST, PORT);
  675. ASSERT_TRUE(cli.is_valid());
  676. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  677. auto res = cli.Get(original);
  678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  679. // Expect the echoed target to exactly match the original path (order
  680. // preserved)
  681. EXPECT_EQ(res->body, original);
  682. }
  683. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  684. string chineseCharacters = U8("中国語");
  685. string russianCharacters = U8("дом");
  686. string brazilianCharacters = U8("óculos");
  687. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  688. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  689. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  690. "%D0%B4%D0%BE%D0%BC");
  691. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  692. }
  693. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  694. string unescapedCharacters = "-_.!~*'()";
  695. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  696. }
  697. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  698. string reservedCharacters = ";,/?:@&=+$";
  699. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  700. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  701. }
  702. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  703. string chineseCharacters = U8("中国語");
  704. string russianCharacters = U8("дом");
  705. string brazilianCharacters = U8("óculos");
  706. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  707. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  708. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  709. "%D0%B4%D0%BE%D0%BC");
  710. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  711. }
  712. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  713. // Issue #2082 use case: encoding path component with ampersand
  714. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  715. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  716. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  717. }
  718. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  723. string reservedCharacters = ";,/?:@&=+$#";
  724. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  725. }
  726. TEST(EncodeUriTest, TestUTF8Characters) {
  727. string chineseCharacters = U8("中国語");
  728. string russianCharacters = U8("дом");
  729. string brazilianCharacters = U8("óculos");
  730. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  731. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  732. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  733. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  734. }
  735. TEST(EncodeUriTest, TestCompleteUri) {
  736. string uri =
  737. "https://example.com/path/to/resource?query=value&param=test#fragment";
  738. EXPECT_EQ(
  739. httplib::encode_uri(uri),
  740. "https://example.com/path/to/resource?query=value&param=test#fragment");
  741. }
  742. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  743. string uri =
  744. "https://example.com/path with spaces/file name.html?q=hello world";
  745. EXPECT_EQ(httplib::encode_uri(uri),
  746. "https://example.com/path%20with%20spaces/"
  747. "file%20name.html?q=hello%20world");
  748. }
  749. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  750. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  751. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  752. }
  753. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  754. string unescapedCharacters = "-_.!~*'()";
  755. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  756. }
  757. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  758. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  759. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  760. string encodedBrazilian = "%C3%B3culos";
  761. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  762. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  763. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  764. }
  765. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  766. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  767. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  768. "Piri Tommy Villiers - on & on");
  769. }
  770. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  771. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  772. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  773. }
  774. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  775. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  776. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  777. }
  778. TEST(DecodeUriTest, TestUTF8Characters) {
  779. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  780. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  781. string encodedBrazilian = "%C3%B3culos";
  782. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  783. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  784. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  785. }
  786. TEST(DecodeUriTest, TestCompleteUri) {
  787. string encodedUri = "https://example.com/path%20with%20spaces/"
  788. "file%20name.html?q=hello%20world";
  789. EXPECT_EQ(
  790. httplib::decode_uri(encodedUri),
  791. "https://example.com/path with spaces/file name.html?q=hello world");
  792. }
  793. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  794. string original =
  795. "https://example.com/path with spaces/file name.html?q=hello world";
  796. string encoded = httplib::encode_uri(original);
  797. string decoded = httplib::decode_uri(encoded);
  798. EXPECT_EQ(decoded, original);
  799. }
  800. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  801. // decode_uri is the inverse of encode_uri: an escaped reserved character
  802. // stays encoded so it is not promoted into a real delimiter, while
  803. // non-reserved escapes still decode (like JS decodeURI).
  804. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  805. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  806. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  807. "%3F%3A%40%26%3D%2B%24%2C%3B");
  808. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  809. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  810. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  811. "http://example.com/a%2Fb");
  812. // decode_uri_component still decodes the reserved character.
  813. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  814. }
  815. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  816. string original = "Piri Tommy Villiers - on & on";
  817. string encoded = httplib::encode_uri_component(original);
  818. string decoded = httplib::decode_uri_component(encoded);
  819. EXPECT_EQ(decoded, original);
  820. }
  821. TEST(TrimTests, TrimStringTests) {
  822. EXPECT_EQ("abc", detail::trim_copy("abc"));
  823. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  824. EXPECT_TRUE(detail::trim_copy("").empty());
  825. }
  826. TEST(AsciiTest, LocaleIndependentClassification) {
  827. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  828. // which consult the global C locale: std::isalnum(0xC5) can return true
  829. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  830. // helpers must classify every byte by the ASCII grammar alone.
  831. for (int i = 0; i < 256; i++) {
  832. auto c = static_cast<char>(i);
  833. auto is_digit = i >= '0' && i <= '9';
  834. auto is_upper = i >= 'A' && i <= 'Z';
  835. auto is_lower = i >= 'a' && i <= 'z';
  836. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  837. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  838. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  839. << "byte " << i;
  840. }
  841. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  842. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  843. // Non-ASCII bytes must be percent-encoded, never passed through as
  844. // alphanumeric.
  845. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  846. }
  847. TEST(FromCharsTest, Double) {
  848. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  849. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  850. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  851. auto parse = [](const std::string &s, double &v) {
  852. return detail::from_chars(s.data(), s.data() + s.size(), v);
  853. };
  854. double v = -1.0;
  855. // Representative quality values.
  856. EXPECT_EQ(parse("0", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 0.0);
  858. EXPECT_EQ(parse("1", v).ec, std::errc{});
  859. EXPECT_DOUBLE_EQ(v, 1.0);
  860. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.8);
  862. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 0.001);
  864. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 1.0);
  866. // A missing integer or fractional part is tolerated.
  867. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 0.5);
  869. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  870. EXPECT_DOUBLE_EQ(v, 5.0);
  871. // Values outside [0, 1] still parse; the caller range-checks them.
  872. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 123.456);
  874. // Stops at the first byte that is not part of the number and reports where.
  875. std::string trailing = "0.9, text/html";
  876. auto r = parse(trailing, v);
  877. EXPECT_EQ(r.ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.9);
  879. EXPECT_EQ(*r.ptr, ',');
  880. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  881. // outright, and an 'e'/'E' simply ends the number.
  882. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  883. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  884. std::string exp_input = "1.5e3";
  885. r = parse(exp_input, v);
  886. EXPECT_EQ(r.ec, std::errc{});
  887. EXPECT_DOUBLE_EQ(v, 1.5);
  888. EXPECT_EQ(*r.ptr, 'e');
  889. // Invalid inputs.
  890. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  891. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  892. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  895. // Pathological but well-formed inputs must stay bounded (no overflow, no
  896. // out-of-bounds table access) and stay within [0, 1] for the caller.
  897. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  898. std::errc{});
  899. EXPECT_DOUBLE_EQ(v, 0.0);
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  901. std::errc{});
  902. EXPECT_GE(v, 0.0);
  903. EXPECT_LE(v, 1.0);
  904. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  905. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  906. }
  907. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  908. // Simple case without quality values
  909. std::vector<std::string> result1;
  910. EXPECT_TRUE(detail::parse_accept_header(
  911. "text/html,application/json,text/plain", result1));
  912. EXPECT_EQ(result1.size(), 3U);
  913. EXPECT_EQ(result1[0], "text/html");
  914. EXPECT_EQ(result1[1], "application/json");
  915. EXPECT_EQ(result1[2], "text/plain");
  916. // With quality values
  917. std::vector<std::string> result2;
  918. EXPECT_TRUE(detail::parse_accept_header(
  919. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  920. EXPECT_EQ(result2.size(), 3U);
  921. EXPECT_EQ(result2[0], "application/json"); // highest q value
  922. EXPECT_EQ(result2[1], "text/html");
  923. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  924. }
  925. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  926. // Mixed with and without quality values
  927. std::vector<std::string> result;
  928. EXPECT_TRUE(detail::parse_accept_header(
  929. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  930. EXPECT_EQ(result.size(), 3U);
  931. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  932. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  933. EXPECT_EQ(result[2], "application/json"); // q=0.5
  934. }
  935. TEST(ParseAcceptHeaderTest, EdgeCases) {
  936. // Empty header
  937. std::vector<std::string> empty_result;
  938. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  939. EXPECT_TRUE(empty_result.empty());
  940. // Single type
  941. std::vector<std::string> single_result;
  942. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  943. EXPECT_EQ(single_result.size(), 1U);
  944. EXPECT_EQ(single_result[0], "application/json");
  945. // Wildcard types
  946. std::vector<std::string> wildcard_result;
  947. EXPECT_TRUE(detail::parse_accept_header(
  948. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  949. EXPECT_EQ(wildcard_result.size(), 3U);
  950. EXPECT_EQ(wildcard_result[0], "application/json");
  951. EXPECT_EQ(wildcard_result[1], "text/*");
  952. EXPECT_EQ(wildcard_result[2], "*/*");
  953. }
  954. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  955. // Common browser Accept header
  956. std::vector<std::string> browser_result;
  957. EXPECT_TRUE(
  958. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  959. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  960. browser_result));
  961. EXPECT_EQ(browser_result.size(), 6U);
  962. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  963. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  964. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  965. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  967. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  968. // API client header
  969. std::vector<std::string> api_result;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  972. api_result));
  973. EXPECT_EQ(api_result.size(), 3U);
  974. EXPECT_EQ(api_result[0], "application/json");
  975. EXPECT_EQ(api_result[1], "application/xml");
  976. EXPECT_EQ(api_result[2], "text/plain");
  977. }
  978. TEST(ParseAcceptHeaderTest, SpecialCases) {
  979. // Quality value with 3 decimal places
  980. std::vector<std::string> decimal_result;
  981. EXPECT_TRUE(detail::parse_accept_header(
  982. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  983. EXPECT_EQ(decimal_result.size(), 2U);
  984. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  985. EXPECT_EQ(decimal_result[1], "text/html");
  986. // Zero quality (should still be included but with lowest priority)
  987. std::vector<std::string> zero_q_result;
  988. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  989. zero_q_result));
  990. EXPECT_EQ(zero_q_result.size(), 2U);
  991. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  992. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  993. // No spaces around commas
  994. std::vector<std::string> no_space_result;
  995. EXPECT_TRUE(detail::parse_accept_header(
  996. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  997. no_space_result));
  998. EXPECT_EQ(no_space_result.size(), 3U);
  999. EXPECT_EQ(no_space_result[0], "text/html");
  1000. EXPECT_EQ(no_space_result[1], "application/json");
  1001. EXPECT_EQ(no_space_result[2], "text/plain");
  1002. }
  1003. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1004. // Quality values always use '.' as the decimal separator, so parsing must
  1005. // not depend on the process locale. An embedding application may have
  1006. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1007. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1008. std::string saved = cur ? cur : "C";
  1009. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1010. "fr_FR.UTF-8"};
  1011. bool switched = false;
  1012. for (const auto loc : comma_locales) {
  1013. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1014. std::localeconv()->decimal_point[0] == ',') {
  1015. switched = true;
  1016. break;
  1017. }
  1018. }
  1019. if (!switched) {
  1020. std::setlocale(LC_NUMERIC, saved.c_str());
  1021. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1022. }
  1023. // The higher-weighted type appears later in the list, so a correct parse
  1024. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1025. // sensitive parse reads both weights as 0 and leaves the original order.
  1026. std::vector<std::string> result;
  1027. EXPECT_TRUE(detail::parse_accept_header(
  1028. "application/json;q=0.1,text/html;q=0.9", result));
  1029. ASSERT_EQ(result.size(), 2U);
  1030. EXPECT_EQ(result[0], "text/html");
  1031. EXPECT_EQ(result[1], "application/json");
  1032. std::setlocale(LC_NUMERIC, saved.c_str());
  1033. }
  1034. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1035. std::vector<std::string> result;
  1036. // Invalid quality value (> 1.0)
  1037. EXPECT_FALSE(
  1038. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1039. // Invalid quality value (< 0.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1042. // Invalid quality value (not a number)
  1043. EXPECT_FALSE(detail::parse_accept_header(
  1044. "text/html;q=invalid,application/json", result));
  1045. // A valid numeric prefix does not make the entire quality value valid.
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=0.5junk,application/json", result));
  1048. // Empty quality value
  1049. EXPECT_FALSE(
  1050. detail::parse_accept_header("text/html;q=,application/json", result));
  1051. // Invalid media type format (no slash and not wildcard)
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("invalidtype,application/json", result));
  1054. // Valid cases should still work
  1055. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1056. EXPECT_EQ(result.size(), 1U);
  1057. EXPECT_EQ(result[0], "*/*");
  1058. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*");
  1061. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "text/*");
  1064. }
  1065. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1066. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1067. // and must not be answered with 400 Bad Request.
  1068. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1069. struct {
  1070. const char *value;
  1071. std::vector<std::string> expected;
  1072. } cases[] = {
  1073. {",application/json", {"application/json"}},
  1074. {"text/html,", {"text/html"}},
  1075. {"text/html,,*/*", {"text/html", "*/*"}},
  1076. // An empty element may be spelled with whitespace in it
  1077. {"text/html, , application/json", {"text/html", "application/json"}},
  1078. // Nothing but empty elements is an empty list, which means the same
  1079. // thing as no Accept header at all
  1080. {",,,", {}},
  1081. // Quality values still apply across ignored empty elements
  1082. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1083. };
  1084. for (const auto &c : cases) {
  1085. std::vector<std::string> result;
  1086. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1087. << "value: " << c.value;
  1088. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1089. }
  1090. // An invalid entry is still rejected when empty elements surround it
  1091. std::vector<std::string> result;
  1092. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1093. }
  1094. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1095. // or ';' inside one does not end the list element or the parameter. Section
  1096. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1097. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1098. struct {
  1099. const char *value;
  1100. std::vector<std::string> expected;
  1101. } cases[] = {
  1102. {"text/html;profile=\"a,b\",application/json",
  1103. {"text/html", "application/json"}},
  1104. // A "q=" inside a quoted value is not the weight
  1105. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1106. {"text/html", "application/json"}},
  1107. // The weight after a quoted value still applies
  1108. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1109. {"application/json", "text/html"}},
  1110. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1111. {"application/json", "text/html"}},
  1112. {"text/html;profile=\"a\\\"b\",application/json",
  1113. {"text/html", "application/json"}},
  1114. // An escaped backslash does not escape the '"' after it
  1115. {"text/html;profile=\"a\\\\\",application/json",
  1116. {"text/html", "application/json"}},
  1117. };
  1118. for (const auto &c : cases) {
  1119. std::vector<std::string> result;
  1120. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1121. << "value: " << c.value;
  1122. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1123. }
  1124. }
  1125. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1126. Server svr;
  1127. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1128. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1129. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1130. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1131. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1132. res.set_content("ok", "text/plain");
  1133. });
  1134. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1135. EXPECT_TRUE(false);
  1136. res.set_content("bad request", "text/plain");
  1137. });
  1138. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1139. auto se = detail::scope_exit([&] {
  1140. svr.stop();
  1141. listen_thread.join();
  1142. ASSERT_FALSE(svr.is_running());
  1143. });
  1144. svr.wait_until_ready();
  1145. Client cli("localhost", PORT);
  1146. {
  1147. auto res = cli.Get(
  1148. "/accept_ok",
  1149. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1151. EXPECT_EQ(StatusCode::OK_200, res->status);
  1152. }
  1153. {
  1154. auto res = cli.Get("/accept_bad_request",
  1155. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1157. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1158. }
  1159. }
  1160. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1161. Server svr;
  1162. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1163. res.set_content("ok", "text/plain");
  1164. });
  1165. std::atomic<int> start_count{0};
  1166. std::atomic<bool> running_when_called{false};
  1167. svr.set_start_handler([&]() {
  1168. running_when_called = svr.is_running();
  1169. start_count++;
  1170. });
  1171. auto port = svr.bind_to_any_port(HOST);
  1172. std::thread t([&]() { svr.listen_after_bind(); });
  1173. auto se = detail::scope_exit([&] {
  1174. svr.stop();
  1175. t.join();
  1176. ASSERT_FALSE(svr.is_running());
  1177. });
  1178. svr.wait_until_ready();
  1179. // A successful request proves the accept loop is running, which the start
  1180. // handler precedes; so by now the handler must have run exactly once.
  1181. Client cli(HOST, port);
  1182. cli.set_connection_timeout(std::chrono::seconds(5));
  1183. auto res = cli.Get("/");
  1184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1185. EXPECT_EQ(StatusCode::OK_200, res->status);
  1186. EXPECT_EQ(1, start_count.load());
  1187. EXPECT_TRUE(running_when_called.load());
  1188. }
  1189. TEST(DivideTest, DivideStringTests) {
  1190. auto divide = [](const std::string &str, char d) {
  1191. std::string lhs;
  1192. std::string rhs;
  1193. detail::divide(str, d,
  1194. [&](const char *lhs_data, std::size_t lhs_size,
  1195. const char *rhs_data, std::size_t rhs_size) {
  1196. lhs.assign(lhs_data, lhs_size);
  1197. rhs.assign(rhs_data, rhs_size);
  1198. });
  1199. return std::make_pair(std::move(lhs), std::move(rhs));
  1200. };
  1201. {
  1202. const auto res = divide("", '=');
  1203. EXPECT_EQ(res.first, "");
  1204. EXPECT_EQ(res.second, "");
  1205. }
  1206. {
  1207. const auto res = divide("=", '=');
  1208. EXPECT_EQ(res.first, "");
  1209. EXPECT_EQ(res.second, "");
  1210. }
  1211. {
  1212. const auto res = divide(" ", '=');
  1213. EXPECT_EQ(res.first, " ");
  1214. EXPECT_EQ(res.second, "");
  1215. }
  1216. {
  1217. const auto res = divide("a", '=');
  1218. EXPECT_EQ(res.first, "a");
  1219. EXPECT_EQ(res.second, "");
  1220. }
  1221. {
  1222. const auto res = divide("a=", '=');
  1223. EXPECT_EQ(res.first, "a");
  1224. EXPECT_EQ(res.second, "");
  1225. }
  1226. {
  1227. const auto res = divide("=b", '=');
  1228. EXPECT_EQ(res.first, "");
  1229. EXPECT_EQ(res.second, "b");
  1230. }
  1231. {
  1232. const auto res = divide("a=b", '=');
  1233. EXPECT_EQ(res.first, "a");
  1234. EXPECT_EQ(res.second, "b");
  1235. }
  1236. {
  1237. const auto res = divide("a=b=", '=');
  1238. EXPECT_EQ(res.first, "a");
  1239. EXPECT_EQ(res.second, "b=");
  1240. }
  1241. {
  1242. const auto res = divide("a=b=c", '=');
  1243. EXPECT_EQ(res.first, "a");
  1244. EXPECT_EQ(res.second, "b=c");
  1245. }
  1246. }
  1247. TEST(SplitTest, ParseQueryString) {
  1248. string s = "key1=val1&key2=val2&key3=val3";
  1249. Params dic;
  1250. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1251. [&](const char *b, const char *e) {
  1252. string key, val;
  1253. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1254. if (key.empty()) {
  1255. key.assign(b2, e2);
  1256. } else {
  1257. val.assign(b2, e2);
  1258. }
  1259. });
  1260. dic.emplace(key, val);
  1261. });
  1262. EXPECT_EQ("val1", dic.find("key1")->second);
  1263. EXPECT_EQ("val2", dic.find("key2")->second);
  1264. EXPECT_EQ("val3", dic.find("key3")->second);
  1265. }
  1266. TEST(SplitTest, ParseInvalidQueryTests) {
  1267. {
  1268. string s = " ";
  1269. Params dict;
  1270. detail::parse_query_text(s, dict);
  1271. EXPECT_TRUE(dict.empty());
  1272. }
  1273. {
  1274. string s = " = =";
  1275. Params dict;
  1276. detail::parse_query_text(s, dict);
  1277. EXPECT_TRUE(dict.empty());
  1278. }
  1279. }
  1280. TEST(ParseQueryTest, ParseQueryString) {
  1281. {
  1282. std::string s = "key1=val1&key2=val2&key3=val3";
  1283. Params dic;
  1284. detail::parse_query_text(s, dic);
  1285. EXPECT_EQ("val1", dic.find("key1")->second);
  1286. EXPECT_EQ("val2", dic.find("key2")->second);
  1287. EXPECT_EQ("val3", dic.find("key3")->second);
  1288. }
  1289. {
  1290. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1291. Params dic;
  1292. detail::parse_query_text(s, dic);
  1293. EXPECT_EQ("", dic.find("key1")->second);
  1294. EXPECT_EQ("val1", dic.find("key2")->second);
  1295. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1296. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1297. }
  1298. }
  1299. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1300. Params dic;
  1301. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1302. dic.emplace("key1", "val1");
  1303. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1304. dic.emplace("key2", "val2");
  1305. dic.emplace("key3", "val3");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1307. }
  1308. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1309. Params params;
  1310. params.emplace("a", "1");
  1311. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1312. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1313. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1314. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1315. // Long enough to overflow the stack when matched with std::regex.
  1316. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1317. EXPECT_EQ("/p?" + long_query + "&a=1",
  1318. append_query_params("/p?" + long_query, params));
  1319. }
  1320. // Joins every entry of a Headers or Params into "key=value " so a whole
  1321. // traversal can be compared in one assertion. Both are instantiations of the
  1322. // same insertion-ordered container, so one helper serves both.
  1323. template <typename Map> static std::string entries_to_string(const Map &m) {
  1324. std::string s;
  1325. for (const auto &entry : m) {
  1326. s += entry.first + "=" + entry.second + " ";
  1327. }
  1328. return s;
  1329. }
  1330. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1331. // Params used to be a std::multimap, which sorted by name and handed the
  1332. // caller's query back alphabetised. A client signing its query string could
  1333. // not reproduce the order it asked for.
  1334. Params dic;
  1335. dic.emplace("zulu", "1");
  1336. dic.emplace("alpha", "2");
  1337. dic.emplace("mike", "3");
  1338. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1339. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1340. }
  1341. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1342. Params dic;
  1343. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1344. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1345. }
  1346. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1347. Request req;
  1348. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1349. req.params);
  1350. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1351. EXPECT_EQ("first", req.get_param_value("tag"));
  1352. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1353. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1354. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1355. EXPECT_EQ("", req.get_param_value("tag", 3));
  1356. }
  1357. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1358. // Params shares its container with Headers, which matches field names
  1359. // case-insensitively. Parameter names must not pick that up.
  1360. Params dic;
  1361. dic.emplace("Key", "upper");
  1362. dic.emplace("key", "lower");
  1363. EXPECT_EQ(2U, dic.size());
  1364. EXPECT_EQ(1U, dic.count("Key"));
  1365. EXPECT_EQ(1U, dic.count("key"));
  1366. EXPECT_EQ("upper", dic.find("Key")->second);
  1367. EXPECT_EQ("lower", dic.find("key")->second);
  1368. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1369. }
  1370. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1371. Server svr;
  1372. std::string order;
  1373. svr.Get("/order", [&](const Request &req, Response &res) {
  1374. order = entries_to_string(req.params);
  1375. res.set_content("ok", "text/plain");
  1376. });
  1377. auto port = svr.bind_to_any_port(HOST);
  1378. thread t = thread([&] { svr.listen_after_bind(); });
  1379. auto se = detail::scope_exit([&] {
  1380. svr.stop();
  1381. t.join();
  1382. ASSERT_FALSE(svr.is_running());
  1383. });
  1384. svr.wait_until_ready();
  1385. Client cli(HOST, port);
  1386. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1387. ASSERT_TRUE(res);
  1388. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1389. }
  1390. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1391. Server svr;
  1392. std::string field_order, file_order;
  1393. svr.Post("/order", [&](const Request &req, Response &res) {
  1394. for (const auto &field : req.form.fields) {
  1395. field_order += field.first + "=" + field.second.content + " ";
  1396. }
  1397. for (const auto &file : req.form.files) {
  1398. file_order += file.first + "=" + file.second.filename + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. UploadFormDataItems items = {
  1411. {"zulu", "1", "", ""},
  1412. {"alpha", "2", "", ""},
  1413. {"mike", "3", "", ""},
  1414. {"zebra", "z", "z.txt", "text/plain"},
  1415. {"apple", "a", "a.txt", "text/plain"},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/order", items);
  1419. ASSERT_TRUE(res);
  1420. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1421. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1422. }
  1423. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1424. Server svr;
  1425. std::vector<std::string> values;
  1426. std::string first, second, out_of_range, order;
  1427. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1428. values = req.form.get_fields("tag");
  1429. first = req.form.get_field("tag", 0);
  1430. second = req.form.get_field("tag", 1);
  1431. out_of_range = req.form.get_field("tag", 2);
  1432. for (const auto &field : req.form.fields) {
  1433. order += field.first + "=" + field.second.content + " ";
  1434. }
  1435. res.set_content("ok", "text/plain");
  1436. });
  1437. auto port = svr.bind_to_any_port(HOST);
  1438. thread t = thread([&] { svr.listen_after_bind(); });
  1439. auto se = detail::scope_exit([&] {
  1440. svr.stop();
  1441. t.join();
  1442. ASSERT_FALSE(svr.is_running());
  1443. });
  1444. svr.wait_until_ready();
  1445. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1446. // not adjacent in the container.
  1447. UploadFormDataItems items = {
  1448. {"tag", "first", "", ""},
  1449. {"other", "x", "", ""},
  1450. {"tag", "second", "", ""},
  1451. };
  1452. Client cli(HOST, port);
  1453. auto res = cli.Post("/repeated", items);
  1454. ASSERT_TRUE(res);
  1455. ASSERT_EQ(2U, values.size());
  1456. EXPECT_EQ("first", values[0]);
  1457. EXPECT_EQ("second", values[1]);
  1458. EXPECT_EQ("first", first);
  1459. EXPECT_EQ("second", second);
  1460. // std::multimap already kept entries sharing a name in insertion order, so
  1461. // everything above passes without this change too. The whole traversal is
  1462. // what tells the two apart: sorting by name would hoist "other" to the front
  1463. // and the two "tag" parts would end up adjacent.
  1464. EXPECT_EQ("tag=first other=x tag=second ", order);
  1465. // Advancing past the last entry of a name used to run off the container;
  1466. // the container's saturating increment makes it return the default instead.
  1467. EXPECT_EQ("", out_of_range);
  1468. }
  1469. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1470. // Server::read_content() keeps a FormFields::iterator alive across the
  1471. // content callbacks that fill the part it points at. The container is
  1472. // vector-backed, so a later emplace can reallocate and invalidate an older
  1473. // iterator; 64 parts grow the vector through seven reallocations, which
  1474. // checks that every part's content still lands in its own entry.
  1475. const size_t part_count = 64;
  1476. // One formula for both the parts sent and the values expected back, so the
  1477. // two cannot drift apart.
  1478. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1479. auto content_of = [](size_t i) {
  1480. return std::string(64, static_cast<char>('a' + (i % 26)));
  1481. };
  1482. Server svr;
  1483. std::vector<std::pair<std::string, std::string>> received;
  1484. svr.Post("/many", [&](const Request &req, Response &res) {
  1485. for (const auto &field : req.form.fields) {
  1486. received.emplace_back(field.first, field.second.content);
  1487. }
  1488. res.set_content("ok", "text/plain");
  1489. });
  1490. auto port = svr.bind_to_any_port(HOST);
  1491. thread t = thread([&] { svr.listen_after_bind(); });
  1492. auto se = detail::scope_exit([&] {
  1493. svr.stop();
  1494. t.join();
  1495. ASSERT_FALSE(svr.is_running());
  1496. });
  1497. svr.wait_until_ready();
  1498. UploadFormDataItems items;
  1499. for (size_t i = 0; i < part_count; i++) {
  1500. items.push_back({name_of(i), content_of(i), "", ""});
  1501. }
  1502. Client cli(HOST, port);
  1503. auto res = cli.Post("/many", items);
  1504. ASSERT_TRUE(res);
  1505. ASSERT_EQ(part_count, received.size());
  1506. for (size_t i = 0; i < part_count; i++) {
  1507. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1508. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1509. }
  1510. }
  1511. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1512. string content_type = "multipart/form-data; boundary=something";
  1513. string boundary;
  1514. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1515. EXPECT_TRUE(ret);
  1516. EXPECT_EQ(boundary, "something");
  1517. }
  1518. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1519. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1520. string boundary;
  1521. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1522. EXPECT_TRUE(ret);
  1523. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1524. }
  1525. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1526. string content_type =
  1527. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1528. string boundary;
  1529. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1530. EXPECT_TRUE(ret);
  1531. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1532. }
  1533. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1534. string content_type =
  1535. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1536. string boundary;
  1537. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1538. EXPECT_TRUE(ret);
  1539. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1542. const string boundary(70, 'a');
  1543. string content_type = "multipart/form-data; boundary=" + boundary;
  1544. string parsed;
  1545. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(parsed, boundary);
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1550. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1551. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1552. string parsed;
  1553. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1554. EXPECT_FALSE(ret);
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1557. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1558. // is 72 characters on the wire and still valid.
  1559. const string boundary(70, 'a');
  1560. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1561. string parsed;
  1562. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1563. EXPECT_EQ(parsed, boundary);
  1564. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1565. parsed.clear();
  1566. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1567. }
  1568. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1569. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1570. // The parameter parser must not treat that '=' as the key/value separator.
  1571. string content_type =
  1572. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1573. "charset=UTF-8";
  1574. string parsed;
  1575. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1576. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1577. }
  1578. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1579. // A ';' inside the quoted-string is part of the value, not a parameter
  1580. // separator, so it must not truncate the boundary.
  1581. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1582. string parsed;
  1583. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1584. EXPECT_EQ(parsed, "a;b");
  1585. }
  1586. TEST(ParseDispositionParamsTest, QuotedValues) {
  1587. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1588. // ';' and '=' are ordinary characters inside one.
  1589. struct {
  1590. const char *value;
  1591. std::vector<std::pair<const char *, const char *>> expected;
  1592. } cases[] = {
  1593. {"name=\"file1\"; filename=\"a.txt\"",
  1594. {{"name", "file1"}, {"filename", "a.txt"}}},
  1595. // Whitespace around '=' and ';' is still trimmed
  1596. {"name=\"file2\" ;filename = \"a.html\"",
  1597. {{"name", "file2"}, {"filename", "a.html"}}},
  1598. // '=' inside the value used to leave only the text after the last one
  1599. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1600. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1601. {"name=\"x=y\"", {{"name", "x=y"}}},
  1602. // ';' inside the value used to truncate the pair and leave a bogus one
  1603. {"name=\"file3\"; filename=\"a;b.txt\"",
  1604. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1605. // An unquoted value keeps working, and so does filename*
  1606. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1607. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1608. // A parameter with no key is dropped rather than turned into one whose
  1609. // key is the value
  1610. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1611. // An escaped quote does not end the value
  1612. {"name=\"a\\\"; filename=evil.php\"",
  1613. {{"name", "a\"; filename=evil.php"}}},
  1614. // Other backslashes, as in a Windows path, are kept
  1615. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1616. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1617. };
  1618. for (const auto &c : cases) {
  1619. Params params;
  1620. detail::parse_disposition_params(c.value, params);
  1621. for (const auto &kv : c.expected) {
  1622. auto it = params.find(kv.first);
  1623. ASSERT_NE(it, params.end())
  1624. << "value: " << c.value << ", key: " << kv.first;
  1625. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1626. }
  1627. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1628. }
  1629. }
  1630. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1631. Server svr;
  1632. std::string filename;
  1633. std::string content;
  1634. svr.Post("/upload", [&](const Request &req, Response &) {
  1635. const auto &file = req.form.get_file("file");
  1636. filename = file.filename;
  1637. content = file.content;
  1638. });
  1639. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1640. auto se = detail::scope_exit([&] {
  1641. svr.stop();
  1642. thread.join();
  1643. ASSERT_FALSE(svr.is_running());
  1644. });
  1645. svr.wait_until_ready();
  1646. std::string body = "--B\r\n"
  1647. "Content-Disposition: form-data; name=\"file\"; "
  1648. "filename=\"a.txt\"\r\n"
  1649. "Content-Type: text/plain\r\n"
  1650. "\r\n"
  1651. "hello\r\n"
  1652. "--B--\r\n";
  1653. Client cli(HOST, PORT);
  1654. auto res = cli.Post(
  1655. "/upload",
  1656. [&](size_t offset, DataSink &sink) {
  1657. if (offset < body.size()) {
  1658. sink.write(&body[offset], 1);
  1659. } else {
  1660. sink.done();
  1661. }
  1662. return true;
  1663. },
  1664. "multipart/form-data; boundary=B");
  1665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1666. EXPECT_EQ(StatusCode::OK_200, res->status);
  1667. EXPECT_EQ("a.txt", filename);
  1668. EXPECT_EQ("hello", content);
  1669. }
  1670. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1671. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1672. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1673. Server svr;
  1674. std::string field_value, file_name, file_filename;
  1675. bool has_field = false, has_file = false;
  1676. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1677. has_field = req.form.has_field("x=y");
  1678. field_value = req.form.get_field("x=y");
  1679. has_file = req.form.has_file("file1");
  1680. const auto &file = req.form.get_file("file1");
  1681. file_name = file.name;
  1682. file_filename = file.filename;
  1683. res.set_content("ok", "text/plain");
  1684. });
  1685. auto port = svr.bind_to_any_port(HOST);
  1686. thread t = thread([&] { svr.listen_after_bind(); });
  1687. auto se = detail::scope_exit([&] {
  1688. svr.stop();
  1689. t.join();
  1690. ASSERT_FALSE(svr.is_running());
  1691. });
  1692. svr.wait_until_ready();
  1693. UploadFormDataItems items = {
  1694. {"x=y", "field-value", "", ""},
  1695. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1696. };
  1697. Client cli(HOST, port);
  1698. auto res = cli.Post("/quoted", items);
  1699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1700. ASSERT_EQ(StatusCode::OK_200, res->status);
  1701. EXPECT_TRUE(has_field);
  1702. EXPECT_EQ("field-value", field_value);
  1703. EXPECT_TRUE(has_file);
  1704. EXPECT_EQ("file1", file_name);
  1705. EXPECT_EQ("a;b=report.pdf", file_filename);
  1706. }
  1707. TEST(GetHeaderValueTest, DefaultValue) {
  1708. Headers headers = {{"Dummy", "Dummy"}};
  1709. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1710. EXPECT_STREQ("text/plain", val);
  1711. }
  1712. TEST(GetHeaderValueTest, DefaultValueInt) {
  1713. Headers headers = {{"Dummy", "Dummy"}};
  1714. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1715. EXPECT_EQ(100ull, val);
  1716. }
  1717. TEST(GetHeaderValueTest, RegularValue) {
  1718. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1719. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1720. EXPECT_STREQ("text/html", val);
  1721. }
  1722. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1723. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1724. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1725. EXPECT_STREQ("text/html", val);
  1726. }
  1727. TEST(GetHeaderValueTest, SetContent) {
  1728. Response res;
  1729. res.set_content("html", "text/html");
  1730. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1731. res.set_content("text", "text/plain");
  1732. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1733. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1734. }
  1735. TEST(GetHeaderValueTest, RegularValueInt) {
  1736. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1737. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1738. EXPECT_EQ(100ull, val);
  1739. }
  1740. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1741. Headers headers = {{"Content-Length", "x"}};
  1742. auto is_invalid_value = false;
  1743. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1744. is_invalid_value);
  1745. EXPECT_EQ(0ull, val);
  1746. EXPECT_TRUE(is_invalid_value);
  1747. }
  1748. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1749. // An all-digit value that overflows size_t must be reported as invalid, not
  1750. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1751. // a large length to a small one on 32-bit builds, leaving the framing length
  1752. // wrong while is_invalid_value stayed false.
  1753. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1754. auto is_invalid_value = false;
  1755. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1756. is_invalid_value);
  1757. EXPECT_TRUE(is_invalid_value);
  1758. // A well-formed length is unaffected.
  1759. Headers ok = {{"Content-Length", "1234"}};
  1760. is_invalid_value = false;
  1761. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1762. is_invalid_value);
  1763. EXPECT_EQ(1234ull, val);
  1764. EXPECT_FALSE(is_invalid_value);
  1765. }
  1766. TEST(GetHeaderValueTest, Range) {
  1767. {
  1768. Headers headers = {make_range_header({{1, -1}})};
  1769. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1770. EXPECT_STREQ("bytes=1-", val);
  1771. }
  1772. {
  1773. Headers headers = {make_range_header({{-1, 1}})};
  1774. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1775. EXPECT_STREQ("bytes=-1", val);
  1776. }
  1777. {
  1778. Headers headers = {make_range_header({{1, 10}})};
  1779. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1780. EXPECT_STREQ("bytes=1-10", val);
  1781. }
  1782. {
  1783. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1784. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1785. EXPECT_STREQ("bytes=1-10, 100-", val);
  1786. }
  1787. {
  1788. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1789. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1790. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1791. }
  1792. {
  1793. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1794. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1795. EXPECT_STREQ("bytes=0-0, -1", val);
  1796. }
  1797. }
  1798. TEST(BearerTokenAuthTest, SchemeValidation) {
  1799. // A value shorter than "Bearer " must not throw from the fixed-length
  1800. // substr, and a non-Bearer scheme must not be reported as a token.
  1801. struct {
  1802. const char *value;
  1803. const char *expected;
  1804. } cases[] = {
  1805. {"x", ""},
  1806. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1807. {"Bearer abc123", "abc123"},
  1808. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1809. };
  1810. for (const auto &c : cases) {
  1811. Request req;
  1812. req.set_header("Authorization", c.value);
  1813. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1814. }
  1815. }
  1816. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1817. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1818. // to depend on the standard library (libstdc++ handed back duplicates in
  1819. // reverse insertion order, libc++ in insertion order).
  1820. Request req;
  1821. req.set_header("Accept-Encoding", "gzip");
  1822. req.set_header("Accept-Encoding", "deflate");
  1823. req.set_header("Accept-Encoding", "br");
  1824. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1825. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1826. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1827. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1828. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1829. }
  1830. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1831. Request req;
  1832. req.set_header("X-Test", "only");
  1833. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1834. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1835. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1836. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1837. }
  1838. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1839. Request req;
  1840. req.set_header("X-First", "1");
  1841. req.set_header("X-Test", "2");
  1842. req.params.emplace("first", "1");
  1843. req.params.emplace("test", "2");
  1844. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1845. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1846. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1847. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1848. // The second one is negative when read as a signed value
  1849. const auto max_id = (std::numeric_limits<size_t>::max)();
  1850. for (auto id : {max_id / 2, max_id}) {
  1851. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1852. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1853. EXPECT_EQ("", req.get_param_value("test", id));
  1854. EXPECT_EQ("", req.form.get_field("test", id));
  1855. EXPECT_EQ("", req.form.get_file("test", id).content);
  1856. }
  1857. }
  1858. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1859. Headers headers;
  1860. headers.emplace("Host", "example.com");
  1861. headers.emplace("Accept-Encoding", "gzip");
  1862. headers.emplace("User-Agent", "test");
  1863. headers.emplace("Accept-Encoding", "deflate");
  1864. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1865. "Accept-Encoding=deflate ",
  1866. entries_to_string(headers));
  1867. }
  1868. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1869. Headers headers = {{"Content-Type", "text/html"},
  1870. {"CONTENT-TYPE", "text/xml"}};
  1871. EXPECT_EQ(2U, headers.count("content-type"));
  1872. auto it = headers.find("content-type");
  1873. ASSERT_TRUE(it != headers.end());
  1874. EXPECT_EQ("text/html", it->second);
  1875. }
  1876. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1877. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1878. // drop only those fields and leave everything positioned between them.
  1879. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1880. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1881. auto rng = headers.equal_range("a");
  1882. headers.erase(rng.first, rng.second);
  1883. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1884. }
  1885. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1886. Headers headers = {
  1887. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1888. EXPECT_EQ(3U, headers.erase("A"));
  1889. EXPECT_EQ(0U, headers.count("A"));
  1890. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1891. }
  1892. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1893. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1894. headers.emplace_front("Host", "example.com");
  1895. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1896. entries_to_string(headers));
  1897. }
  1898. TEST(ParseHeaderValueTest, Range) {
  1899. {
  1900. Ranges ranges;
  1901. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1902. EXPECT_TRUE(ret);
  1903. EXPECT_EQ(1u, ranges.size());
  1904. EXPECT_EQ(1u, ranges[0].first);
  1905. EXPECT_EQ(-1, ranges[0].second);
  1906. }
  1907. {
  1908. Ranges ranges;
  1909. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1910. EXPECT_TRUE(ret);
  1911. EXPECT_EQ(1u, ranges.size());
  1912. EXPECT_EQ(-1, ranges[0].first);
  1913. EXPECT_EQ(1u, ranges[0].second);
  1914. }
  1915. {
  1916. Ranges ranges;
  1917. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1918. EXPECT_TRUE(ret);
  1919. EXPECT_EQ(1u, ranges.size());
  1920. EXPECT_EQ(1u, ranges[0].first);
  1921. EXPECT_EQ(10u, ranges[0].second);
  1922. }
  1923. {
  1924. Ranges ranges;
  1925. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1926. EXPECT_FALSE(ret);
  1927. }
  1928. {
  1929. Ranges ranges;
  1930. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1931. EXPECT_TRUE(ret);
  1932. EXPECT_EQ(2u, ranges.size());
  1933. EXPECT_EQ(1u, ranges[0].first);
  1934. EXPECT_EQ(10u, ranges[0].second);
  1935. EXPECT_EQ(100u, ranges[1].first);
  1936. EXPECT_EQ(-1, ranges[1].second);
  1937. }
  1938. {
  1939. Ranges ranges;
  1940. auto ret =
  1941. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ(3u, ranges.size());
  1944. EXPECT_EQ(1u, ranges[0].first);
  1945. EXPECT_EQ(10u, ranges[0].second);
  1946. EXPECT_EQ(100u, ranges[1].first);
  1947. EXPECT_EQ(200u, ranges[1].second);
  1948. EXPECT_EQ(300u, ranges[2].first);
  1949. EXPECT_EQ(400u, ranges[2].second);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1954. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1955. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1956. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1957. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1958. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1959. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1960. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1961. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1962. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1963. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1964. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1965. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1966. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1967. EXPECT_FALSE(
  1968. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1969. EXPECT_TRUE(ranges.empty());
  1970. }
  1971. {
  1972. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1973. // remainder of the representation, so it stays accepted.
  1974. Ranges ranges;
  1975. auto ret =
  1976. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1977. EXPECT_TRUE(ret);
  1978. ASSERT_EQ(1u, ranges.size());
  1979. EXPECT_EQ(0, ranges[0].first);
  1980. EXPECT_EQ(-1, ranges[0].second);
  1981. }
  1982. // RFC 9110 14.1: range unit names are case-insensitive.
  1983. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1984. Ranges ranges;
  1985. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1986. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1987. }
  1988. }
  1989. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1990. Request req;
  1991. req.set_header("Accept-Encoding", "gzip");
  1992. Response res;
  1993. res.set_header("Content-Type", "text/plain");
  1994. auto ret = detail::encoding_type(req, res);
  1995. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1996. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1997. #else
  1998. EXPECT_TRUE(ret == detail::EncodingType::None);
  1999. #endif
  2000. }
  2001. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2002. Request req;
  2003. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2004. Response res;
  2005. res.set_header("Content-Type", "text/plain");
  2006. auto ret = detail::encoding_type(req, res);
  2007. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2008. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2009. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2010. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2011. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2012. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2013. #else
  2014. EXPECT_TRUE(ret == detail::EncodingType::None);
  2015. #endif
  2016. }
  2017. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2018. Request req;
  2019. req.set_header("Accept-Encoding",
  2020. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2021. Response res;
  2022. res.set_header("Content-Type", "text/plain");
  2023. auto ret = detail::encoding_type(req, res);
  2024. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2025. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2026. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2027. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2028. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2029. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2030. #else
  2031. EXPECT_TRUE(ret == detail::EncodingType::None);
  2032. #endif
  2033. }
  2034. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2035. // All supported encodings rejected with q=0 should return None
  2036. Request req;
  2037. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2038. Response res;
  2039. res.set_header("Content-Type", "text/plain");
  2040. auto ret = detail::encoding_type(req, res);
  2041. EXPECT_TRUE(ret == detail::EncodingType::None);
  2042. }
  2043. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2044. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2045. Request req;
  2046. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2047. Response res;
  2048. res.set_header("Content-Type", "text/plain");
  2049. auto ret = detail::encoding_type(req, res);
  2050. EXPECT_TRUE(ret == detail::EncodingType::None);
  2051. }
  2052. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2053. Request req;
  2054. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2055. Response res;
  2056. res.set_header("Content-Type", "text/plain");
  2057. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2058. }
  2059. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2060. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2061. Request req;
  2062. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2063. Response res;
  2064. res.set_header("Content-Type", "text/plain");
  2065. auto ret = detail::encoding_type(req, res);
  2066. EXPECT_TRUE(ret == detail::EncodingType::None);
  2067. }
  2068. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2069. // RFC 7231: Accept-Encoding values are case-insensitive
  2070. Request req;
  2071. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2072. Response res;
  2073. res.set_header("Content-Type", "text/plain");
  2074. auto ret = detail::encoding_type(req, res);
  2075. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2076. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2077. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2078. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2079. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2080. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2081. #else
  2082. EXPECT_TRUE(ret == detail::EncodingType::None);
  2083. #endif
  2084. }
  2085. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2086. // q value should determine priority, not hardcoded order
  2087. Request req;
  2088. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2089. Response res;
  2090. res.set_header("Content-Type", "text/plain");
  2091. auto ret = detail::encoding_type(req, res);
  2092. // gzip has highest q=1.0, so it should be selected even though
  2093. // br and zstd are also supported
  2094. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2095. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2096. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2097. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2098. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2100. #else
  2101. EXPECT_TRUE(ret == detail::EncodingType::None);
  2102. #endif
  2103. }
  2104. TEST(BufferStreamTest, read) {
  2105. detail::BufferStream strm1;
  2106. Stream &strm = strm1;
  2107. EXPECT_EQ(5, strm.write("hello"));
  2108. char buf[512];
  2109. EXPECT_EQ(2, strm.read(buf, 2));
  2110. EXPECT_EQ('h', buf[0]);
  2111. EXPECT_EQ('e', buf[1]);
  2112. EXPECT_EQ(2, strm.read(buf, 2));
  2113. EXPECT_EQ('l', buf[0]);
  2114. EXPECT_EQ('l', buf[1]);
  2115. EXPECT_EQ(1, strm.read(buf, 1));
  2116. EXPECT_EQ('o', buf[0]);
  2117. EXPECT_EQ(0, strm.read(buf, 1));
  2118. }
  2119. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2120. auto host = "www.httpwatch.com";
  2121. auto ip = hosted_at(host);
  2122. EXPECT_EQ("23.96.13.243", ip);
  2123. std::vector<std::string> addrs;
  2124. hosted_at(host, addrs);
  2125. EXPECT_EQ(1u, addrs.size());
  2126. }
  2127. #if 0 // It depends on each test environment...
  2128. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2129. auto host = "www.youtube.com";
  2130. std::vector<std::string> addrs;
  2131. hosted_at(host, addrs);
  2132. EXPECT_EQ(20u, addrs.size());
  2133. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2134. EXPECT_TRUE(it != addrs.end());
  2135. }
  2136. #endif
  2137. class ChunkedEncodingTest : public ::testing::Test {
  2138. protected:
  2139. ChunkedEncodingTest()
  2140. : cli_(HOST, PORT)
  2141. #ifdef CPPHTTPLIB_SSL_ENABLED
  2142. ,
  2143. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2144. #endif
  2145. {
  2146. cli_.set_connection_timeout(2);
  2147. #ifdef CPPHTTPLIB_SSL_ENABLED
  2148. cli_.enable_server_certificate_verification(false);
  2149. #endif
  2150. }
  2151. virtual void SetUp() {
  2152. read_file("./image.jpg", image_data_);
  2153. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2154. res.set_content("Hello World!", "text/plain");
  2155. });
  2156. svr_.Get(
  2157. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2158. res.set_chunked_content_provider(
  2159. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2160. size_t remaining = image_data_.size() - offset;
  2161. if (remaining == 0) {
  2162. sink.done();
  2163. } else {
  2164. constexpr size_t CHUNK_SIZE = 1024;
  2165. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2166. sink.write(&image_data_[offset], send_size);
  2167. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2168. }
  2169. return true;
  2170. });
  2171. });
  2172. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2173. svr_.wait_until_ready();
  2174. }
  2175. virtual void TearDown() {
  2176. svr_.stop();
  2177. if (!request_threads_.empty()) {
  2178. std::this_thread::sleep_for(std::chrono::seconds(1));
  2179. for (auto &t : request_threads_) {
  2180. t.join();
  2181. }
  2182. }
  2183. t_.join();
  2184. }
  2185. #ifdef CPPHTTPLIB_SSL_ENABLED
  2186. SSLClient cli_;
  2187. SSLServer svr_;
  2188. #else
  2189. Client cli_;
  2190. Server svr_;
  2191. #endif
  2192. thread t_;
  2193. std::vector<thread> request_threads_;
  2194. std::string image_data_;
  2195. };
  2196. TEST_F(ChunkedEncodingTest, NormalGet) {
  2197. auto res = cli_.Get("/chunked");
  2198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2199. std::string out;
  2200. read_file("./image.jpg", out);
  2201. EXPECT_EQ(StatusCode::OK_200, res->status);
  2202. EXPECT_EQ(out, res->body);
  2203. }
  2204. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2205. std::string body;
  2206. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2207. body.append(data, data_length);
  2208. return true;
  2209. });
  2210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2211. std::string out;
  2212. read_file("./image.jpg", out);
  2213. EXPECT_EQ(StatusCode::OK_200, res->status);
  2214. EXPECT_EQ(out, body);
  2215. }
  2216. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2217. std::string body;
  2218. auto res = cli_.Get(
  2219. "/chunked",
  2220. [&](const Response &response) {
  2221. EXPECT_EQ(StatusCode::OK_200, response.status);
  2222. return true;
  2223. },
  2224. [&](const char *data, size_t data_length) {
  2225. body.append(data, data_length);
  2226. return true;
  2227. });
  2228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2229. std::string out;
  2230. read_file("./image.jpg", out);
  2231. EXPECT_EQ(StatusCode::OK_200, res->status);
  2232. EXPECT_EQ(out, body);
  2233. }
  2234. TEST(RangeTest, FromHTTPBin_Online) {
  2235. auto host = "httpbingo.org";
  2236. auto path = std::string{"/range/32"};
  2237. #ifdef CPPHTTPLIB_SSL_ENABLED
  2238. auto port = 443;
  2239. SSLClient cli(host, port);
  2240. #else
  2241. auto port = 80;
  2242. Client cli(host, port);
  2243. #endif
  2244. cli.set_connection_timeout(5);
  2245. {
  2246. auto res = cli.Get(path);
  2247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2248. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2249. EXPECT_EQ(StatusCode::OK_200, res->status);
  2250. }
  2251. {
  2252. Headers headers = {make_range_header({{1, -1}})};
  2253. auto res = cli.Get(path, headers);
  2254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2255. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2257. }
  2258. {
  2259. Headers headers = {make_range_header({{1, 10}})};
  2260. auto res = cli.Get(path, headers);
  2261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2262. EXPECT_EQ("bcdefghijk", res->body);
  2263. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2264. }
  2265. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2266. // entire resource, while the original httpbin returned 200. Both are
  2267. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2268. {
  2269. Headers headers = {make_range_header({{0, 31}})};
  2270. auto res = cli.Get(path, headers);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2274. res->status == StatusCode::PartialContent_206);
  2275. }
  2276. {
  2277. Headers headers = {make_range_header({{0, -1}})};
  2278. auto res = cli.Get(path, headers);
  2279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2280. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2281. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2282. res->status == StatusCode::PartialContent_206);
  2283. }
  2284. // go-httpbin returns 206 with clamped range for over-range requests,
  2285. // while the original httpbin returned 416. Both behaviors are observed
  2286. // in real servers, so we only verify the request succeeds.
  2287. {
  2288. Headers headers = {make_range_header({{0, 32}})};
  2289. auto res = cli.Get(path, headers);
  2290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2291. }
  2292. }
  2293. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2294. auto host = "unresolvableaddress.local";
  2295. auto path = std::string{"/"};
  2296. #ifdef CPPHTTPLIB_SSL_ENABLED
  2297. auto port = 443;
  2298. SSLClient cli(host, port);
  2299. #else
  2300. auto port = 80;
  2301. Client cli(host, port);
  2302. #endif
  2303. cli.set_connection_timeout(1);
  2304. {
  2305. auto res = cli.Get(path);
  2306. ASSERT_FALSE(res);
  2307. }
  2308. std::this_thread::sleep_for(std::chrono::seconds(8));
  2309. }
  2310. #if defined(__linux__) && defined(__GLIBC__) && \
  2311. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2312. // Forward declaration: in split builds split.py strips `inline` and moves the
  2313. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2314. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2315. // against the symbol in both header-only and split builds.
  2316. namespace httplib {
  2317. namespace detail {
  2318. int getaddrinfo_with_timeout(const char *node, const char *service,
  2319. const struct addrinfo *hints,
  2320. struct addrinfo **res, time_t timeout_sec);
  2321. } // namespace detail
  2322. } // namespace httplib
  2323. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2324. //
  2325. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2326. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2327. // gai_suspend() call hits the connection timeout the function calls
  2328. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2329. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2330. // still alive and still references the now-destroyed stack frame.
  2331. //
  2332. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2333. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2334. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2335. // and runs them in a container.
  2336. namespace {
  2337. bool should_run_issue_2431_tests() {
  2338. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2339. return v && *v && std::string(v) != "0";
  2340. }
  2341. std::string unique_unresolvable_host(int n) {
  2342. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2343. // glibc still asks the configured nameserver — which is exactly the path
  2344. // we want to exercise. A unique label per call avoids the resolver cache.
  2345. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2346. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2347. std::to_string(n) + ".invalid";
  2348. }
  2349. } // namespace
  2350. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2351. if (!should_run_issue_2431_tests()) {
  2352. GTEST_SKIP()
  2353. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2354. }
  2355. for (int i = 0; i < 8; ++i) {
  2356. struct addrinfo hints;
  2357. memset(&hints, 0, sizeof(hints));
  2358. hints.ai_family = AF_UNSPEC;
  2359. hints.ai_socktype = SOCK_STREAM;
  2360. auto host = unique_unresolvable_host(i);
  2361. struct addrinfo *result = nullptr;
  2362. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2363. &result, /*timeout_sec=*/1);
  2364. if (rc == 0 && result) { freeaddrinfo(result); }
  2365. }
  2366. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2367. // stack region they still believe holds their gaicb.
  2368. std::this_thread::sleep_for(std::chrono::seconds(3));
  2369. }
  2370. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2371. if (!should_run_issue_2431_tests()) {
  2372. GTEST_SKIP()
  2373. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2374. }
  2375. std::atomic<bool> stop{false};
  2376. std::vector<std::thread> threads;
  2377. for (int t = 0; t < 8; ++t) {
  2378. threads.emplace_back([t, &stop] {
  2379. int i = 0;
  2380. while (!stop.load(std::memory_order_relaxed)) {
  2381. struct addrinfo hints;
  2382. memset(&hints, 0, sizeof(hints));
  2383. hints.ai_family = AF_UNSPEC;
  2384. hints.ai_socktype = SOCK_STREAM;
  2385. auto host = unique_unresolvable_host(t * 100000 + i++);
  2386. struct addrinfo *result = nullptr;
  2387. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2388. &result, /*timeout_sec=*/1);
  2389. if (rc == 0 && result) { freeaddrinfo(result); }
  2390. }
  2391. });
  2392. }
  2393. std::this_thread::sleep_for(std::chrono::seconds(8));
  2394. stop.store(true, std::memory_order_relaxed);
  2395. for (auto &th : threads) {
  2396. th.join();
  2397. }
  2398. std::this_thread::sleep_for(std::chrono::seconds(3));
  2399. }
  2400. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2401. if (!should_run_issue_2431_tests()) {
  2402. GTEST_SKIP()
  2403. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2404. }
  2405. std::atomic<bool> stop{false};
  2406. std::vector<std::thread> threads;
  2407. for (int t = 0; t < 8; ++t) {
  2408. threads.emplace_back([t, &stop] {
  2409. int i = 0;
  2410. while (!stop.load(std::memory_order_relaxed)) {
  2411. auto host = unique_unresolvable_host(t * 100000 + i++);
  2412. Client cli(host, 80);
  2413. cli.set_connection_timeout(1, 0);
  2414. cli.set_read_timeout(1, 0);
  2415. cli.set_write_timeout(1, 0);
  2416. (void)cli.Get("/");
  2417. }
  2418. });
  2419. }
  2420. std::this_thread::sleep_for(std::chrono::seconds(8));
  2421. stop.store(true, std::memory_order_relaxed);
  2422. for (auto &th : threads) {
  2423. th.join();
  2424. }
  2425. std::this_thread::sleep_for(std::chrono::seconds(3));
  2426. }
  2427. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2428. TEST(ConnectionErrorTest, InvalidHost) {
  2429. auto host = "-abcde.com";
  2430. #ifdef CPPHTTPLIB_SSL_ENABLED
  2431. auto port = 443;
  2432. SSLClient cli(host, port);
  2433. #else
  2434. auto port = 80;
  2435. Client cli(host, port);
  2436. #endif
  2437. cli.set_connection_timeout(std::chrono::seconds(2));
  2438. auto res = cli.Get("/");
  2439. ASSERT_TRUE(!res);
  2440. EXPECT_EQ(Error::Connection, res.error());
  2441. }
  2442. TEST(ConnectionErrorTest, InvalidHost2) {
  2443. auto host = "httpcan.org/";
  2444. #ifdef CPPHTTPLIB_SSL_ENABLED
  2445. SSLClient cli(host);
  2446. #else
  2447. Client cli(host);
  2448. #endif
  2449. cli.set_connection_timeout(std::chrono::seconds(2));
  2450. auto res = cli.Get("/");
  2451. ASSERT_TRUE(!res);
  2452. EXPECT_EQ(Error::Connection, res.error());
  2453. }
  2454. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2455. auto host = "httpcan.org/";
  2456. #ifdef CPPHTTPLIB_SSL_ENABLED
  2457. SSLClient cli(host);
  2458. #else
  2459. Client cli(host);
  2460. #endif
  2461. cli.set_connection_timeout(std::chrono::seconds(2));
  2462. auto res = cli.Get("/");
  2463. ASSERT_TRUE(!res);
  2464. stringstream s;
  2465. s << "error code: " << res.error();
  2466. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2467. }
  2468. TEST(ConnectionErrorTest, InvalidPort) {
  2469. auto host = "localhost";
  2470. auto port = 44380;
  2471. #ifdef CPPHTTPLIB_SSL_ENABLED
  2472. SSLClient cli(host, port);
  2473. #else
  2474. Client cli(host, port);
  2475. #endif
  2476. cli.set_connection_timeout(std::chrono::seconds(2));
  2477. auto res = cli.Get("/");
  2478. ASSERT_TRUE(!res);
  2479. EXPECT_TRUE(Error::Connection == res.error() ||
  2480. Error::ConnectionTimeout == res.error());
  2481. }
  2482. TEST(ConnectionErrorTest, Timeout_Online) {
  2483. auto host = "google.com";
  2484. #ifdef CPPHTTPLIB_SSL_ENABLED
  2485. auto port = 44380;
  2486. SSLClient cli(host, port);
  2487. #else
  2488. auto port = 8080;
  2489. Client cli(host, port);
  2490. #endif
  2491. cli.set_connection_timeout(std::chrono::seconds(2));
  2492. // only probe one address type so that the error reason
  2493. // correlates to the timed-out IPv4, not the unsupported
  2494. // IPv6 connection attempt
  2495. cli.set_address_family(AF_INET);
  2496. auto res = cli.Get("/");
  2497. ASSERT_TRUE(!res);
  2498. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2499. }
  2500. TEST(CancelTest, NoCancel_Online) {
  2501. auto host = "httpbingo.org";
  2502. auto path = std::string{"/range/32"};
  2503. #ifdef CPPHTTPLIB_SSL_ENABLED
  2504. auto port = 443;
  2505. SSLClient cli(host, port);
  2506. #else
  2507. auto port = 80;
  2508. Client cli(host, port);
  2509. #endif
  2510. cli.set_connection_timeout(std::chrono::seconds(5));
  2511. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2513. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2514. EXPECT_EQ(StatusCode::OK_200, res->status);
  2515. }
  2516. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2517. // Use /bytes with a large payload so that the DownloadProgress callback
  2518. // (which only fires for Content-Length responses) is invoked before the
  2519. // entire body is received, giving cancellation a chance to fire.
  2520. auto host = "httpbingo.org";
  2521. auto path = std::string{"/bytes/524288"};
  2522. #ifdef CPPHTTPLIB_SSL_ENABLED
  2523. auto port = 443;
  2524. SSLClient cli(host, port);
  2525. #else
  2526. auto port = 80;
  2527. Client cli(host, port);
  2528. #endif
  2529. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2530. cli.set_connection_timeout(std::chrono::seconds(5));
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. TEST(CancelTest, WithCancelLargePayload_Online) {
  2535. auto host = "httpbingo.org";
  2536. auto path = std::string{"/bytes/524288"};
  2537. #ifdef CPPHTTPLIB_SSL_ENABLED
  2538. auto port = 443;
  2539. SSLClient cli(host, port);
  2540. #else
  2541. auto port = 80;
  2542. Client cli(host, port);
  2543. #endif
  2544. cli.set_connection_timeout(std::chrono::seconds(5));
  2545. uint32_t count = 0;
  2546. auto res =
  2547. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2548. ASSERT_TRUE(!res);
  2549. EXPECT_EQ(Error::Canceled, res.error());
  2550. }
  2551. TEST(CancelTest, NoCancelPost) {
  2552. Server svr;
  2553. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2554. res.set_content("Hello World!", "text/plain");
  2555. });
  2556. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2557. auto se = detail::scope_exit([&] {
  2558. svr.stop();
  2559. thread.join();
  2560. ASSERT_FALSE(svr.is_running());
  2561. });
  2562. svr.wait_until_ready();
  2563. Client cli(HOST, PORT);
  2564. cli.set_connection_timeout(std::chrono::seconds(5));
  2565. auto res =
  2566. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2567. "application/json", [](uint64_t, uint64_t) { return true; });
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. EXPECT_EQ("Hello World!", res->body);
  2570. EXPECT_EQ(StatusCode::OK_200, res->status);
  2571. }
  2572. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2573. Server svr;
  2574. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2575. res.set_content("Hello World!", "text/plain");
  2576. });
  2577. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2578. auto se = detail::scope_exit([&] {
  2579. svr.stop();
  2580. thread.join();
  2581. ASSERT_FALSE(svr.is_running());
  2582. });
  2583. svr.wait_until_ready();
  2584. Client cli(HOST, PORT);
  2585. cli.set_connection_timeout(std::chrono::seconds(5));
  2586. auto res =
  2587. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2588. "application/json", [](uint64_t, uint64_t) { return false; });
  2589. ASSERT_TRUE(!res);
  2590. EXPECT_EQ(Error::Canceled, res.error());
  2591. }
  2592. TEST(CancelTest, WithCancelLargePayloadPost) {
  2593. Server svr;
  2594. svr.set_payload_max_length(200 * 1024 * 1024);
  2595. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2596. res.set_content(LARGE_DATA, "text/plain");
  2597. });
  2598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2599. auto se = detail::scope_exit([&] {
  2600. svr.stop();
  2601. thread.join();
  2602. ASSERT_FALSE(svr.is_running());
  2603. });
  2604. svr.wait_until_ready();
  2605. Client cli(HOST, PORT);
  2606. cli.set_payload_max_length(200 * 1024 * 1024);
  2607. cli.set_connection_timeout(std::chrono::seconds(5));
  2608. auto res =
  2609. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2610. "application/json", [](uint64_t, uint64_t) { return false; });
  2611. ASSERT_TRUE(!res);
  2612. EXPECT_EQ(Error::Canceled, res.error());
  2613. }
  2614. TEST(CancelTest, NoCancelPut) {
  2615. Server svr;
  2616. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2617. res.set_content("Hello World!", "text/plain");
  2618. });
  2619. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2620. auto se = detail::scope_exit([&] {
  2621. svr.stop();
  2622. thread.join();
  2623. ASSERT_FALSE(svr.is_running());
  2624. });
  2625. svr.wait_until_ready();
  2626. Client cli(HOST, PORT);
  2627. cli.set_connection_timeout(std::chrono::seconds(5));
  2628. auto res =
  2629. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2630. "application/json", [](uint64_t, uint64_t) { return true; });
  2631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2632. EXPECT_EQ("Hello World!", res->body);
  2633. EXPECT_EQ(StatusCode::OK_200, res->status);
  2634. }
  2635. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2636. Server svr;
  2637. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2638. res.set_content("Hello World!", "text/plain");
  2639. });
  2640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2641. auto se = detail::scope_exit([&] {
  2642. svr.stop();
  2643. thread.join();
  2644. ASSERT_FALSE(svr.is_running());
  2645. });
  2646. svr.wait_until_ready();
  2647. Client cli(HOST, PORT);
  2648. cli.set_connection_timeout(std::chrono::seconds(5));
  2649. auto res =
  2650. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2651. "application/json", [](uint64_t, uint64_t) { return false; });
  2652. ASSERT_TRUE(!res);
  2653. EXPECT_EQ(Error::Canceled, res.error());
  2654. }
  2655. TEST(CancelTest, WithCancelLargePayloadPut) {
  2656. Server svr;
  2657. svr.set_payload_max_length(200 * 1024 * 1024);
  2658. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2659. res.set_content(LARGE_DATA, "text/plain");
  2660. });
  2661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2662. auto se = detail::scope_exit([&] {
  2663. svr.stop();
  2664. thread.join();
  2665. ASSERT_FALSE(svr.is_running());
  2666. });
  2667. svr.wait_until_ready();
  2668. Client cli(HOST, PORT);
  2669. cli.set_payload_max_length(200 * 1024 * 1024);
  2670. cli.set_connection_timeout(std::chrono::seconds(5));
  2671. auto res =
  2672. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2673. "application/json", [](uint64_t, uint64_t) { return false; });
  2674. ASSERT_TRUE(!res);
  2675. EXPECT_EQ(Error::Canceled, res.error());
  2676. }
  2677. TEST(CancelTest, NoCancelPatch) {
  2678. Server svr;
  2679. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2680. res.set_content("Hello World!", "text/plain");
  2681. });
  2682. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2683. auto se = detail::scope_exit([&] {
  2684. svr.stop();
  2685. thread.join();
  2686. ASSERT_FALSE(svr.is_running());
  2687. });
  2688. svr.wait_until_ready();
  2689. Client cli(HOST, PORT);
  2690. cli.set_connection_timeout(std::chrono::seconds(5));
  2691. auto res =
  2692. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2693. "application/json", [](uint64_t, uint64_t) { return true; });
  2694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2695. EXPECT_EQ("Hello World!", res->body);
  2696. EXPECT_EQ(StatusCode::OK_200, res->status);
  2697. }
  2698. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2699. Server svr;
  2700. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2701. res.set_content("Hello World!", "text/plain");
  2702. });
  2703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2704. auto se = detail::scope_exit([&] {
  2705. svr.stop();
  2706. thread.join();
  2707. ASSERT_FALSE(svr.is_running());
  2708. });
  2709. svr.wait_until_ready();
  2710. Client cli(HOST, PORT);
  2711. cli.set_connection_timeout(std::chrono::seconds(5));
  2712. auto res =
  2713. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2714. "application/json", [](uint64_t, uint64_t) { return false; });
  2715. ASSERT_TRUE(!res);
  2716. EXPECT_EQ(Error::Canceled, res.error());
  2717. }
  2718. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2719. Server svr;
  2720. svr.set_payload_max_length(200 * 1024 * 1024);
  2721. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2722. res.set_content(LARGE_DATA, "text/plain");
  2723. });
  2724. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2725. auto se = detail::scope_exit([&] {
  2726. svr.stop();
  2727. thread.join();
  2728. ASSERT_FALSE(svr.is_running());
  2729. });
  2730. svr.wait_until_ready();
  2731. Client cli(HOST, PORT);
  2732. cli.set_payload_max_length(200 * 1024 * 1024);
  2733. cli.set_connection_timeout(std::chrono::seconds(5));
  2734. auto res =
  2735. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2736. "application/json", [](uint64_t, uint64_t) { return false; });
  2737. ASSERT_TRUE(!res);
  2738. EXPECT_EQ(Error::Canceled, res.error());
  2739. }
  2740. TEST(CancelTest, NoCancelDelete) {
  2741. Server svr;
  2742. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2743. res.set_content("Hello World!", "text/plain");
  2744. });
  2745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2746. auto se = detail::scope_exit([&] {
  2747. svr.stop();
  2748. thread.join();
  2749. ASSERT_FALSE(svr.is_running());
  2750. });
  2751. svr.wait_until_ready();
  2752. Client cli(HOST, PORT);
  2753. cli.set_connection_timeout(std::chrono::seconds(5));
  2754. auto res =
  2755. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2756. "application/json", [](uint64_t, uint64_t) { return true; });
  2757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2758. EXPECT_EQ("Hello World!", res->body);
  2759. EXPECT_EQ(StatusCode::OK_200, res->status);
  2760. }
  2761. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2762. Server svr;
  2763. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2764. res.set_content("Hello World!", "text/plain");
  2765. });
  2766. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2767. auto se = detail::scope_exit([&] {
  2768. svr.stop();
  2769. thread.join();
  2770. ASSERT_FALSE(svr.is_running());
  2771. });
  2772. svr.wait_until_ready();
  2773. Client cli(HOST, PORT);
  2774. cli.set_connection_timeout(std::chrono::seconds(5));
  2775. auto res =
  2776. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2777. "application/json", [](uint64_t, uint64_t) { return false; });
  2778. ASSERT_TRUE(!res);
  2779. EXPECT_EQ(Error::Canceled, res.error());
  2780. }
  2781. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2782. Server svr;
  2783. svr.set_payload_max_length(200 * 1024 * 1024);
  2784. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2785. res.set_content(LARGE_DATA, "text/plain");
  2786. });
  2787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2788. auto se = detail::scope_exit([&] {
  2789. svr.stop();
  2790. thread.join();
  2791. ASSERT_FALSE(svr.is_running());
  2792. });
  2793. svr.wait_until_ready();
  2794. Client cli(HOST, PORT);
  2795. cli.set_payload_max_length(200 * 1024 * 1024);
  2796. cli.set_connection_timeout(std::chrono::seconds(5));
  2797. auto res =
  2798. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2799. "application/json", [](uint64_t, uint64_t) { return false; });
  2800. ASSERT_TRUE(!res);
  2801. EXPECT_EQ(Error::Canceled, res.error());
  2802. }
  2803. static std::string remove_whitespace(const std::string &input) {
  2804. std::string output;
  2805. output.reserve(input.size());
  2806. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2807. [](unsigned char c) { return !std::isspace(c); });
  2808. return output;
  2809. }
  2810. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2811. auto host = "httpbingo.org";
  2812. auto path = std::string{"/basic-auth/hello/world"};
  2813. #ifdef CPPHTTPLIB_SSL_ENABLED
  2814. auto port = 443;
  2815. SSLClient cli(host, port);
  2816. #else
  2817. auto port = 80;
  2818. Client cli(host, port);
  2819. #endif
  2820. {
  2821. auto res = cli.Get(path);
  2822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2823. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2824. }
  2825. {
  2826. auto res = cli.Get(
  2827. path, Headers{make_basic_authentication_header("hello", "world")});
  2828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2829. auto body = remove_whitespace(res->body);
  2830. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2831. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2832. EXPECT_EQ(StatusCode::OK_200, res->status);
  2833. }
  2834. {
  2835. cli.set_basic_auth("hello", "world");
  2836. auto res = cli.Get(path);
  2837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2838. auto body = remove_whitespace(res->body);
  2839. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2840. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2841. EXPECT_EQ(StatusCode::OK_200, res->status);
  2842. }
  2843. {
  2844. cli.set_basic_auth("hello", "bad");
  2845. auto res = cli.Get(path);
  2846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2848. }
  2849. {
  2850. cli.set_basic_auth("bad", "world");
  2851. auto res = cli.Get(path);
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2854. }
  2855. }
  2856. #ifdef CPPHTTPLIB_SSL_ENABLED
  2857. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2858. auto host = "httpbingo.org";
  2859. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2860. auto paths = std::vector<std::string>{
  2861. "/digest-auth/auth/hello/world/MD5",
  2862. "/digest-auth/auth/hello/world/SHA-256",
  2863. };
  2864. auto port = 443;
  2865. SSLClient cli(host, port);
  2866. {
  2867. auto res = cli.Get(unauth_path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2870. }
  2871. {
  2872. cli.set_digest_auth("hello", "world");
  2873. for (const auto &path : paths) {
  2874. auto res = cli.Get(path.c_str());
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. auto body = remove_whitespace(res->body);
  2877. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2878. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2879. EXPECT_EQ(StatusCode::OK_200, res->status);
  2880. }
  2881. cli.set_digest_auth("hello", "bad");
  2882. for (const auto &path : paths) {
  2883. auto res = cli.Get(path.c_str());
  2884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2885. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2886. }
  2887. }
  2888. }
  2889. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2890. // comma-separated list of challenges, and each challenge may itself carry a
  2891. // comma-separated auth-param list, so a server can legally offer Basic
  2892. // before Digest, either as two field lines or packed into one. Runs one 401
  2893. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2894. // value() joins them in receipt order) and checks that the retry carries a
  2895. // well-formed Digest Authorization header naming expected_realm.
  2896. static void
  2897. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2898. const std::string &expected_realm) {
  2899. std::atomic<int> hits{0};
  2900. Server svr;
  2901. svr.Get("/x", [&](const Request &req, Response &res) {
  2902. if (++hits == 1) {
  2903. res.status = StatusCode::Unauthorized_401;
  2904. for (const auto &challenge : challenges) {
  2905. res.set_header("WWW-Authenticate", challenge);
  2906. }
  2907. } else {
  2908. auto authorization = req.get_header_value("Authorization");
  2909. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2910. EXPECT_NE(std::string::npos,
  2911. authorization.find("realm=\"" + expected_realm + "\""));
  2912. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2913. res.set_content("ok", "text/plain");
  2914. }
  2915. });
  2916. auto port = svr.bind_to_any_port(HOST);
  2917. std::thread t([&]() { svr.listen_after_bind(); });
  2918. auto se = detail::scope_exit([&] {
  2919. svr.stop();
  2920. t.join();
  2921. });
  2922. svr.wait_until_ready();
  2923. Client cli(HOST, port);
  2924. cli.set_digest_auth("hello", "world");
  2925. auto res = cli.Get("/x");
  2926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2927. EXPECT_EQ(2, hits.load());
  2928. }
  2929. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2930. static const char *kDigestChallenge =
  2931. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2932. "algorithm=MD5";
  2933. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2934. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2935. "testrealm");
  2936. }
  2937. // Same challenge list with the schemes in the opposite order, to make sure
  2938. // the fix above didn't just special-case "Basic first".
  2939. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2940. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2941. "testrealm");
  2942. }
  2943. // A comma inside a quoted auth-param value must not be mistaken for the
  2944. // separator between two challenges (or two auth-params).
  2945. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2946. run_digest_challenge_list_test(
  2947. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2948. "algorithm=MD5"},
  2949. "test,realm");
  2950. }
  2951. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2952. // make_digest_authentication_header() dereferences both unconditionally, so
  2953. // a server sending a challenge missing either one must not be treated as
  2954. // usable -- doing so used to crash the client with std::out_of_range.
  2955. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2956. Server svr;
  2957. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2958. res.status = StatusCode::Unauthorized_401;
  2959. res.set_header("WWW-Authenticate", challenge);
  2960. });
  2961. auto port = svr.bind_to_any_port(HOST);
  2962. std::thread t([&]() { svr.listen_after_bind(); });
  2963. auto se = detail::scope_exit([&] {
  2964. svr.stop();
  2965. t.join();
  2966. });
  2967. svr.wait_until_ready();
  2968. Client cli(HOST, port);
  2969. cli.set_digest_auth("hello", "world");
  2970. auto res = cli.Get("/x");
  2971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2972. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2973. }
  2974. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2975. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2976. }
  2977. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2978. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2979. }
  2980. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2981. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2982. }
  2983. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2984. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2985. // when storing the values, so the header builder has to re-escape them (and
  2986. // keep algorithm a bare token); otherwise the value breaks out of its
  2987. // quoted-string and injects extra auth-params into the client's Authorization.
  2988. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2989. std::atomic<int> hits{0};
  2990. std::string authorization;
  2991. Server svr;
  2992. svr.Get("/x", [&](const Request &req, Response &res) {
  2993. if (++hits == 1) {
  2994. res.status = StatusCode::Unauthorized_401;
  2995. // On the wire the quotes embedded in the values are backslash-escaped.
  2996. res.set_header("WWW-Authenticate",
  2997. "Digest realm=\"testrealm\", "
  2998. "nonce=\"n\\\"; injected=\\\"x\", "
  2999. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3000. } else {
  3001. authorization = req.get_header_value("Authorization");
  3002. res.set_content("ok", "text/plain");
  3003. }
  3004. });
  3005. auto port = svr.bind_to_any_port(HOST);
  3006. std::thread t([&]() { svr.listen_after_bind(); });
  3007. auto se = detail::scope_exit([&] {
  3008. svr.stop();
  3009. t.join();
  3010. });
  3011. svr.wait_until_ready();
  3012. Client cli(HOST, port);
  3013. cli.set_digest_auth("hello", "world");
  3014. auto res = cli.Get("/x");
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ(2, hits.load());
  3017. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3018. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3019. // inside its quoted-string rather than starting an "injected" auth-param.
  3020. EXPECT_NE(std::string::npos,
  3021. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3022. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3023. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3024. }
  3025. #endif
  3026. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3027. auto host = "google.com";
  3028. auto another_host = "example.com";
  3029. auto wrong_ip = "0.0.0.0";
  3030. #ifdef CPPHTTPLIB_SSL_ENABLED
  3031. SSLClient cli(host);
  3032. #else
  3033. Client cli(host);
  3034. #endif
  3035. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3036. auto res = cli.Get("/");
  3037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3038. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3039. }
  3040. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3041. auto host = "google.com";
  3042. auto wrong_ip = "0.0.0.0";
  3043. #ifdef CPPHTTPLIB_SSL_ENABLED
  3044. SSLClient cli(host);
  3045. #else
  3046. Client cli(host);
  3047. #endif
  3048. cli.set_hostname_addr_map({{host, wrong_ip}});
  3049. auto res = cli.Get("/");
  3050. ASSERT_TRUE(!res);
  3051. EXPECT_EQ(Error::Connection, res.error());
  3052. }
  3053. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3054. // A mapped value that is not an IP literal must be resolved. "localhost"
  3055. // resolves from the hosts file, so this test needs no external DNS.
  3056. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3057. auto host = "target.invalid";
  3058. Server svr;
  3059. std::string received_host;
  3060. svr.Get("/hi", [&](const Request &req, Response &res) {
  3061. received_host = req.get_header_value("Host");
  3062. res.set_content("Hello World!", "text/plain");
  3063. });
  3064. auto port = svr.bind_to_any_port(HOST);
  3065. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3066. auto se = detail::scope_exit([&] {
  3067. svr.stop();
  3068. thread.join();
  3069. ASSERT_FALSE(svr.is_running());
  3070. });
  3071. svr.wait_until_ready();
  3072. Client cli(host, port);
  3073. cli.set_hostname_addr_map({{host, HOST}});
  3074. auto res = cli.Get("/hi");
  3075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3076. EXPECT_EQ(StatusCode::OK_200, res->status);
  3077. // The mapping only redirects the connection; the identity stays host_.
  3078. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3079. }
  3080. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3081. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3082. auto host = "target.invalid";
  3083. Server svr;
  3084. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3085. res.set_content("Hello World!", "text/plain");
  3086. });
  3087. auto port = svr.bind_to_any_port("127.0.0.1");
  3088. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3089. auto se = detail::scope_exit([&] {
  3090. svr.stop();
  3091. thread.join();
  3092. ASSERT_FALSE(svr.is_running());
  3093. });
  3094. svr.wait_until_ready();
  3095. Client cli(host, port);
  3096. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3097. auto res = cli.Get("/hi");
  3098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3099. EXPECT_EQ(StatusCode::OK_200, res->status);
  3100. }
  3101. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3102. // An empty mapped value must leave host_ as the connection target. Without
  3103. // that guard the empty value would become the host argument, getaddrinfo
  3104. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3105. // loopback - silently connecting somewhere the caller never asked for.
  3106. // The server listens on loopback, so such a fallback would succeed and is
  3107. // therefore observable as a failure of this test.
  3108. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3109. Server svr;
  3110. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3111. res.set_content("Hello World!", "text/plain");
  3112. });
  3113. auto port = svr.bind_to_any_port(HOST);
  3114. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3115. auto se = detail::scope_exit([&] {
  3116. svr.stop();
  3117. thread.join();
  3118. ASSERT_FALSE(svr.is_running());
  3119. });
  3120. svr.wait_until_ready();
  3121. Client cli(blackhole, port);
  3122. cli.set_hostname_addr_map({{blackhole, ""}});
  3123. cli.set_connection_timeout(1);
  3124. auto res = cli.Get("/hi");
  3125. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3126. }
  3127. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3128. auto host = "httpbingo.org";
  3129. auto path = std::string{"/absolute-redirect/3"};
  3130. #ifdef CPPHTTPLIB_SSL_ENABLED
  3131. SSLClient cli(host);
  3132. #else
  3133. Client cli(host);
  3134. #endif
  3135. cli.set_follow_location(true);
  3136. auto res = cli.Get(path);
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ(StatusCode::OK_200, res->status);
  3139. }
  3140. TEST(RedirectTest, Redirect_Online) {
  3141. auto host = "httpbingo.org";
  3142. auto path = std::string{"/redirect/3"};
  3143. #ifdef CPPHTTPLIB_SSL_ENABLED
  3144. SSLClient cli(host);
  3145. #else
  3146. Client cli(host);
  3147. #endif
  3148. cli.set_follow_location(true);
  3149. auto res = cli.Get(path);
  3150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3151. EXPECT_EQ(StatusCode::OK_200, res->status);
  3152. }
  3153. TEST(RelativeRedirectTest, Redirect_Online) {
  3154. auto host = "httpbingo.org";
  3155. auto path = std::string{"/relative-redirect/3"};
  3156. #ifdef CPPHTTPLIB_SSL_ENABLED
  3157. SSLClient cli(host);
  3158. #else
  3159. Client cli(host);
  3160. #endif
  3161. cli.set_follow_location(true);
  3162. auto res = cli.Get(path);
  3163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3164. EXPECT_EQ(StatusCode::OK_200, res->status);
  3165. }
  3166. TEST(TooManyRedirectTest, Redirect_Online) {
  3167. auto host = "httpbingo.org";
  3168. auto path = std::string{"/redirect/21"};
  3169. #ifdef CPPHTTPLIB_SSL_ENABLED
  3170. SSLClient cli(host);
  3171. #else
  3172. Client cli(host);
  3173. #endif
  3174. cli.set_follow_location(true);
  3175. auto res = cli.Get(path);
  3176. ASSERT_TRUE(!res);
  3177. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3178. }
  3179. #ifdef CPPHTTPLIB_SSL_ENABLED
  3180. TEST(YahooRedirectTest, Redirect_Online) {
  3181. Client cli("yahoo.com");
  3182. auto res = cli.Get("/");
  3183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3184. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3185. cli.set_follow_location(true);
  3186. res = cli.Get("/");
  3187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3188. EXPECT_EQ(StatusCode::OK_200, res->status);
  3189. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3190. }
  3191. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3192. #define REDIR_HOST "httpbingo.org"
  3193. #define REDIR_PATH "/redirect-to"
  3194. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3195. SSLClient cli(REDIR_HOST);
  3196. cli.set_follow_location(true);
  3197. auto res =
  3198. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3200. EXPECT_EQ(StatusCode::OK_200, res->status);
  3201. }
  3202. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3203. SSLClient cli(REDIR_HOST);
  3204. cli.set_follow_location(true);
  3205. Params params;
  3206. params.emplace("url", "http://example.com");
  3207. params.emplace("status_code", "302");
  3208. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3210. EXPECT_EQ(StatusCode::OK_200, res->status);
  3211. }
  3212. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3213. SSLClient cli(REDIR_HOST);
  3214. cli.set_follow_location(true);
  3215. Params params;
  3216. params.emplace("url", "http://example.com");
  3217. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. }
  3221. TEST(UrlWithSpace, Redirect_Online) {
  3222. SSLClient cli("edge.forgecdn.net");
  3223. cli.set_follow_location(true);
  3224. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3226. EXPECT_EQ(StatusCode::OK_200, res->status);
  3227. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3228. }
  3229. #endif
  3230. #if !defined(_WIN32) && !defined(_WIN64)
  3231. TEST(ReceiveSignals, Signal) {
  3232. auto setupSignalHandlers = []() {
  3233. struct sigaction act;
  3234. sigemptyset(&act.sa_mask);
  3235. act.sa_flags = SA_SIGINFO;
  3236. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3237. switch (sig) {
  3238. case SIGINT:
  3239. default: break;
  3240. }
  3241. };
  3242. ::sigaction(SIGINT, &act, nullptr);
  3243. };
  3244. Server svr;
  3245. int port = 0;
  3246. auto thread = std::thread([&]() {
  3247. setupSignalHandlers();
  3248. port = svr.bind_to_any_port(HOST);
  3249. svr.listen_after_bind();
  3250. });
  3251. auto se = detail::scope_exit([&] {
  3252. svr.stop();
  3253. thread.join();
  3254. ASSERT_FALSE(svr.is_running());
  3255. });
  3256. svr.wait_until_ready();
  3257. ASSERT_TRUE(svr.is_running());
  3258. pthread_kill(thread.native_handle(), SIGINT);
  3259. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3260. ASSERT_TRUE(svr.is_running());
  3261. }
  3262. #endif
  3263. TEST(RedirectToDifferentPort, Redirect) {
  3264. Server svr1;
  3265. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3266. res.set_content("Hello World!", "text/plain");
  3267. });
  3268. int svr1_port = 0;
  3269. auto thread1 = std::thread([&]() {
  3270. svr1_port = svr1.bind_to_any_port(HOST);
  3271. svr1.listen_after_bind();
  3272. });
  3273. Server svr2;
  3274. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3275. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3276. });
  3277. int svr2_port = 0;
  3278. auto thread2 = std::thread([&]() {
  3279. svr2_port = svr2.bind_to_any_port(HOST);
  3280. svr2.listen_after_bind();
  3281. });
  3282. auto se = detail::scope_exit([&] {
  3283. svr2.stop();
  3284. thread2.join();
  3285. svr1.stop();
  3286. thread1.join();
  3287. ASSERT_FALSE(svr2.is_running());
  3288. ASSERT_FALSE(svr1.is_running());
  3289. });
  3290. svr1.wait_until_ready();
  3291. svr2.wait_until_ready();
  3292. Client cli("localhost", svr2_port);
  3293. cli.set_follow_location(true);
  3294. auto res = cli.Get("/2");
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. EXPECT_EQ("Hello World!", res->body);
  3298. }
  3299. // GET /redir on one server redirects to /target on another port, so the
  3300. // client follows it with a new client.
  3301. static Result
  3302. GetThroughRedirectToDifferentPort(Server::Handler target,
  3303. const std::function<void(Client &)> &setup,
  3304. const Headers &headers = Headers()) {
  3305. Server target_svr;
  3306. target_svr.Get("/target", target);
  3307. int target_port = 0;
  3308. auto target_thread = std::thread([&]() {
  3309. target_port = target_svr.bind_to_any_port(HOST);
  3310. target_svr.listen_after_bind();
  3311. });
  3312. Server origin_svr;
  3313. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3314. res.set_redirect(
  3315. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3316. });
  3317. int origin_port = 0;
  3318. auto origin_thread = std::thread([&]() {
  3319. origin_port = origin_svr.bind_to_any_port(HOST);
  3320. origin_svr.listen_after_bind();
  3321. });
  3322. auto se = detail::scope_exit([&] {
  3323. origin_svr.stop();
  3324. origin_thread.join();
  3325. target_svr.stop();
  3326. target_thread.join();
  3327. });
  3328. target_svr.wait_until_ready();
  3329. origin_svr.wait_until_ready();
  3330. Client cli("localhost", origin_port);
  3331. cli.set_follow_location(true);
  3332. setup(cli);
  3333. return cli.Get("/redir", headers);
  3334. }
  3335. static void
  3336. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3337. std::string captured_authorization;
  3338. auto result = GetThroughRedirectToDifferentPort(
  3339. [&](const Request &req, Response &res) {
  3340. captured_authorization = req.get_header_value("Authorization");
  3341. res.set_content("OK", "text/plain");
  3342. },
  3343. set_auth);
  3344. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3345. EXPECT_EQ(StatusCode::OK_200, result->status);
  3346. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3347. EXPECT_TRUE(captured_authorization.empty());
  3348. }
  3349. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3350. TestDoNotForwardCredentialsOnRedirect(
  3351. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3352. }
  3353. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3354. TestDoNotForwardCredentialsOnRedirect(
  3355. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3356. }
  3357. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3358. std::string captured_cookie;
  3359. auto result = GetThroughRedirectToDifferentPort(
  3360. [&](const Request &req, Response &res) {
  3361. captured_cookie = req.get_header_value("Cookie");
  3362. res.set_content("OK", "text/plain");
  3363. },
  3364. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3365. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3366. EXPECT_EQ(StatusCode::OK_200, result->status);
  3367. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3368. EXPECT_TRUE(captured_cookie.empty());
  3369. }
  3370. TEST(RedirectToSamePort, ForwardCookie) {
  3371. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3372. // header so that ordinary session flows keep working.
  3373. Server svr;
  3374. std::string captured_cookie;
  3375. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3376. res.set_redirect("/target", 302);
  3377. });
  3378. svr.Get("/target", [&](const Request &req, Response &res) {
  3379. captured_cookie = req.get_header_value("Cookie");
  3380. res.set_content("OK", "text/plain");
  3381. });
  3382. auto port = svr.bind_to_any_port(HOST);
  3383. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3384. auto se = detail::scope_exit([&] {
  3385. svr.stop();
  3386. thread.join();
  3387. ASSERT_FALSE(svr.is_running());
  3388. });
  3389. svr.wait_until_ready();
  3390. Client cli(HOST, port);
  3391. cli.set_follow_location(true);
  3392. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3393. auto res = cli.Get("/redir", headers);
  3394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3395. EXPECT_EQ(StatusCode::OK_200, res->status);
  3396. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3397. }
  3398. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3399. std::string authorization;
  3400. std::string trace_id;
  3401. auto result = GetThroughRedirectToDifferentPort(
  3402. [&](const Request &req, Response &res) {
  3403. authorization = req.get_header_value("Authorization");
  3404. trace_id = req.get_header_value("X-Trace-Id");
  3405. res.set_content("OK", "text/plain");
  3406. },
  3407. [](Client &cli) {
  3408. cli.set_default_headers(
  3409. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3410. });
  3411. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3412. EXPECT_EQ(StatusCode::OK_200, result->status);
  3413. // Like a header given with the request, a default one goes along unless it
  3414. // carries credentials (RFC 9110 15.4).
  3415. EXPECT_TRUE(authorization.empty());
  3416. EXPECT_EQ("42", trace_id);
  3417. }
  3418. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3419. auto result = GetThroughRedirectToDifferentPort(
  3420. [](const Request &, Response &res) {
  3421. res.set_content(std::string(2048, 'x'), "text/plain");
  3422. },
  3423. [](Client &cli) { cli.set_payload_max_length(1024); });
  3424. EXPECT_FALSE(result);
  3425. }
  3426. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3427. auto result = GetThroughRedirectToDifferentPort(
  3428. [](const Request &req, Response &res) {
  3429. // Answer after a second, or once the client gives up.
  3430. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3431. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3432. }
  3433. res.set_content("late", "text/plain");
  3434. },
  3435. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3436. ASSERT_FALSE(result);
  3437. EXPECT_EQ(Error::Read, result.error());
  3438. }
  3439. #ifdef CPPHTTPLIB_SSL_ENABLED
  3440. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3441. auto result = GetThroughRedirectToDifferentPort(
  3442. [](const Request &, Response &res) {
  3443. res.status = StatusCode::Unauthorized_401;
  3444. res.set_header("WWW-Authenticate",
  3445. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3446. },
  3447. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3448. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3449. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3450. }
  3451. #endif
  3452. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3453. Server svr;
  3454. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3455. // Port number that overflows int — should not crash
  3456. res.set_redirect("http://localhost:99999999999999999999/target");
  3457. });
  3458. auto port = svr.bind_to_any_port(HOST);
  3459. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3460. auto se = detail::scope_exit([&] {
  3461. svr.stop();
  3462. thread.join();
  3463. ASSERT_FALSE(svr.is_running());
  3464. });
  3465. svr.wait_until_ready();
  3466. Client cli(HOST, port);
  3467. cli.set_follow_location(true);
  3468. auto res = cli.Get("/redir");
  3469. // Should fail gracefully, not crash (no valid response due to bad port)
  3470. EXPECT_FALSE(res);
  3471. }
  3472. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3473. Server svr;
  3474. auto port = svr.bind_to_any_port(HOST);
  3475. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3476. // The server's own port followed by junk must not be followed
  3477. res.set_redirect("http://" + std::string(HOST) + ":" +
  3478. std::to_string(port) + "junk/target");
  3479. });
  3480. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3481. res.set_content("target", "text/plain");
  3482. });
  3483. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3484. auto se = detail::scope_exit([&] {
  3485. svr.stop();
  3486. thread.join();
  3487. ASSERT_FALSE(svr.is_running());
  3488. });
  3489. svr.wait_until_ready();
  3490. Client cli(HOST, port);
  3491. cli.set_follow_location(true);
  3492. auto res = cli.Get("/redir");
  3493. EXPECT_FALSE(res);
  3494. }
  3495. TEST(RedirectFromPageWithContent, Redirect) {
  3496. Server svr;
  3497. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3498. res.set_content("___", "text/plain");
  3499. res.set_redirect("/2");
  3500. });
  3501. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3502. res.set_content("Hello World!", "text/plain");
  3503. });
  3504. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3505. auto se = detail::scope_exit([&] {
  3506. svr.stop();
  3507. th.join();
  3508. ASSERT_FALSE(svr.is_running());
  3509. });
  3510. svr.wait_until_ready();
  3511. {
  3512. Client cli("localhost", PORT);
  3513. cli.set_follow_location(true);
  3514. std::string body;
  3515. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3516. body.append(data, data_length);
  3517. return true;
  3518. });
  3519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3520. EXPECT_EQ(StatusCode::OK_200, res->status);
  3521. EXPECT_EQ("Hello World!", body);
  3522. }
  3523. {
  3524. Client cli("localhost", PORT);
  3525. std::string body;
  3526. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3527. body.append(data, data_length);
  3528. return true;
  3529. });
  3530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3531. EXPECT_EQ(StatusCode::Found_302, res->status);
  3532. EXPECT_EQ("___", body);
  3533. }
  3534. }
  3535. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3536. Server svr;
  3537. auto port_str = std::to_string(PORT);
  3538. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3539. auto expected_host = "[::1]:" + port_str;
  3540. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3541. res.set_content("___", "text/plain");
  3542. // res.set_redirect("/2");
  3543. res.set_redirect(redirect_url);
  3544. });
  3545. svr.Get("/2", [&](const Request &req, Response &res) {
  3546. auto host_header = req.headers.find("Host");
  3547. ASSERT_TRUE(host_header != req.headers.end());
  3548. EXPECT_EQ(expected_host, host_header->second);
  3549. res.set_content("Hello World!", "text/plain");
  3550. });
  3551. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3552. auto se = detail::scope_exit([&] {
  3553. svr.stop();
  3554. th.join();
  3555. ASSERT_FALSE(svr.is_running());
  3556. });
  3557. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3558. // actually starts anything, so the condition !svr.is_running() will
  3559. // always remain true, and the loop never stops.
  3560. // This basically counts how many milliseconds have passed since the
  3561. // call to svr.listen(), and if after 5 seconds nothing started yet
  3562. // aborts the test.
  3563. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3564. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3565. ASSERT_LT(milliseconds, 5000U);
  3566. }
  3567. {
  3568. Client cli("::1", PORT);
  3569. cli.set_follow_location(true);
  3570. std::string body;
  3571. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3572. body.append(data, data_length);
  3573. return true;
  3574. });
  3575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3576. EXPECT_EQ(StatusCode::OK_200, res->status);
  3577. EXPECT_EQ("Hello World!", body);
  3578. }
  3579. {
  3580. Client cli("::1", PORT);
  3581. std::string body;
  3582. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3583. body.append(data, data_length);
  3584. return true;
  3585. });
  3586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3587. EXPECT_EQ(StatusCode::Found_302, res->status);
  3588. EXPECT_EQ("___", body);
  3589. }
  3590. }
  3591. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3592. Server svr;
  3593. svr.Get("/foo", [](const Request &req, Response &res) {
  3594. auto a = req.params.find("a");
  3595. if (a != req.params.end()) {
  3596. res.set_content((*a).second, "text/plain");
  3597. res.status = StatusCode::OK_200;
  3598. } else {
  3599. res.status = StatusCode::BadRequest_400;
  3600. }
  3601. });
  3602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3603. auto se = detail::scope_exit([&] {
  3604. svr.stop();
  3605. thread.join();
  3606. ASSERT_FALSE(svr.is_running());
  3607. });
  3608. svr.wait_until_ready();
  3609. {
  3610. Client cli(HOST, PORT);
  3611. cli.set_path_encode(false);
  3612. auto res = cli.Get("/foo?a=explicitly+encoded");
  3613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3614. EXPECT_EQ(StatusCode::OK_200, res->status);
  3615. // This expects it back with a space, as the `+` won't have been
  3616. // url-encoded, and server-side the params get decoded turning `+`
  3617. // into spaces.
  3618. EXPECT_EQ("explicitly encoded", res->body);
  3619. }
  3620. }
  3621. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3622. // When path encoding is disabled the client must transmit the supplied
  3623. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3624. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3625. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3626. // than a space (0x20). Assert on the raw wire target to catch this.
  3627. Server svr;
  3628. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3629. svr.Get("/foo", [&](const Request &req, Response &res) {
  3630. EXPECT_EQ(expected_target, req.target);
  3631. res.status = StatusCode::OK_200;
  3632. });
  3633. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3634. auto se = detail::scope_exit([&] {
  3635. svr.stop();
  3636. thread.join();
  3637. ASSERT_FALSE(svr.is_running());
  3638. });
  3639. svr.wait_until_ready();
  3640. {
  3641. Client cli(HOST, PORT);
  3642. cli.set_path_encode(false);
  3643. auto res = cli.Get(expected_target.c_str());
  3644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3645. EXPECT_EQ(StatusCode::OK_200, res->status);
  3646. }
  3647. }
  3648. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3649. // `open_stream()` used to skip the path encoding that the buffered send
  3650. // path applies, so the same `path` produced different bytes in the request
  3651. // line depending on which API was used. Assert the two agree.
  3652. Server svr;
  3653. std::string target;
  3654. svr.Get(".*", [&](const Request &req, Response &res) {
  3655. target = req.target;
  3656. res.status = StatusCode::OK_200;
  3657. });
  3658. auto port = svr.bind_to_any_port(HOST);
  3659. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3660. auto se = detail::scope_exit([&] {
  3661. svr.stop();
  3662. thread.join();
  3663. ASSERT_FALSE(svr.is_running());
  3664. });
  3665. svr.wait_until_ready();
  3666. struct {
  3667. const char *path;
  3668. const char *expected;
  3669. } cases[] = {
  3670. {"/a b?x=1", "/a%20b?x=1"},
  3671. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3672. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3673. };
  3674. for (const auto &c : cases) {
  3675. Client cli(HOST, port);
  3676. target.clear();
  3677. auto res = cli.Get(c.path);
  3678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3679. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3680. auto buffered_target = target;
  3681. target.clear();
  3682. auto handle = cli.open_stream("GET", c.path);
  3683. EXPECT_TRUE(handle.is_valid())
  3684. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3685. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3686. }
  3687. }
  3688. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3689. // The `set_path_encode(false)` contract — transmit the supplied target
  3690. // verbatim — must hold for the streaming API too.
  3691. Server svr;
  3692. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3693. std::string target;
  3694. svr.Get("/foo", [&](const Request &req, Response &res) {
  3695. target = req.target;
  3696. res.status = StatusCode::OK_200;
  3697. });
  3698. auto port = svr.bind_to_any_port(HOST);
  3699. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3700. auto se = detail::scope_exit([&] {
  3701. svr.stop();
  3702. thread.join();
  3703. ASSERT_FALSE(svr.is_running());
  3704. });
  3705. svr.wait_until_ready();
  3706. {
  3707. Client cli(HOST, port);
  3708. cli.set_path_encode(false);
  3709. auto handle = cli.open_stream("GET", expected_target);
  3710. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3711. EXPECT_EQ(expected_target, target);
  3712. }
  3713. }
  3714. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3715. // With path encoding enabled a CR/LF in the target is percent-encoded
  3716. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3717. // write_request_line still backstops `set_path_encode(false)`, which is
  3718. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3719. Server svr;
  3720. // Captured before routing: the decoded path contains a newline, which a
  3721. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3722. std::string target;
  3723. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3724. target = req.target;
  3725. res.status = StatusCode::OK_200;
  3726. return Server::HandlerResponse::Handled;
  3727. });
  3728. auto port = svr.bind_to_any_port(HOST);
  3729. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3730. auto se = detail::scope_exit([&] {
  3731. svr.stop();
  3732. thread.join();
  3733. ASSERT_FALSE(svr.is_running());
  3734. });
  3735. svr.wait_until_ready();
  3736. {
  3737. Client cli(HOST, port);
  3738. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3739. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3740. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3741. }
  3742. }
  3743. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3744. // Every control character is percent-encoded, not just CR/LF, so the target
  3745. // passes the request-target check in write_request_line.
  3746. Server svr;
  3747. std::string target;
  3748. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3749. target = req.target;
  3750. res.status = StatusCode::OK_200;
  3751. return Server::HandlerResponse::Handled;
  3752. });
  3753. auto port = svr.bind_to_any_port(HOST);
  3754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3755. auto se = detail::scope_exit([&] {
  3756. svr.stop();
  3757. thread.join();
  3758. ASSERT_FALSE(svr.is_running());
  3759. });
  3760. svr.wait_until_ready();
  3761. {
  3762. Client cli(HOST, port);
  3763. auto res = cli.Get("/a\tb\x1b\x7f");
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. EXPECT_EQ("/a%09b%1B%7F", target);
  3766. }
  3767. }
  3768. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3769. // Nothing may reach the wire: a raw CR/LF target would split the request
  3770. // line and inject headers.
  3771. Server svr;
  3772. // Pre-routing so that "not called" means nothing reached the server at all,
  3773. // rather than merely failing to match a handler pattern.
  3774. auto handler_called = false;
  3775. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3776. handler_called = true;
  3777. res.status = StatusCode::OK_200;
  3778. return Server::HandlerResponse::Handled;
  3779. });
  3780. auto port = svr.bind_to_any_port(HOST);
  3781. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3782. auto se = detail::scope_exit([&] {
  3783. svr.stop();
  3784. thread.join();
  3785. ASSERT_FALSE(svr.is_running());
  3786. });
  3787. svr.wait_until_ready();
  3788. {
  3789. Client cli(HOST, port);
  3790. cli.set_path_encode(false);
  3791. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3792. EXPECT_FALSE(handle.is_valid());
  3793. EXPECT_EQ(Error::Write, handle.error);
  3794. EXPECT_FALSE(handler_called);
  3795. }
  3796. }
  3797. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3798. // Which of the two branches runs is decided by whether the query component
  3799. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3800. // an empty query and must still fall back to building one from
  3801. // `req.params`, while a non-empty query must win over `req.params`.
  3802. Server svr;
  3803. std::string target;
  3804. svr.Get("/foo", [&](const Request &req, Response &res) {
  3805. target = req.target;
  3806. res.status = StatusCode::OK_200;
  3807. });
  3808. auto port = svr.bind_to_any_port(HOST);
  3809. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. {
  3817. // Trailing `?` -> empty query component -> `req.params` is used.
  3818. Client cli(HOST, port);
  3819. Request req;
  3820. req.method = "GET";
  3821. req.path = "/foo?";
  3822. req.params.emplace("a", "1");
  3823. target.clear();
  3824. auto res = cli.send(req);
  3825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3826. EXPECT_EQ("/foo?a=1", target);
  3827. }
  3828. {
  3829. // Non-empty query in `req.path` -> `req.params` is not appended.
  3830. Client cli(HOST, port);
  3831. Request req;
  3832. req.method = "GET";
  3833. req.path = "/foo?b=2";
  3834. req.params.emplace("a", "1");
  3835. target.clear();
  3836. auto res = cli.send(req);
  3837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3838. EXPECT_EQ("/foo?b=2", target);
  3839. }
  3840. }
  3841. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3842. Server svr;
  3843. svr.Get("/", [](const Request &req, Response &) {
  3844. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3845. });
  3846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3847. auto se = detail::scope_exit([&] {
  3848. svr.stop();
  3849. thread.join();
  3850. ASSERT_FALSE(svr.is_running());
  3851. });
  3852. svr.wait_until_ready();
  3853. {
  3854. Client cli(HOST, PORT);
  3855. cli.set_path_encode(false);
  3856. auto res = cli.Get("/?something=%0A");
  3857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3858. EXPECT_EQ(StatusCode::OK_200, res->status);
  3859. }
  3860. }
  3861. TEST(BindServerTest, BindDualStack) {
  3862. Server svr;
  3863. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3864. res.set_content("Hello World!", "text/plain");
  3865. });
  3866. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3867. auto se = detail::scope_exit([&] {
  3868. svr.stop();
  3869. thread.join();
  3870. ASSERT_FALSE(svr.is_running());
  3871. });
  3872. svr.wait_until_ready();
  3873. {
  3874. Client cli("127.0.0.1", PORT);
  3875. auto res = cli.Get("/1");
  3876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3877. EXPECT_EQ(StatusCode::OK_200, res->status);
  3878. EXPECT_EQ("Hello World!", res->body);
  3879. }
  3880. {
  3881. Client cli("::1", PORT);
  3882. auto res = cli.Get("/1");
  3883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3884. EXPECT_EQ(StatusCode::OK_200, res->status);
  3885. EXPECT_EQ("Hello World!", res->body);
  3886. }
  3887. }
  3888. TEST(BindServerTest, BindAndListenSeparately) {
  3889. Server svr;
  3890. int port = svr.bind_to_any_port("0.0.0.0");
  3891. ASSERT_TRUE(svr.is_valid());
  3892. ASSERT_TRUE(port > 0);
  3893. svr.stop();
  3894. }
  3895. // Reports whether anything is still listening on a loopback port. A plain
  3896. // connect() is used instead of a Client request because a socket left bound by
  3897. // mistake accepts the connection into its backlog and never answers, which
  3898. // would hang the test instead of failing it.
  3899. static bool is_loopback_port_accepting(int port) {
  3900. sockaddr_in addr{};
  3901. addr.sin_family = AF_INET;
  3902. addr.sin_port = htons(static_cast<uint16_t>(port));
  3903. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3904. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3905. EXPECT_NE(sock, INVALID_SOCKET);
  3906. if (sock == INVALID_SOCKET) { return false; }
  3907. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3908. static_cast<socklen_t>(sizeof(addr)));
  3909. detail::close_socket(sock);
  3910. return ret == 0;
  3911. }
  3912. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3913. Server svr;
  3914. auto port = svr.bind_to_any_port("127.0.0.1");
  3915. ASSERT_TRUE(port > 0);
  3916. svr.stop();
  3917. // bind_to_any_port() already called listen(2), so until stop() closed the
  3918. // descriptor the port kept accepting connections into the backlog. ASSERT
  3919. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3920. // below blocks forever in the accept loop.
  3921. ASSERT_FALSE(is_loopback_port_accepting(port));
  3922. // Nothing is left to accept on, so listen_after_bind() must report failure
  3923. // instead of returning success without ever serving.
  3924. EXPECT_FALSE(svr.listen_after_bind());
  3925. // The failed listen marks the server decommissioned, so a waiter returns
  3926. // instead of spinning forever.
  3927. svr.wait_until_ready();
  3928. }
  3929. #ifdef CPPHTTPLIB_SSL_ENABLED
  3930. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3931. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3932. CLIENT_CA_CERT_DIR);
  3933. int port = svr.bind_to_any_port("0.0.0.0");
  3934. ASSERT_TRUE(svr.is_valid());
  3935. ASSERT_TRUE(port > 0);
  3936. svr.stop();
  3937. }
  3938. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3939. // or a rejected CustomRoute() registration would not stop the server binding.
  3940. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3942. CLIENT_CA_CERT_DIR);
  3943. ASSERT_TRUE(svr.is_valid());
  3944. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3945. EXPECT_FALSE(svr.is_valid());
  3946. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3947. }
  3948. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3949. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3950. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3951. int port = svr.bind_to_any_port("0.0.0.0");
  3952. ASSERT_TRUE(svr.is_valid());
  3953. ASSERT_TRUE(port > 0);
  3954. svr.stop();
  3955. }
  3956. TEST(BindServerTest, UpdateCertsPem) {
  3957. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3958. int port = svr.bind_to_any_port("0.0.0.0");
  3959. ASSERT_TRUE(svr.is_valid());
  3960. ASSERT_TRUE(port > 0);
  3961. // Read PEM files
  3962. std::string cert_pem, key_pem, ca_pem;
  3963. read_file(SERVER_CERT_FILE, cert_pem);
  3964. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3965. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3966. // Update server certificates using PEM API
  3967. ASSERT_TRUE(
  3968. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3969. ASSERT_TRUE(svr.is_valid());
  3970. svr.stop();
  3971. }
  3972. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3973. // Start server with client CA (enables client auth)
  3974. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3975. ASSERT_TRUE(svr.is_valid());
  3976. bool handler_called = false;
  3977. svr.Get("/test", [&](const Request &req, Response &res) {
  3978. handler_called = true;
  3979. // Verify client certificate is present
  3980. auto cert = req.peer_cert();
  3981. EXPECT_TRUE(static_cast<bool>(cert));
  3982. res.set_content("ok", "text/plain");
  3983. });
  3984. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3985. auto se = detail::scope_exit([&] {
  3986. svr.stop();
  3987. t.join();
  3988. ASSERT_FALSE(svr.is_running());
  3989. });
  3990. svr.wait_until_ready();
  3991. // Read PEM files
  3992. std::string cert_pem, key_pem, ca_pem;
  3993. read_file(SERVER_CERT_FILE, cert_pem);
  3994. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3995. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3996. // Update server certificates and client CA using PEM API while server running
  3997. ASSERT_TRUE(
  3998. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3999. // Connect with client certificate
  4000. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4001. cli.enable_server_certificate_verification(false);
  4002. cli.set_connection_timeout(30);
  4003. auto res = cli.Get("/test");
  4004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4005. ASSERT_EQ(StatusCode::OK_200, res->status);
  4006. ASSERT_TRUE(handler_called);
  4007. EXPECT_EQ("ok", res->body);
  4008. }
  4009. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4011. ASSERT_TRUE(svr.is_valid());
  4012. svr.Get("/test", [](const Request &, Response &res) {
  4013. res.set_content("ok", "text/plain");
  4014. });
  4015. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4016. auto se = detail::scope_exit([&] {
  4017. svr.stop();
  4018. t.join();
  4019. ASSERT_FALSE(svr.is_running());
  4020. });
  4021. svr.wait_until_ready();
  4022. auto get = [] {
  4023. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4024. cli.enable_server_certificate_verification(false);
  4025. return cli.Get("/test");
  4026. };
  4027. ASSERT_TRUE(get());
  4028. // A CA that did not sign the client's certificate takes the old one's place.
  4029. std::string cert_pem, key_pem, ca_pem;
  4030. read_file(SERVER_CERT_FILE, cert_pem);
  4031. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4032. read_file(SERVER_CERT2_FILE, ca_pem);
  4033. ASSERT_TRUE(
  4034. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4035. EXPECT_FALSE(get());
  4036. }
  4037. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4038. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4039. ASSERT_TRUE(svr.is_valid());
  4040. svr.Get("/test", [](const Request &, Response &res) {
  4041. res.set_content("ok", "text/plain");
  4042. });
  4043. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4044. auto se = detail::scope_exit([&] {
  4045. svr.stop();
  4046. t.join();
  4047. ASSERT_FALSE(svr.is_running());
  4048. });
  4049. svr.wait_until_ready();
  4050. // A connection that sends no ClientHello keeps its handshake in progress,
  4051. // once the server has had a moment to start it.
  4052. auto error = Error::Success;
  4053. auto sock = detail::create_client_socket(
  4054. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4055. /*connection_timeout_sec=*/5, 0,
  4056. /*read_timeout_sec=*/5, 0,
  4057. /*write_timeout_sec=*/5, 0, std::string(), error);
  4058. ASSERT_NE(INVALID_SOCKET, sock);
  4059. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4060. std::string cert_pem, key_pem;
  4061. read_file(SERVER_CERT_FILE, cert_pem);
  4062. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4063. auto update = std::async(std::launch::async, [&]() {
  4064. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4065. });
  4066. EXPECT_EQ(std::future_status::timeout,
  4067. update.wait_for(std::chrono::milliseconds(200)));
  4068. detail::close_socket(sock);
  4069. EXPECT_TRUE(update.get());
  4070. SSLClient cli(HOST, PORT);
  4071. cli.enable_server_certificate_verification(false);
  4072. auto res = cli.Get("/test");
  4073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4074. EXPECT_EQ(StatusCode::OK_200, res->status);
  4075. }
  4076. #endif
  4077. TEST(ErrorHandlerTest, ContentLength) {
  4078. Server svr;
  4079. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4080. res.status = StatusCode::OK_200;
  4081. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4082. "text/html"); // <= Content-Length still 13
  4083. });
  4084. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4085. res.set_content("Hello World!\n", "text/plain");
  4086. res.status = 524;
  4087. });
  4088. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4089. auto se = detail::scope_exit([&] {
  4090. svr.stop();
  4091. thread.join();
  4092. ASSERT_FALSE(svr.is_running());
  4093. });
  4094. svr.wait_until_ready();
  4095. {
  4096. Client cli(HOST, PORT);
  4097. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4099. EXPECT_EQ(StatusCode::OK_200, res->status);
  4100. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4101. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4102. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4103. }
  4104. }
  4105. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4106. TEST(ExceptionTest, WithoutExceptionHandler) {
  4107. Server svr;
  4108. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4109. throw std::runtime_error("exception...");
  4110. });
  4111. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4112. throw std::runtime_error("exception\r\n...");
  4113. });
  4114. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4115. auto se = detail::scope_exit([&] {
  4116. svr.stop();
  4117. listen_thread.join();
  4118. ASSERT_FALSE(svr.is_running());
  4119. });
  4120. svr.wait_until_ready();
  4121. Client cli("localhost", PORT);
  4122. {
  4123. auto res = cli.Get("/exception");
  4124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4125. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4126. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4127. }
  4128. {
  4129. auto res = cli.Get("/unknown");
  4130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4131. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4132. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4133. }
  4134. }
  4135. TEST(ExceptionTest, WithExceptionHandler) {
  4136. Server svr;
  4137. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4138. std::exception_ptr ep) {
  4139. EXPECT_FALSE(ep == nullptr);
  4140. try {
  4141. std::rethrow_exception(ep);
  4142. } catch (std::exception &e) {
  4143. EXPECT_EQ("abc", std::string(e.what()));
  4144. } catch (...) {}
  4145. res.status = StatusCode::InternalServerError_500;
  4146. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4147. "text/html"); // <= Content-Length still 13 at this point
  4148. });
  4149. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4150. res.set_content("Hello World!\n", "text/plain");
  4151. throw std::runtime_error("abc");
  4152. });
  4153. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4154. auto se = detail::scope_exit([&] {
  4155. svr.stop();
  4156. thread.join();
  4157. ASSERT_FALSE(svr.is_running());
  4158. });
  4159. svr.wait_until_ready();
  4160. for (size_t i = 0; i < 10; i++) {
  4161. Client cli(HOST, PORT);
  4162. for (size_t j = 0; j < 100; j++) {
  4163. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4165. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4166. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4167. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4168. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4169. }
  4170. cli.set_keep_alive(true);
  4171. for (size_t j = 0; j < 100; j++) {
  4172. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4174. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4175. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4176. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4177. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4178. }
  4179. }
  4180. }
  4181. TEST(ExceptionTest, AndErrorHandler) {
  4182. Server svr;
  4183. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4184. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4185. });
  4186. svr.set_exception_handler(
  4187. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4188. EXPECT_FALSE(ep == nullptr);
  4189. try {
  4190. std::rethrow_exception(ep);
  4191. } catch (std::exception &e) {
  4192. res.set_content(e.what(), "text/html");
  4193. } catch (...) {}
  4194. res.status = StatusCode::InternalServerError_500;
  4195. });
  4196. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4197. throw std::runtime_error("EXCEPTION");
  4198. });
  4199. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4200. res.set_content("ERROR", "text/html");
  4201. res.status = StatusCode::InternalServerError_500;
  4202. });
  4203. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4204. auto se = detail::scope_exit([&] {
  4205. svr.stop();
  4206. thread.join();
  4207. ASSERT_FALSE(svr.is_running());
  4208. });
  4209. svr.wait_until_ready();
  4210. Client cli(HOST, PORT);
  4211. {
  4212. auto res = cli.Get("/exception");
  4213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4214. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4215. EXPECT_EQ("EXCEPTION", res->body);
  4216. }
  4217. {
  4218. auto res = cli.Get("/error");
  4219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4220. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4221. EXPECT_EQ("ERROR", res->body);
  4222. }
  4223. {
  4224. auto res = cli.Get("/invalid");
  4225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4226. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4227. EXPECT_EQ("NOT_FOUND", res->body);
  4228. }
  4229. }
  4230. #endif
  4231. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4232. // process_request() wraps only routing() in a try/catch, so an exception from
  4233. // any other user callback used to unwind into the task queue - which does not
  4234. // catch - and terminate the process. Each test below runs the server on a
  4235. // single worker thread: a guard that catches the exception but still loses the
  4236. // thread would otherwise be hidden by a spare worker serving the follow-up
  4237. // request. Note that a regression here aborts the whole test binary rather
  4238. // than failing one test.
  4239. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4240. Server svr;
  4241. svr.new_task_queue = [] { return new ThreadPool(1); };
  4242. std::atomic<int> reported{0};
  4243. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4244. if (err == Error::UserCallbackException) { reported++; }
  4245. });
  4246. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4247. res.set_content_provider(
  4248. 1024, "text/plain",
  4249. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4250. sink.write("hello", 5);
  4251. throw std::runtime_error("from the content provider");
  4252. });
  4253. });
  4254. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4255. res.set_content("ok", "text/plain");
  4256. });
  4257. auto port = svr.bind_to_any_port(HOST);
  4258. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4259. auto se = detail::scope_exit([&] {
  4260. svr.stop();
  4261. listen_thread.join();
  4262. ASSERT_FALSE(svr.is_running());
  4263. });
  4264. svr.wait_until_ready();
  4265. {
  4266. Client cli(HOST, port);
  4267. cli.set_read_timeout(5, 0);
  4268. EXPECT_FALSE(cli.Get("/throw"));
  4269. }
  4270. EXPECT_TRUE(svr.is_running());
  4271. EXPECT_EQ(1, reported.load());
  4272. // A request on a fresh connection is still served.
  4273. {
  4274. Client cli(HOST, port);
  4275. auto res = cli.Get("/ok");
  4276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4277. EXPECT_EQ(StatusCode::OK_200, res->status);
  4278. EXPECT_EQ("ok", res->body);
  4279. }
  4280. }
  4281. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4282. Server svr;
  4283. svr.new_task_queue = [] { return new ThreadPool(1); };
  4284. std::atomic<bool> should_throw{true};
  4285. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4286. res.set_content("hi", "text/plain");
  4287. });
  4288. svr.set_post_routing_handler(
  4289. [&](const Request & /*req*/, Response & /*res*/) {
  4290. if (should_throw) {
  4291. throw std::runtime_error("from the post-routing handler");
  4292. }
  4293. });
  4294. auto port = svr.bind_to_any_port(HOST);
  4295. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4296. auto se = detail::scope_exit([&] {
  4297. svr.stop();
  4298. listen_thread.join();
  4299. ASSERT_FALSE(svr.is_running());
  4300. });
  4301. svr.wait_until_ready();
  4302. {
  4303. Client cli(HOST, port);
  4304. cli.set_read_timeout(5, 0);
  4305. EXPECT_FALSE(cli.Get("/hi"));
  4306. }
  4307. EXPECT_TRUE(svr.is_running());
  4308. should_throw = false;
  4309. {
  4310. Client cli(HOST, port);
  4311. auto res = cli.Get("/hi");
  4312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4313. EXPECT_EQ(StatusCode::OK_200, res->status);
  4314. EXPECT_EQ("hi", res->body);
  4315. }
  4316. }
  4317. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4318. // The guard reports the caught exception through the error logger, which is
  4319. // a user callback too. A logger that throws has to be contained as well, or
  4320. // the process would terminate from inside the catch.
  4321. Server svr;
  4322. svr.new_task_queue = [] { return new ThreadPool(1); };
  4323. std::atomic<int> reported{0};
  4324. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4325. if (err == Error::UserCallbackException) {
  4326. reported++;
  4327. throw std::runtime_error("from the error logger");
  4328. }
  4329. });
  4330. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4331. res.set_content_provider(
  4332. 1024, "text/plain",
  4333. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4334. sink.write("hello", 5);
  4335. throw std::runtime_error("from the content provider");
  4336. });
  4337. });
  4338. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4339. res.set_content("ok", "text/plain");
  4340. });
  4341. auto port = svr.bind_to_any_port(HOST);
  4342. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4343. auto se = detail::scope_exit([&] {
  4344. svr.stop();
  4345. listen_thread.join();
  4346. ASSERT_FALSE(svr.is_running());
  4347. });
  4348. svr.wait_until_ready();
  4349. {
  4350. Client cli(HOST, port);
  4351. cli.set_read_timeout(5, 0);
  4352. EXPECT_FALSE(cli.Get("/throw"));
  4353. }
  4354. EXPECT_TRUE(svr.is_running());
  4355. EXPECT_EQ(1, reported.load());
  4356. {
  4357. Client cli(HOST, port);
  4358. auto res = cli.Get("/ok");
  4359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4360. EXPECT_EQ(StatusCode::OK_200, res->status);
  4361. EXPECT_EQ("ok", res->body);
  4362. }
  4363. }
  4364. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4365. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4366. // so the exception unwinds through the ws::WebSocket object on its way to
  4367. // the guard. None of the HTTP cases above cross that.
  4368. Server svr;
  4369. svr.new_task_queue = [] { return new ThreadPool(1); };
  4370. std::atomic<int> reported{0};
  4371. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4372. if (err == Error::UserCallbackException) { reported++; }
  4373. });
  4374. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4375. throw std::runtime_error("from the WebSocket handler");
  4376. });
  4377. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4378. res.set_content("ok", "text/plain");
  4379. });
  4380. auto port = svr.bind_to_any_port(HOST);
  4381. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4382. auto se = detail::scope_exit([&] {
  4383. svr.stop();
  4384. listen_thread.join();
  4385. ASSERT_FALSE(svr.is_running());
  4386. });
  4387. svr.wait_until_ready();
  4388. {
  4389. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4390. "/ws");
  4391. auto res = client.connect();
  4392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4393. // The server dropped the connection instead of dying.
  4394. std::string msg;
  4395. EXPECT_FALSE(client.read(msg));
  4396. client.close();
  4397. }
  4398. EXPECT_TRUE(svr.is_running());
  4399. EXPECT_EQ(1, reported.load());
  4400. {
  4401. Client cli(HOST, port);
  4402. auto res = cli.Get("/ok");
  4403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4404. EXPECT_EQ(StatusCode::OK_200, res->status);
  4405. EXPECT_EQ("ok", res->body);
  4406. }
  4407. }
  4408. #ifdef CPPHTTPLIB_SSL_ENABLED
  4409. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4410. // SSLServer::process_and_close_socket() is a separate overload with its own
  4411. // guard, so it is exercised on its own.
  4412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4413. ASSERT_TRUE(svr.is_valid());
  4414. svr.new_task_queue = [] { return new ThreadPool(1); };
  4415. std::atomic<int> reported{0};
  4416. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4417. if (err == Error::UserCallbackException) { reported++; }
  4418. });
  4419. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4420. res.set_content_provider(
  4421. 1024, "text/plain",
  4422. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4423. sink.write("hello", 5);
  4424. throw std::runtime_error("from the content provider");
  4425. });
  4426. });
  4427. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4428. res.set_content("ok", "text/plain");
  4429. });
  4430. auto port = svr.bind_to_any_port(HOST);
  4431. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4432. auto se = detail::scope_exit([&] {
  4433. svr.stop();
  4434. listen_thread.join();
  4435. ASSERT_FALSE(svr.is_running());
  4436. });
  4437. svr.wait_until_ready();
  4438. {
  4439. SSLClient cli(HOST, port);
  4440. cli.enable_server_certificate_verification(false);
  4441. cli.set_read_timeout(5, 0);
  4442. EXPECT_FALSE(cli.Get("/throw"));
  4443. }
  4444. EXPECT_TRUE(svr.is_running());
  4445. EXPECT_EQ(1, reported.load());
  4446. {
  4447. SSLClient cli(HOST, port);
  4448. cli.enable_server_certificate_verification(false);
  4449. auto res = cli.Get("/ok");
  4450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4451. EXPECT_EQ(StatusCode::OK_200, res->status);
  4452. EXPECT_EQ("ok", res->body);
  4453. }
  4454. }
  4455. #endif
  4456. #endif
  4457. TEST(NoContentTest, ContentLength) {
  4458. Server svr;
  4459. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4460. res.status = StatusCode::NoContent_204;
  4461. });
  4462. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4463. auto se = detail::scope_exit([&] {
  4464. svr.stop();
  4465. thread.join();
  4466. ASSERT_FALSE(svr.is_running());
  4467. });
  4468. svr.wait_until_ready();
  4469. {
  4470. Client cli(HOST, PORT);
  4471. auto res = cli.Get("/hi");
  4472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4473. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4474. // RFC 9110 8.6: none in a 204 response
  4475. EXPECT_FALSE(res->has_header("Content-Length"));
  4476. }
  4477. }
  4478. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4479. Server svr;
  4480. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4481. res.set_header("Content-Length", "5");
  4482. res.set_content("hello world", "text/plain");
  4483. });
  4484. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4485. // A body that reads as the last chunk, were it taken as chunked
  4486. res.set_header("Transfer-Encoding", "chunked");
  4487. res.set_content("0\r\n\r\n", "text/plain");
  4488. });
  4489. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4490. res.set_header("Content-Length", "2");
  4491. res.set_content_provider(5, "text/plain",
  4492. [](size_t offset, size_t length, DataSink &sink) {
  4493. sink.write(&"hello"[offset], length);
  4494. return true;
  4495. });
  4496. });
  4497. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4498. res.set_header("Content-Length", "1234");
  4499. });
  4500. thread t = thread([&] { svr.listen(HOST, PORT); });
  4501. auto se = detail::scope_exit([&] {
  4502. svr.stop();
  4503. t.join();
  4504. ASSERT_FALSE(svr.is_running());
  4505. });
  4506. svr.wait_until_ready();
  4507. Client cli(HOST, PORT);
  4508. cli.set_read_timeout(1, 0);
  4509. auto expect_body = [&](const Result &res, const std::string &body) {
  4510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4511. EXPECT_EQ(body, res->body);
  4512. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4513. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4514. };
  4515. Headers identity{{"Accept-Encoding", ""}};
  4516. expect_body(cli.Get("/body", identity), "hello world");
  4517. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4518. expect_body(cli.Get("/body",
  4519. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4520. "he");
  4521. expect_body(cli.Get("/provider", identity), "hello");
  4522. expect_body(cli.Get("/empty", identity), "");
  4523. // A HEAD response may give the length of the body a GET would get.
  4524. auto res = cli.Head("/empty");
  4525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4526. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4527. }
  4528. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4529. Server svr;
  4530. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4531. res.set_content("short", "text/plain");
  4532. });
  4533. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4534. res.body += " with a footer";
  4535. res.set_header("Transfer-Encoding", "chunked");
  4536. });
  4537. thread t = thread([&] { svr.listen(HOST, PORT); });
  4538. auto se = detail::scope_exit([&] {
  4539. svr.stop();
  4540. t.join();
  4541. ASSERT_FALSE(svr.is_running());
  4542. });
  4543. svr.wait_until_ready();
  4544. Client cli(HOST, PORT);
  4545. cli.set_read_timeout(1, 0);
  4546. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4548. EXPECT_EQ("short with a footer", res->body);
  4549. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4550. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4551. }
  4552. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4553. #ifdef CPPHTTPLIB_SSL_ENABLED
  4554. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4555. ASSERT_TRUE(svr.is_valid());
  4556. #else
  4557. Server svr;
  4558. #endif
  4559. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4560. if (req.path == "/routing_handler") {
  4561. res.set_header("PRE_ROUTING", "on");
  4562. res.set_content("Routing Handler", "text/plain");
  4563. return httplib::Server::HandlerResponse::Handled;
  4564. }
  4565. return httplib::Server::HandlerResponse::Unhandled;
  4566. });
  4567. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4568. res.set_content("Error", "text/html");
  4569. });
  4570. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4571. if (req.path == "/routing_handler") {
  4572. res.set_header("POST_ROUTING", "on");
  4573. }
  4574. });
  4575. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4576. res.set_content("Hello World!\n", "text/plain");
  4577. });
  4578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4579. auto se = detail::scope_exit([&] {
  4580. svr.stop();
  4581. thread.join();
  4582. ASSERT_FALSE(svr.is_running());
  4583. });
  4584. svr.wait_until_ready();
  4585. {
  4586. #ifdef CPPHTTPLIB_SSL_ENABLED
  4587. SSLClient cli(HOST, PORT);
  4588. cli.enable_server_certificate_verification(false);
  4589. #else
  4590. Client cli(HOST, PORT);
  4591. #endif
  4592. auto res = cli.Get("/routing_handler");
  4593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4594. EXPECT_EQ(StatusCode::OK_200, res->status);
  4595. EXPECT_EQ("Routing Handler", res->body);
  4596. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4597. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4598. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4599. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4600. }
  4601. {
  4602. #ifdef CPPHTTPLIB_SSL_ENABLED
  4603. SSLClient cli(HOST, PORT);
  4604. cli.enable_server_certificate_verification(false);
  4605. #else
  4606. Client cli(HOST, PORT);
  4607. #endif
  4608. auto res = cli.Get("/hi");
  4609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4610. EXPECT_EQ(StatusCode::OK_200, res->status);
  4611. EXPECT_EQ("Hello World!\n", res->body);
  4612. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4613. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4614. }
  4615. {
  4616. #ifdef CPPHTTPLIB_SSL_ENABLED
  4617. SSLClient cli(HOST, PORT);
  4618. cli.enable_server_certificate_verification(false);
  4619. #else
  4620. Client cli(HOST, PORT);
  4621. #endif
  4622. auto res = cli.Get("/aaa");
  4623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4624. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4625. EXPECT_EQ("Error", res->body);
  4626. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4627. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4628. }
  4629. }
  4630. TEST(RequestHandlerTest, PreRequestHandler) {
  4631. auto route_path = "/user/:user";
  4632. Server svr;
  4633. svr.Get("/hi", [](const Request &, Response &res) {
  4634. res.set_content("hi", "text/plain");
  4635. });
  4636. svr.Get(route_path, [](const Request &req, Response &res) {
  4637. res.set_content(req.path_params.at("user"), "text/plain");
  4638. });
  4639. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4640. if (req.matched_route == route_path) {
  4641. auto user = req.path_params.at("user");
  4642. if (user != "john") {
  4643. res.status = StatusCode::Forbidden_403;
  4644. res.set_content("error", "text/html");
  4645. return Server::HandlerResponse::Handled;
  4646. }
  4647. }
  4648. return Server::HandlerResponse::Unhandled;
  4649. });
  4650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4651. auto se = detail::scope_exit([&] {
  4652. svr.stop();
  4653. thread.join();
  4654. ASSERT_FALSE(svr.is_running());
  4655. });
  4656. svr.wait_until_ready();
  4657. Client cli(HOST, PORT);
  4658. {
  4659. auto res = cli.Get("/hi");
  4660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4661. EXPECT_EQ(StatusCode::OK_200, res->status);
  4662. EXPECT_EQ("hi", res->body);
  4663. }
  4664. {
  4665. auto res = cli.Get("/user/john");
  4666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ("john", res->body);
  4669. }
  4670. {
  4671. auto res = cli.Get("/user/invalid-user");
  4672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4673. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4674. EXPECT_EQ("error", res->body);
  4675. }
  4676. }
  4677. // The pre-request handler must run before the request body is read, so a
  4678. // rejected request never forces the server to buffer a (potentially large)
  4679. // body. Here the posted body is larger than the payload limit: if the body
  4680. // were read first the server would answer 413, but because the pre-request
  4681. // handler runs first it answers 403 and the body is never read.
  4682. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4683. Server svr;
  4684. svr.set_payload_max_length(8);
  4685. auto handler_ran = false;
  4686. svr.Post("/reject", [&](const Request &req, Response &res) {
  4687. handler_ran = true;
  4688. res.set_content(req.body, "text/plain");
  4689. });
  4690. svr.Post("/accept", [](const Request &req, Response &res) {
  4691. res.set_content(req.body, "text/plain");
  4692. });
  4693. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4694. if (req.matched_route == "/reject") {
  4695. res.status = StatusCode::Forbidden_403;
  4696. res.set_content("denied", "text/plain");
  4697. return Server::HandlerResponse::Handled;
  4698. }
  4699. return Server::HandlerResponse::Unhandled;
  4700. });
  4701. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4702. auto se = detail::scope_exit([&] {
  4703. svr.stop();
  4704. thread.join();
  4705. ASSERT_FALSE(svr.is_running());
  4706. });
  4707. svr.wait_until_ready();
  4708. Client cli(HOST, PORT);
  4709. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4710. // rejects with 403 before the body is read, so 413 is never reached.
  4711. {
  4712. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4714. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4715. EXPECT_EQ("denied", res->body);
  4716. EXPECT_FALSE(handler_ran);
  4717. }
  4718. // An approved route still reads the body and enforces the payload limit.
  4719. {
  4720. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4722. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4723. }
  4724. }
  4725. TEST(UserDataTest, BasicOperations) {
  4726. httplib::UserData ud;
  4727. // Initially empty
  4728. EXPECT_FALSE(ud.has("key"));
  4729. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4730. // set and get
  4731. ud.set("key", 42);
  4732. EXPECT_TRUE(ud.has("key"));
  4733. auto *p = ud.get<int>("key");
  4734. ASSERT_NE(nullptr, p);
  4735. EXPECT_EQ(42, *p);
  4736. // Type mismatch → nullptr
  4737. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4738. // Overwrite with different type
  4739. ud.set("key", std::string("hello"));
  4740. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4741. auto *s = ud.get<std::string>("key");
  4742. ASSERT_NE(nullptr, s);
  4743. EXPECT_EQ("hello", *s);
  4744. // erase
  4745. ud.erase("key");
  4746. EXPECT_FALSE(ud.has("key"));
  4747. // clear
  4748. ud.set("a", 1);
  4749. ud.set("b", 2);
  4750. ud.clear();
  4751. EXPECT_FALSE(ud.has("a"));
  4752. EXPECT_FALSE(ud.has("b"));
  4753. }
  4754. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4755. struct AuthCtx {
  4756. std::string user_id;
  4757. };
  4758. Server svr;
  4759. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4760. res.user_data.set("auth", AuthCtx{"alice"});
  4761. return Server::HandlerResponse::Unhandled;
  4762. });
  4763. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4764. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4765. ASSERT_NE(nullptr, ctx);
  4766. res.set_content("Hello " + ctx->user_id, "text/plain");
  4767. });
  4768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4769. auto se = detail::scope_exit([&] {
  4770. svr.stop();
  4771. thread.join();
  4772. ASSERT_FALSE(svr.is_running());
  4773. });
  4774. svr.wait_until_ready();
  4775. Client cli(HOST, PORT);
  4776. auto res = cli.Get("/me");
  4777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4778. EXPECT_EQ(StatusCode::OK_200, res->status);
  4779. EXPECT_EQ("Hello alice", res->body);
  4780. }
  4781. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4782. struct RoleCtx {
  4783. std::string role;
  4784. };
  4785. Server svr;
  4786. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4787. res.user_data.set("role", RoleCtx{"admin"});
  4788. return Server::HandlerResponse::Unhandled;
  4789. });
  4790. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4791. auto *ctx = res.user_data.get<RoleCtx>("role");
  4792. ASSERT_NE(nullptr, ctx);
  4793. res.set_content(ctx->role, "text/plain");
  4794. });
  4795. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4796. auto se = detail::scope_exit([&] {
  4797. svr.stop();
  4798. thread.join();
  4799. ASSERT_FALSE(svr.is_running());
  4800. });
  4801. svr.wait_until_ready();
  4802. Client cli(HOST, PORT);
  4803. auto res = cli.Get("/role");
  4804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4805. EXPECT_EQ(StatusCode::OK_200, res->status);
  4806. EXPECT_EQ("admin", res->body);
  4807. }
  4808. TEST(InvalidFormatTest, StatusCode) {
  4809. Server svr;
  4810. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4811. res.set_content("Hello World!\n", "text/plain");
  4812. res.status = 9999; // Status should be a three-digit code...
  4813. });
  4814. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4815. auto se = detail::scope_exit([&] {
  4816. svr.stop();
  4817. thread.join();
  4818. ASSERT_FALSE(svr.is_running());
  4819. });
  4820. svr.wait_until_ready();
  4821. {
  4822. Client cli(HOST, PORT);
  4823. auto res = cli.Get("/hi");
  4824. ASSERT_FALSE(res);
  4825. }
  4826. }
  4827. TEST(URLFragmentTest, WithFragment) {
  4828. Server svr;
  4829. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4830. EXPECT_TRUE(req.target == "/hi");
  4831. });
  4832. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4833. auto se = detail::scope_exit([&] {
  4834. svr.stop();
  4835. thread.join();
  4836. ASSERT_FALSE(svr.is_running());
  4837. });
  4838. svr.wait_until_ready();
  4839. {
  4840. Client cli(HOST, PORT);
  4841. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4842. EXPECT_TRUE(res);
  4843. EXPECT_EQ(StatusCode::OK_200, res->status);
  4844. res = cli.Get("/hi%23key1=val1=key2=val2");
  4845. EXPECT_TRUE(res);
  4846. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4847. }
  4848. }
  4849. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  4850. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  4851. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  4852. Server svr;
  4853. std::vector<std::string> targets;
  4854. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  4855. targets.push_back(req.target);
  4856. });
  4857. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4858. auto se = detail::scope_exit([&] {
  4859. svr.stop();
  4860. thread.join();
  4861. ASSERT_FALSE(svr.is_running());
  4862. });
  4863. svr.wait_until_ready();
  4864. Client cli(HOST, PORT);
  4865. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  4866. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  4867. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  4868. // A '?' after the '#' belongs to the fragment, not to the query.
  4869. Request req;
  4870. req.method = "GET";
  4871. req.path = "/hi#f?x=1";
  4872. req.params.emplace("a", "1");
  4873. Response res;
  4874. auto error = Error::Success;
  4875. EXPECT_TRUE(cli.send(req, res, error));
  4876. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  4877. "/hi?a=1"}),
  4878. targets);
  4879. }
  4880. TEST(HeaderWriter, SetHeaderWriter) {
  4881. Server svr;
  4882. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4883. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4884. return detail::write_headers(strm, hdrs);
  4885. });
  4886. svr.Get("/hi", [](const Request &req, Response &res) {
  4887. auto it = req.headers.find("CustomClientHeader");
  4888. EXPECT_TRUE(it != req.headers.end());
  4889. EXPECT_EQ(it->second, "CustomClientValue");
  4890. res.set_content("Hello World!\n", "text/plain");
  4891. });
  4892. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4893. auto se = detail::scope_exit([&] {
  4894. svr.stop();
  4895. thread.join();
  4896. ASSERT_FALSE(svr.is_running());
  4897. });
  4898. svr.wait_until_ready();
  4899. {
  4900. Client cli(HOST, PORT);
  4901. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4902. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4903. return detail::write_headers(strm, hdrs);
  4904. });
  4905. auto res = cli.Get("/hi");
  4906. EXPECT_TRUE(res);
  4907. EXPECT_EQ(StatusCode::OK_200, res->status);
  4908. auto it = res->headers.find("CustomServerHeader");
  4909. EXPECT_TRUE(it != res->headers.end());
  4910. EXPECT_EQ(it->second, "CustomServerValue");
  4911. }
  4912. }
  4913. class ServerTest : public ::testing::Test {
  4914. protected:
  4915. ServerTest()
  4916. : cli_(HOST, PORT)
  4917. #ifdef CPPHTTPLIB_SSL_ENABLED
  4918. ,
  4919. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4920. #endif
  4921. {
  4922. #ifdef CPPHTTPLIB_SSL_ENABLED
  4923. cli_.enable_server_certificate_verification(false);
  4924. #endif
  4925. // Allow LARGE_DATA (100MB) responses
  4926. cli_.set_payload_max_length(200 * 1024 * 1024);
  4927. }
  4928. virtual void SetUp() {
  4929. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4930. svr_.set_payload_max_length(200 * 1024 * 1024);
  4931. svr_.set_mount_point("/", "./www");
  4932. svr_.set_mount_point("/mount", "./www2");
  4933. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4934. svr_.Get("/hi",
  4935. [&](const Request & /*req*/, Response &res) {
  4936. res.set_content("Hello World!", "text/plain");
  4937. })
  4938. .Get("/file_content",
  4939. [&](const Request & /*req*/, Response &res) {
  4940. res.set_file_content("./www/dir/test.html");
  4941. })
  4942. .Get("/file_content_with_content_type",
  4943. [&](const Request & /*req*/, Response &res) {
  4944. res.set_file_content("./www/file", "text/plain");
  4945. })
  4946. .Get("/invalid_file_content",
  4947. [&](const Request & /*req*/, Response &res) {
  4948. res.set_file_content("./www/dir/invalid_file_path");
  4949. })
  4950. .Get("/http_response_splitting",
  4951. [&](const Request & /*req*/, Response &res) {
  4952. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4953. EXPECT_EQ(0U, res.headers.size());
  4954. EXPECT_FALSE(res.has_header("a"));
  4955. res.set_header("a", "1\nSet-Cookie: a=1");
  4956. EXPECT_EQ(0U, res.headers.size());
  4957. EXPECT_FALSE(res.has_header("a"));
  4958. res.set_header("a", "1\rSet-Cookie: a=1");
  4959. EXPECT_EQ(0U, res.headers.size());
  4960. EXPECT_FALSE(res.has_header("a"));
  4961. res.set_header("a\r\nb", "0");
  4962. EXPECT_EQ(0U, res.headers.size());
  4963. EXPECT_FALSE(res.has_header("a"));
  4964. res.set_header("a\rb", "0");
  4965. EXPECT_EQ(0U, res.headers.size());
  4966. EXPECT_FALSE(res.has_header("a"));
  4967. res.set_header("a\nb", "0");
  4968. EXPECT_EQ(0U, res.headers.size());
  4969. EXPECT_FALSE(res.has_header("a"));
  4970. res.set_redirect("1\r\nSet-Cookie: a=1");
  4971. EXPECT_EQ(0U, res.headers.size());
  4972. EXPECT_FALSE(res.has_header("Location"));
  4973. })
  4974. .Get("/slow",
  4975. [&](const Request & /*req*/, Response &res) {
  4976. std::this_thread::sleep_for(std::chrono::seconds(4));
  4977. res.set_content("slow", "text/plain");
  4978. })
  4979. #if 0
  4980. .Post("/slowpost",
  4981. [&](const Request & /*req*/, Response &res) {
  4982. std::this_thread::sleep_for(std::chrono::seconds(2));
  4983. res.set_content("slow", "text/plain");
  4984. })
  4985. #endif
  4986. .Get("/remote_addr",
  4987. [&](const Request &req, Response &res) {
  4988. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4989. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4990. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4991. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4992. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4993. #endif
  4994. res.set_content(req.remote_addr, "text/plain");
  4995. })
  4996. .Get("/local_addr",
  4997. [&](const Request &req, Response &res) {
  4998. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4999. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5000. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5001. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5002. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5003. #endif
  5004. auto local_addr = req.local_addr;
  5005. auto local_port = std::to_string(req.local_port);
  5006. res.set_content(local_addr.append(":").append(local_port),
  5007. "text/plain");
  5008. })
  5009. .Get("/endwith%",
  5010. [&](const Request & /*req*/, Response &res) {
  5011. res.set_content("Hello World!", "text/plain");
  5012. })
  5013. .Get("/a\\+\\+b",
  5014. [&](const Request &req, Response &res) {
  5015. ASSERT_TRUE(req.has_param("a +b"));
  5016. auto val = req.get_param_value("a +b");
  5017. res.set_content(val, "text/plain");
  5018. })
  5019. .Get("/", [&](const Request & /*req*/,
  5020. Response &res) { res.set_redirect("/hi"); })
  5021. .Post("/1",
  5022. [](const Request & /*req*/, Response &res) {
  5023. res.set_redirect("/2", StatusCode::SeeOther_303);
  5024. })
  5025. .Get("/2",
  5026. [](const Request & /*req*/, Response &res) {
  5027. res.set_content("redirected.", "text/plain");
  5028. res.status = StatusCode::OK_200;
  5029. })
  5030. .Post("/person",
  5031. [&](const Request &req, Response &res) {
  5032. if (req.has_param("name") && req.has_param("note")) {
  5033. persons_[req.get_param_value("name")] =
  5034. req.get_param_value("note");
  5035. } else {
  5036. res.status = StatusCode::BadRequest_400;
  5037. }
  5038. })
  5039. .Put("/person",
  5040. [&](const Request &req, Response &res) {
  5041. if (req.has_param("name") && req.has_param("note")) {
  5042. persons_[req.get_param_value("name")] =
  5043. req.get_param_value("note");
  5044. } else {
  5045. res.status = StatusCode::BadRequest_400;
  5046. }
  5047. })
  5048. .Get("/person/(.*)",
  5049. [&](const Request &req, Response &res) {
  5050. string name = req.matches[1];
  5051. if (persons_.find(name) != persons_.end()) {
  5052. auto note = persons_[name];
  5053. res.set_content(note, "text/plain");
  5054. } else {
  5055. res.status = StatusCode::NotFound_404;
  5056. }
  5057. })
  5058. .Delete("/person",
  5059. [&](const Request &req, Response &res) {
  5060. if (req.has_param("name")) {
  5061. string name = req.get_param_value("name");
  5062. if (persons_.find(name) != persons_.end()) {
  5063. persons_.erase(name);
  5064. res.set_content("DELETED", "text/plain");
  5065. } else {
  5066. res.status = StatusCode::NotFound_404;
  5067. }
  5068. } else {
  5069. res.status = StatusCode::BadRequest_400;
  5070. }
  5071. })
  5072. .Post("/x-www-form-urlencoded-json",
  5073. [&](const Request &req, Response &res) {
  5074. auto json = req.get_param_value("json");
  5075. ASSERT_EQ(JSON_DATA, json);
  5076. res.set_content(json, "appliation/json");
  5077. res.status = StatusCode::OK_200;
  5078. })
  5079. .Get("/streamed-chunked",
  5080. [&](const Request & /*req*/, Response &res) {
  5081. res.set_chunked_content_provider(
  5082. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5083. sink.os << "123";
  5084. sink.os << "456";
  5085. sink.os << "789";
  5086. sink.done();
  5087. return true;
  5088. });
  5089. })
  5090. .Get("/streamed-chunked-with-prohibited-trailer",
  5091. [&](const Request & /*req*/, Response &res) {
  5092. auto i = new int(0);
  5093. // Declare both a prohibited trailer (Content-Length) and an
  5094. // allowed one
  5095. res.set_header("Trailer", "Content-Length, X-Allowed");
  5096. res.set_chunked_content_provider(
  5097. "text/plain",
  5098. [i](size_t /*offset*/, DataSink &sink) {
  5099. switch (*i) {
  5100. case 0: sink.os << "123"; break;
  5101. case 1: sink.os << "456"; break;
  5102. case 2: sink.os << "789"; break;
  5103. case 3: {
  5104. sink.done_with_trailer(
  5105. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5106. } break;
  5107. }
  5108. (*i)++;
  5109. return true;
  5110. },
  5111. [i](bool success) {
  5112. EXPECT_TRUE(success);
  5113. delete i;
  5114. });
  5115. })
  5116. .Get("/streamed-chunked2",
  5117. [&](const Request & /*req*/, Response &res) {
  5118. auto i = new int(0);
  5119. res.set_chunked_content_provider(
  5120. "text/plain",
  5121. [i](size_t /*offset*/, DataSink &sink) {
  5122. switch (*i) {
  5123. case 0: sink.os << "123"; break;
  5124. case 1: sink.os << "456"; break;
  5125. case 2: sink.os << "789"; break;
  5126. case 3: sink.done(); break;
  5127. }
  5128. (*i)++;
  5129. return true;
  5130. },
  5131. [i](bool success) {
  5132. EXPECT_TRUE(success);
  5133. delete i;
  5134. });
  5135. })
  5136. .Get("/streamed-chunked-with-trailer",
  5137. [&](const Request & /*req*/, Response &res) {
  5138. auto i = new int(0);
  5139. res.set_header("Trailer", "Dummy1, Dummy2");
  5140. res.set_chunked_content_provider(
  5141. "text/plain",
  5142. [i](size_t /*offset*/, DataSink &sink) {
  5143. switch (*i) {
  5144. case 0: sink.os << "123"; break;
  5145. case 1: sink.os << "456"; break;
  5146. case 2: sink.os << "789"; break;
  5147. case 3: {
  5148. sink.done_with_trailer(
  5149. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5150. } break;
  5151. }
  5152. (*i)++;
  5153. return true;
  5154. },
  5155. [i](bool success) {
  5156. EXPECT_TRUE(success);
  5157. delete i;
  5158. });
  5159. })
  5160. .Get("/streamed",
  5161. [&](const Request & /*req*/, Response &res) {
  5162. res.set_content_provider(
  5163. 6, "text/plain",
  5164. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5165. sink.os << (offset < 3 ? "a" : "b");
  5166. return true;
  5167. });
  5168. })
  5169. .Get("/streamed-without-length",
  5170. [&](const Request & /*req*/, Response &res) {
  5171. auto data = new std::string("abcdefg");
  5172. res.set_content_provider(
  5173. "text/plain",
  5174. [data](size_t offset, DataSink &sink) {
  5175. if (offset < data->size()) {
  5176. sink.os << data->substr(offset);
  5177. }
  5178. sink.done();
  5179. return true;
  5180. },
  5181. [data](bool success) {
  5182. EXPECT_TRUE(success);
  5183. delete data;
  5184. });
  5185. })
  5186. .Get("/streamed-with-range",
  5187. [&](const Request &req, Response &res) {
  5188. auto data = new std::string("abcdefg");
  5189. // An explicit status keeps the server from picking the 206 it
  5190. // would otherwise choose for a ranged request, so the response
  5191. // is not a partial representation.
  5192. auto status = req.get_param_value("status");
  5193. if (status == "200") {
  5194. res.status = StatusCode::OK_200;
  5195. } else if (status == "403") {
  5196. res.status = StatusCode::Forbidden_403;
  5197. }
  5198. res.set_content_provider(
  5199. data->size(), "text/plain",
  5200. [data](size_t offset, size_t length, DataSink &sink) {
  5201. size_t DATA_CHUNK_SIZE = 4;
  5202. const auto &d = *data;
  5203. auto out_len =
  5204. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5205. auto ret =
  5206. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5207. EXPECT_TRUE(ret);
  5208. return true;
  5209. },
  5210. [data, &req](bool success) {
  5211. EXPECT_EQ(success, !req.has_param("error"));
  5212. delete data;
  5213. });
  5214. })
  5215. .Get("/streamed-cancel",
  5216. [&](const Request & /*req*/, Response &res) {
  5217. res.set_content_provider(
  5218. size_t(-1), "text/plain",
  5219. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5220. sink.os << "data_chunk";
  5221. return true;
  5222. });
  5223. })
  5224. .Get("/regex-with-delimiter",
  5225. [&](const Request &req, Response & /*res*/) {
  5226. ASSERT_TRUE(req.has_param("key"));
  5227. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5228. })
  5229. .Get("/with-range",
  5230. [&](const Request & /*req*/, Response &res) {
  5231. res.set_content("abcdefg", "text/plain");
  5232. })
  5233. .Get("/test-start-time",
  5234. [&](const Request &req, Response & /*res*/) {
  5235. EXPECT_NE(req.start_time_,
  5236. std::chrono::steady_clock::time_point::min());
  5237. })
  5238. .Get("/with-range-customized-response",
  5239. [&](const Request & /*req*/, Response &res) {
  5240. res.status = StatusCode::BadRequest_400;
  5241. res.set_content(JSON_DATA, "application/json");
  5242. })
  5243. .Post("/chunked",
  5244. [&](const Request &req, Response & /*res*/) {
  5245. EXPECT_EQ(req.body, "dechunked post body");
  5246. })
  5247. .Post("/large-chunked",
  5248. [&](const Request &req, Response & /*res*/) {
  5249. std::string expected(6 * 30 * 1024u, 'a');
  5250. EXPECT_EQ(req.body, expected);
  5251. })
  5252. .Post("/multipart",
  5253. [&](const Request &req, Response & /*res*/) {
  5254. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5255. req.form.get_field_count("text2") +
  5256. req.form.get_field_count("file3") +
  5257. req.form.get_field_count("file4"));
  5258. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5259. req.form.get_file_count("file2"));
  5260. ASSERT_TRUE(!req.form.has_file("???"));
  5261. ASSERT_TRUE(!req.form.has_field("???"));
  5262. ASSERT_TRUE(req.body.empty());
  5263. {
  5264. const auto &text = req.form.get_field("text1");
  5265. EXPECT_EQ("text default", text);
  5266. }
  5267. {
  5268. const auto &text = req.form.get_field("text2");
  5269. EXPECT_EQ("aωb", text);
  5270. }
  5271. {
  5272. const auto &file = req.form.get_file("file1");
  5273. EXPECT_EQ("hello.txt", file.filename);
  5274. EXPECT_EQ("text/plain", file.content_type);
  5275. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5276. }
  5277. {
  5278. const auto &file = req.form.get_file("file2");
  5279. EXPECT_EQ("world.json", file.filename);
  5280. EXPECT_EQ("application/json", file.content_type);
  5281. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5282. }
  5283. {
  5284. const auto &text = req.form.get_field("file3");
  5285. EXPECT_EQ(0u, text.size());
  5286. }
  5287. {
  5288. const auto &text = req.form.get_field("file4");
  5289. EXPECT_EQ(0u, text.size());
  5290. }
  5291. })
  5292. .Post("/multipart/multi_file_values",
  5293. [&](const Request &req, Response & /*res*/) {
  5294. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5295. req.form.get_field_count("multi_text1"));
  5296. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5297. ASSERT_TRUE(!req.form.has_file("???"));
  5298. ASSERT_TRUE(!req.form.has_field("???"));
  5299. ASSERT_TRUE(req.body.empty());
  5300. {
  5301. const auto &text = req.form.get_field("text");
  5302. EXPECT_EQ("default text", text);
  5303. }
  5304. {
  5305. const auto &text1_values = req.form.get_fields("multi_text1");
  5306. EXPECT_EQ(2u, text1_values.size());
  5307. EXPECT_EQ("aaaaa", text1_values[0]);
  5308. EXPECT_EQ("bbbbb", text1_values[1]);
  5309. }
  5310. {
  5311. const auto &file1_values = req.form.get_files("multi_file1");
  5312. EXPECT_EQ(2u, file1_values.size());
  5313. auto file1 = file1_values[0];
  5314. EXPECT_EQ(file1.filename, "hello.txt");
  5315. EXPECT_EQ(file1.content_type, "text/plain");
  5316. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5317. auto file2 = file1_values[1];
  5318. EXPECT_EQ(file2.filename, "world.json");
  5319. EXPECT_EQ(file2.content_type, "application/json");
  5320. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5321. }
  5322. })
  5323. .Post("/empty",
  5324. [&](const Request &req, Response &res) {
  5325. EXPECT_EQ(req.body, "");
  5326. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5327. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5328. res.set_content("empty", "text/plain");
  5329. })
  5330. .Post("/empty-no-content-type",
  5331. [&](const Request &req, Response &res) {
  5332. EXPECT_EQ(req.body, "");
  5333. EXPECT_FALSE(req.has_header("Content-Type"));
  5334. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5335. res.set_content("empty-no-content-type", "text/plain");
  5336. })
  5337. .Post("/path-only",
  5338. [&](const Request &req, Response &res) {
  5339. EXPECT_EQ(req.body, "");
  5340. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5341. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5342. res.set_content("path-only", "text/plain");
  5343. })
  5344. .Post("/path-headers-only",
  5345. [&](const Request &req, Response &res) {
  5346. EXPECT_EQ(req.body, "");
  5347. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5348. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5349. EXPECT_EQ("world", req.get_header_value("hello"));
  5350. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5351. res.set_content("path-headers-only", "text/plain");
  5352. })
  5353. .Post("/post-large",
  5354. [&](const Request &req, Response &res) {
  5355. EXPECT_EQ(req.body, LARGE_DATA);
  5356. res.set_content(req.body, "text/plain");
  5357. })
  5358. .Post("/post-loopback",
  5359. [&](const Request &, Response &res,
  5360. ContentReader const &content_reader) {
  5361. std::string body;
  5362. content_reader([&](const char *data, size_t data_length) {
  5363. body.append(data, data_length);
  5364. return true;
  5365. });
  5366. res.set_content(body, "text/plain");
  5367. })
  5368. .Put("/put-loopback",
  5369. [&](const Request &, Response &res,
  5370. ContentReader const &content_reader) {
  5371. std::string body;
  5372. content_reader([&](const char *data, size_t data_length) {
  5373. body.append(data, data_length);
  5374. return true;
  5375. });
  5376. res.set_content(body, "text/plain");
  5377. })
  5378. .Patch("/patch-loopback",
  5379. [&](const Request &, Response &res,
  5380. ContentReader const &content_reader) {
  5381. std::string body;
  5382. content_reader([&](const char *data, size_t data_length) {
  5383. body.append(data, data_length);
  5384. return true;
  5385. });
  5386. res.set_content(body, "text/plain");
  5387. })
  5388. .Put("/empty-no-content-type",
  5389. [&](const Request &req, Response &res) {
  5390. EXPECT_EQ(req.body, "");
  5391. EXPECT_FALSE(req.has_header("Content-Type"));
  5392. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5393. res.set_content("empty-no-content-type", "text/plain");
  5394. })
  5395. .Put("/put",
  5396. [&](const Request &req, Response &res) {
  5397. EXPECT_EQ(req.body, "PUT");
  5398. res.set_content(req.body, "text/plain");
  5399. })
  5400. .Put("/put-large",
  5401. [&](const Request &req, Response &res) {
  5402. EXPECT_EQ(req.body, LARGE_DATA);
  5403. res.set_content(req.body, "text/plain");
  5404. })
  5405. .Patch("/patch",
  5406. [&](const Request &req, Response &res) {
  5407. EXPECT_EQ(req.body, "PATCH");
  5408. res.set_content(req.body, "text/plain");
  5409. })
  5410. .Delete("/delete",
  5411. [&](const Request & /*req*/, Response &res) {
  5412. res.set_content("DELETE", "text/plain");
  5413. })
  5414. .Delete("/delete-body",
  5415. [&](const Request &req, Response &res) {
  5416. EXPECT_EQ(req.body, "content");
  5417. res.set_content(req.body, "text/plain");
  5418. })
  5419. .Options(R"(\*)",
  5420. [&](const Request & /*req*/, Response &res) {
  5421. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5422. })
  5423. .CustomRoute("PROPFIND", "/dav/:id",
  5424. [&](const Request &req, Response &res) {
  5425. res.set_header("x-body-size",
  5426. std::to_string(req.body.size()));
  5427. res.set_header("x-matched-route", req.matched_route);
  5428. res.set_header("x-dav-id", req.path_params.at("id"));
  5429. res.status = StatusCode::MultiStatus_207;
  5430. res.set_content(req.body, "application/xml");
  5431. })
  5432. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5433. [&](const Request &req, Response &res) {
  5434. res.set_header("x-dav-match", req.matches[1]);
  5435. res.status = StatusCode::MultiStatus_207;
  5436. })
  5437. .CustomRoute("MKCOL", "/dav-mkcol",
  5438. [&](const Request &req, Response &res) {
  5439. EXPECT_TRUE(req.body.empty());
  5440. res.status = StatusCode::Created_201;
  5441. })
  5442. .CustomRoute(
  5443. "REPORT", "/dav-report",
  5444. [&](const Request & /*req*/, Response &res,
  5445. const ContentReader &content_reader) {
  5446. std::string body;
  5447. content_reader([&](const char *data, size_t data_length) {
  5448. body.append(data, data_length);
  5449. return true;
  5450. });
  5451. res.set_header("x-body-size", std::to_string(body.size()));
  5452. res.status = StatusCode::MultiStatus_207;
  5453. res.set_content(body, "application/xml");
  5454. })
  5455. .Get("/request-target",
  5456. [&](const Request &req, Response & /*res*/) {
  5457. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5458. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5459. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5460. })
  5461. .Get("/long-query-value",
  5462. [&](const Request &req, Response & /*res*/) {
  5463. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5464. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5465. })
  5466. .Get("/too-long-query-value",
  5467. [&](const Request &req, Response & /*res*/) {
  5468. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5469. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5470. })
  5471. .Get("/array-param",
  5472. [&](const Request &req, Response & /*res*/) {
  5473. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5474. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5475. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5476. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5477. })
  5478. .Get("/array-param-values",
  5479. [&](const Request &req, Response & /*res*/) {
  5480. auto values = req.get_param_values("array");
  5481. EXPECT_EQ(3u, values.size());
  5482. EXPECT_EQ("value1", values[0]);
  5483. EXPECT_EQ("value2", values[1]);
  5484. EXPECT_EQ("value3", values[2]);
  5485. auto empty = req.get_param_values("nonexistent");
  5486. EXPECT_TRUE(empty.empty());
  5487. })
  5488. .Post("/validate-no-multiple-headers",
  5489. [&](const Request &req, Response & /*res*/) {
  5490. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5491. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5492. })
  5493. .Post("/content_receiver",
  5494. [&](const Request &req, Response &res,
  5495. const ContentReader &content_reader) {
  5496. if (req.is_multipart_form_data()) {
  5497. std::vector<FormData> items;
  5498. content_reader(
  5499. [&](const FormData &file) {
  5500. items.push_back(file);
  5501. return true;
  5502. },
  5503. [&](const char *data, size_t data_length) {
  5504. items.back().content.append(data, data_length);
  5505. return true;
  5506. });
  5507. EXPECT_EQ(5u, items.size());
  5508. {
  5509. const auto &file = get_file_value(items, "text1");
  5510. EXPECT_TRUE(file.filename.empty());
  5511. EXPECT_EQ("text default", file.content);
  5512. }
  5513. {
  5514. const auto &file = get_file_value(items, "text2");
  5515. EXPECT_TRUE(file.filename.empty());
  5516. EXPECT_EQ("aωb", file.content);
  5517. }
  5518. {
  5519. const auto &file = get_file_value(items, "file1");
  5520. EXPECT_EQ("hello.txt", file.filename);
  5521. EXPECT_EQ("text/plain", file.content_type);
  5522. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5523. }
  5524. {
  5525. const auto &file = get_file_value(items, "file2");
  5526. EXPECT_EQ("world.json", file.filename);
  5527. EXPECT_EQ("application/json", file.content_type);
  5528. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5529. }
  5530. {
  5531. const auto &file = get_file_value(items, "file3");
  5532. EXPECT_TRUE(file.filename.empty());
  5533. EXPECT_EQ("application/octet-stream", file.content_type);
  5534. EXPECT_EQ(0u, file.content.size());
  5535. }
  5536. } else {
  5537. std::string body;
  5538. content_reader([&](const char *data, size_t data_length) {
  5539. EXPECT_EQ(7U, data_length);
  5540. body.append(data, data_length);
  5541. return true;
  5542. });
  5543. EXPECT_EQ(body, "content");
  5544. res.set_content(body, "text/plain");
  5545. }
  5546. })
  5547. .Put("/content_receiver",
  5548. [&](const Request & /*req*/, Response &res,
  5549. const ContentReader &content_reader) {
  5550. std::string body;
  5551. content_reader([&](const char *data, size_t data_length) {
  5552. body.append(data, data_length);
  5553. return true;
  5554. });
  5555. EXPECT_EQ(body, "content");
  5556. res.set_content(body, "text/plain");
  5557. })
  5558. .Patch("/content_receiver",
  5559. [&](const Request & /*req*/, Response &res,
  5560. const ContentReader &content_reader) {
  5561. std::string body;
  5562. content_reader([&](const char *data, size_t data_length) {
  5563. body.append(data, data_length);
  5564. return true;
  5565. });
  5566. EXPECT_EQ(body, "content");
  5567. res.set_content(body, "text/plain");
  5568. })
  5569. .Post("/query-string-and-body",
  5570. [&](const Request &req, Response & /*res*/) {
  5571. ASSERT_TRUE(req.has_param("key"));
  5572. EXPECT_EQ(req.get_param_value("key"), "value");
  5573. EXPECT_EQ(req.body, "content");
  5574. })
  5575. .Get("/last-request",
  5576. [&](const Request &req, Response & /*res*/) {
  5577. EXPECT_EQ("close", req.get_header_value("Connection"));
  5578. })
  5579. .Get(R"(/redirect/(\d+))",
  5580. [&](const Request &req, Response &res) {
  5581. auto num = std::stoi(req.matches[1]) + 1;
  5582. std::string url = "/redirect/" + std::to_string(num);
  5583. res.set_redirect(url);
  5584. })
  5585. .Post("/binary",
  5586. [&](const Request &req, Response &res) {
  5587. EXPECT_EQ(4U, req.body.size());
  5588. EXPECT_EQ("application/octet-stream",
  5589. req.get_header_value("Content-Type"));
  5590. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5591. res.set_content(req.body, "application/octet-stream");
  5592. })
  5593. .Put("/binary",
  5594. [&](const Request &req, Response &res) {
  5595. EXPECT_EQ(4U, req.body.size());
  5596. EXPECT_EQ("application/octet-stream",
  5597. req.get_header_value("Content-Type"));
  5598. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5599. res.set_content(req.body, "application/octet-stream");
  5600. })
  5601. .Patch("/binary",
  5602. [&](const Request &req, Response &res) {
  5603. EXPECT_EQ(4U, req.body.size());
  5604. EXPECT_EQ("application/octet-stream",
  5605. req.get_header_value("Content-Type"));
  5606. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5607. res.set_content(req.body, "application/octet-stream");
  5608. })
  5609. .Delete("/binary",
  5610. [&](const Request &req, Response &res) {
  5611. EXPECT_EQ(4U, req.body.size());
  5612. EXPECT_EQ("application/octet-stream",
  5613. req.get_header_value("Content-Type"));
  5614. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5615. res.set_content(req.body, "application/octet-stream");
  5616. })
  5617. .Get("/issue1772",
  5618. [&](const Request & /*req*/, Response &res) {
  5619. res.status = 401;
  5620. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5621. })
  5622. .Delete("/issue609",
  5623. [](const httplib::Request &, httplib::Response &res,
  5624. const httplib::ContentReader &) {
  5625. res.set_content("ok", "text/plain");
  5626. })
  5627. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5628. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5629. .Get("/compress",
  5630. [&](const Request & /*req*/, Response &res) {
  5631. res.set_content(
  5632. "12345678901234567890123456789012345678901234567890123456789"
  5633. "01234567890123456789012345678901234567890",
  5634. "text/plain");
  5635. })
  5636. .Get("/compress-with-charset",
  5637. [&](const Request & /*req*/, Response &res) {
  5638. res.set_content(
  5639. "12345678901234567890123456789012345678901234567890123456789"
  5640. "01234567890123456789012345678901234567890",
  5641. "application/json; charset=utf-8");
  5642. })
  5643. .Get("/nocompress",
  5644. [&](const Request & /*req*/, Response &res) {
  5645. res.set_content(
  5646. "12345678901234567890123456789012345678901234567890123456789"
  5647. "01234567890123456789012345678901234567890",
  5648. "application/octet-stream");
  5649. })
  5650. .Post("/compress-multipart",
  5651. [&](const Request &req, Response & /*res*/) {
  5652. EXPECT_EQ(2u, req.form.fields.size());
  5653. ASSERT_TRUE(!req.form.has_field("???"));
  5654. {
  5655. const auto &text = req.form.get_field("key1");
  5656. EXPECT_EQ("test", text);
  5657. }
  5658. {
  5659. const auto &text = req.form.get_field("key2");
  5660. EXPECT_EQ("--abcdefg123", text);
  5661. }
  5662. })
  5663. #endif
  5664. ;
  5665. persons_["john"] = "programmer";
  5666. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5667. svr_.wait_until_ready();
  5668. }
  5669. virtual void TearDown() {
  5670. svr_.stop();
  5671. if (!request_threads_.empty()) {
  5672. std::this_thread::sleep_for(std::chrono::seconds(1));
  5673. for (auto &t : request_threads_) {
  5674. t.join();
  5675. }
  5676. }
  5677. t_.join();
  5678. }
  5679. map<string, string> persons_;
  5680. #ifdef CPPHTTPLIB_SSL_ENABLED
  5681. SSLClient cli_;
  5682. SSLServer svr_;
  5683. #else
  5684. Client cli_;
  5685. Server svr_;
  5686. #endif
  5687. thread t_;
  5688. std::vector<thread> request_threads_;
  5689. };
  5690. TEST_F(ServerTest, GetMethod200) {
  5691. auto res = cli_.Get("/hi");
  5692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5693. EXPECT_EQ("HTTP/1.1", res->version);
  5694. EXPECT_EQ(StatusCode::OK_200, res->status);
  5695. EXPECT_EQ("OK", res->reason);
  5696. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5697. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5698. EXPECT_EQ("Hello World!", res->body);
  5699. }
  5700. TEST_F(ServerTest, GetEmptyFile) {
  5701. auto res = cli_.Get("/empty_file");
  5702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5703. EXPECT_EQ(StatusCode::OK_200, res->status);
  5704. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5705. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5706. EXPECT_EQ("", res->body);
  5707. }
  5708. TEST_F(ServerTest, GetFileContent) {
  5709. auto res = cli_.Get("/file_content");
  5710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5711. EXPECT_EQ(StatusCode::OK_200, res->status);
  5712. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5713. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5714. EXPECT_EQ("test.html", res->body);
  5715. }
  5716. TEST_F(ServerTest, GetFileContentWithRange) {
  5717. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5720. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5721. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5722. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5723. EXPECT_EQ("est", res->body);
  5724. }
  5725. TEST_F(ServerTest, GetFileContentWithContentType) {
  5726. auto res = cli_.Get("/file_content_with_content_type");
  5727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5728. EXPECT_EQ(StatusCode::OK_200, res->status);
  5729. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5730. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5731. EXPECT_EQ("file\n", res->body);
  5732. }
  5733. TEST_F(ServerTest, GetInvalidFileContent) {
  5734. auto res = cli_.Get("/invalid_file_content");
  5735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5736. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5737. }
  5738. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5739. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5741. EXPECT_EQ("HTTP/1.1", res->version);
  5742. EXPECT_EQ(StatusCode::OK_200, res->status);
  5743. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5744. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5745. EXPECT_EQ("Hello World!", res->body);
  5746. }
  5747. TEST_F(ServerTest, GetMethod302) {
  5748. auto res = cli_.Get("/");
  5749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5750. EXPECT_EQ(StatusCode::Found_302, res->status);
  5751. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5752. }
  5753. TEST_F(ServerTest, GetMethod302Redirect) {
  5754. cli_.set_follow_location(true);
  5755. auto res = cli_.Get("/");
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. EXPECT_EQ(StatusCode::OK_200, res->status);
  5758. EXPECT_EQ("Hello World!", res->body);
  5759. EXPECT_EQ("/hi", res->location);
  5760. }
  5761. TEST_F(ServerTest, GetMethod404) {
  5762. auto res = cli_.Get("/invalid");
  5763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5764. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5765. }
  5766. TEST_F(ServerTest, HeadMethod200) {
  5767. auto res = cli_.Head("/hi");
  5768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5769. EXPECT_EQ(StatusCode::OK_200, res->status);
  5770. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5771. EXPECT_TRUE(res->body.empty());
  5772. }
  5773. TEST_F(ServerTest, HeadMethod200Static) {
  5774. auto res = cli_.Head("/mount/dir/index.html");
  5775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5776. EXPECT_EQ(StatusCode::OK_200, res->status);
  5777. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5778. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5779. EXPECT_TRUE(res->body.empty());
  5780. }
  5781. TEST_F(ServerTest, HeadMethod404) {
  5782. auto res = cli_.Head("/invalid");
  5783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5784. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5785. EXPECT_TRUE(res->body.empty());
  5786. }
  5787. TEST_F(ServerTest, GetMethodPersonJohn) {
  5788. auto res = cli_.Get("/person/john");
  5789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5790. EXPECT_EQ(StatusCode::OK_200, res->status);
  5791. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5792. EXPECT_EQ("programmer", res->body);
  5793. }
  5794. TEST_F(ServerTest, PostMethod1) {
  5795. auto res = cli_.Get("/person/john1");
  5796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5797. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5798. res = cli_.Post("/person", "name=john1&note=coder",
  5799. "application/x-www-form-urlencoded");
  5800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5801. ASSERT_EQ(StatusCode::OK_200, res->status);
  5802. res = cli_.Get("/person/john1");
  5803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5804. ASSERT_EQ(StatusCode::OK_200, res->status);
  5805. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5806. ASSERT_EQ("coder", res->body);
  5807. }
  5808. TEST_F(ServerTest, PostMethod2) {
  5809. auto res = cli_.Get("/person/john2");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5812. Params params;
  5813. params.emplace("name", "john2");
  5814. params.emplace("note", "coder");
  5815. res = cli_.Post("/person", params);
  5816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5817. ASSERT_EQ(StatusCode::OK_200, res->status);
  5818. res = cli_.Get("/person/john2");
  5819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5820. ASSERT_EQ(StatusCode::OK_200, res->status);
  5821. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5822. ASSERT_EQ("coder", res->body);
  5823. }
  5824. TEST_F(ServerTest, PutMethod3) {
  5825. auto res = cli_.Get("/person/john3");
  5826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5827. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5828. Params params;
  5829. params.emplace("name", "john3");
  5830. params.emplace("note", "coder");
  5831. res = cli_.Put("/person", params);
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. ASSERT_EQ(StatusCode::OK_200, res->status);
  5834. res = cli_.Get("/person/john3");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. ASSERT_EQ(StatusCode::OK_200, res->status);
  5837. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5838. ASSERT_EQ("coder", res->body);
  5839. }
  5840. TEST_F(ServerTest, DeleteMethod1) {
  5841. auto res = cli_.Get("/person/john4");
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5844. Params params;
  5845. params.emplace("name", "john4");
  5846. params.emplace("note", "coder");
  5847. res = cli_.Post("/person", params);
  5848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5849. ASSERT_EQ(StatusCode::OK_200, res->status);
  5850. res = cli_.Get("/person/john4");
  5851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5852. ASSERT_EQ(StatusCode::OK_200, res->status);
  5853. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5854. ASSERT_EQ("coder", res->body);
  5855. Params delete_params;
  5856. delete_params.emplace("name", "john4");
  5857. res = cli_.Delete("/person", delete_params);
  5858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5859. ASSERT_EQ(StatusCode::OK_200, res->status);
  5860. ASSERT_EQ("DELETED", res->body);
  5861. res = cli_.Get("/person/john4");
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5864. }
  5865. TEST_F(ServerTest, DeleteMethod2) {
  5866. auto res = cli_.Get("/person/john5");
  5867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5868. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5869. Params params;
  5870. params.emplace("name", "john5");
  5871. params.emplace("note", "developer");
  5872. res = cli_.Post("/person", params);
  5873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5874. ASSERT_EQ(StatusCode::OK_200, res->status);
  5875. res = cli_.Get("/person/john5");
  5876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5877. ASSERT_EQ(StatusCode::OK_200, res->status);
  5878. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5879. ASSERT_EQ("developer", res->body);
  5880. Params delete_params;
  5881. delete_params.emplace("name", "john5");
  5882. Headers headers;
  5883. headers.emplace("Custom-Header", "test-value");
  5884. res = cli_.Delete("/person", headers, delete_params);
  5885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5886. ASSERT_EQ(StatusCode::OK_200, res->status);
  5887. ASSERT_EQ("DELETED", res->body);
  5888. res = cli_.Get("/person/john5");
  5889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5890. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5891. }
  5892. TEST_F(ServerTest, DeleteMethod3) {
  5893. auto res = cli_.Get("/person/john6");
  5894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5895. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5896. Params params;
  5897. params.emplace("name", "john6");
  5898. params.emplace("note", "tester");
  5899. res = cli_.Post("/person", params);
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. ASSERT_EQ(StatusCode::OK_200, res->status);
  5902. res = cli_.Get("/person/john6");
  5903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5904. ASSERT_EQ(StatusCode::OK_200, res->status);
  5905. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5906. ASSERT_EQ("tester", res->body);
  5907. Params delete_params;
  5908. delete_params.emplace("name", "john6");
  5909. Headers headers;
  5910. headers.emplace("Custom-Header", "test-value");
  5911. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5913. ASSERT_EQ(StatusCode::OK_200, res->status);
  5914. ASSERT_EQ("DELETED", res->body);
  5915. res = cli_.Get("/person/john6");
  5916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5917. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5918. }
  5919. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5920. Params params;
  5921. params.emplace("json", JSON_DATA);
  5922. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5924. ASSERT_EQ(StatusCode::OK_200, res->status);
  5925. ASSERT_EQ(JSON_DATA, res->body);
  5926. }
  5927. TEST_F(ServerTest, PostEmptyContent) {
  5928. auto res = cli_.Post("/empty", "", "text/plain");
  5929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5930. ASSERT_EQ(StatusCode::OK_200, res->status);
  5931. ASSERT_EQ("empty", res->body);
  5932. }
  5933. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5934. auto res = cli_.Post("/empty-no-content-type");
  5935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5936. ASSERT_EQ(StatusCode::OK_200, res->status);
  5937. ASSERT_EQ("empty-no-content-type", res->body);
  5938. }
  5939. TEST_F(ServerTest, PostPathOnly) {
  5940. auto res = cli_.Post("/path-only");
  5941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5942. ASSERT_EQ(StatusCode::OK_200, res->status);
  5943. ASSERT_EQ("path-only", res->body);
  5944. }
  5945. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5946. auto res = cli_.Post("/path-headers-only",
  5947. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5949. ASSERT_EQ(StatusCode::OK_200, res->status);
  5950. ASSERT_EQ("path-headers-only", res->body);
  5951. }
  5952. TEST_F(ServerTest, PostLarge) {
  5953. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5955. ASSERT_EQ(StatusCode::OK_200, res->status);
  5956. EXPECT_EQ(LARGE_DATA, res->body);
  5957. }
  5958. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5959. auto res = cli_.Put("/empty-no-content-type");
  5960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5961. ASSERT_EQ(StatusCode::OK_200, res->status);
  5962. ASSERT_EQ("empty-no-content-type", res->body);
  5963. }
  5964. TEST_F(ServerTest, GetMethodDir) {
  5965. auto res = cli_.Get("/dir/");
  5966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5967. EXPECT_EQ(StatusCode::OK_200, res->status);
  5968. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5969. auto body = R"(<html>
  5970. <head>
  5971. </head>
  5972. <body>
  5973. <a href="/dir/test.html">Test</a>
  5974. <a href="/hi">hi</a>
  5975. </body>
  5976. </html>
  5977. )";
  5978. EXPECT_EQ(body, res->body);
  5979. }
  5980. TEST_F(ServerTest, GetMethodDirTest) {
  5981. auto res = cli_.Get("/dir/test.html");
  5982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5983. EXPECT_EQ(StatusCode::OK_200, res->status);
  5984. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5985. EXPECT_EQ("test.html", res->body);
  5986. }
  5987. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5988. auto res = cli_.Get("/dir/../dir/test.html");
  5989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5990. EXPECT_EQ(StatusCode::OK_200, res->status);
  5991. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5992. EXPECT_EQ("test.html", res->body);
  5993. }
  5994. TEST_F(ServerTest, GetMethodInvalidPath) {
  5995. auto res = cli_.Get("/dir/../test.html");
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5998. }
  5999. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6000. auto res = cli_.Get("/../www/dir/test.html");
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6003. }
  6004. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6005. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6007. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6008. }
  6009. TEST_F(ServerTest, GetMethodDirMountTest) {
  6010. auto res = cli_.Get("/mount/dir/test.html");
  6011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6012. EXPECT_EQ(StatusCode::OK_200, res->status);
  6013. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6014. EXPECT_EQ("test.html", res->body);
  6015. }
  6016. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6017. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6021. EXPECT_EQ("test.html", res->body);
  6022. }
  6023. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6024. auto res = cli_.Get("/mount/dir/../test.html");
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6027. }
  6028. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6029. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6031. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6032. }
  6033. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6034. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6037. }
  6038. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6039. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6041. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6042. }
  6043. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6044. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6047. }
  6048. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6049. auto res = cli_.Get("/mount/dir");
  6050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6051. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6052. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6053. }
  6054. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6055. auto res = cli_.Get("//dir");
  6056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6057. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6058. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6059. }
  6060. TEST_F(ServerTest, PostMethod303) {
  6061. auto res = cli_.Post("/1", "body", "text/plain");
  6062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6063. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6064. EXPECT_EQ("/2", res->get_header_value("Location"));
  6065. }
  6066. TEST_F(ServerTest, PostMethod303Redirect) {
  6067. cli_.set_follow_location(true);
  6068. auto res = cli_.Post("/1", "body", "text/plain");
  6069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6070. EXPECT_EQ(StatusCode::OK_200, res->status);
  6071. EXPECT_EQ("redirected.", res->body);
  6072. EXPECT_EQ("/2", res->location);
  6073. }
  6074. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6075. auto res = cli_.Get("/dir/test.abcde");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::OK_200, res->status);
  6078. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6079. EXPECT_EQ("abcde", res->body);
  6080. }
  6081. TEST_F(ServerTest, StaticFileRange) {
  6082. auto res =
  6083. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6085. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6086. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6087. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6088. EXPECT_EQ(true, res->has_header("Content-Range"));
  6089. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6090. EXPECT_EQ(std::string("cd"), res->body);
  6091. }
  6092. TEST_F(ServerTest, StaticFileRanges) {
  6093. auto res = cli_.Get("/dir/test.abcde",
  6094. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6096. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6097. EXPECT_TRUE(
  6098. res->get_header_value("Content-Type")
  6099. .find(
  6100. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6101. 0);
  6102. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6103. }
  6104. TEST_F(ServerTest, StaticFileRangeHead) {
  6105. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6107. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6108. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6109. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6110. EXPECT_EQ(true, res->has_header("Content-Range"));
  6111. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6112. }
  6113. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6114. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6116. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6118. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6119. EXPECT_EQ(true, res->has_header("Content-Range"));
  6120. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6121. res->get_header_value("Content-Range"));
  6122. EXPECT_EQ("LAST\n", res->body);
  6123. }
  6124. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6125. auto res =
  6126. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6128. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6129. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6130. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6131. EXPECT_EQ(true, res->has_header("Content-Range"));
  6132. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6133. }
  6134. TEST_F(ServerTest, StaticFileBigFile) {
  6135. auto res = cli_.Get("/dir/1MB.txt");
  6136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6137. EXPECT_EQ(StatusCode::OK_200, res->status);
  6138. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6139. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6140. }
  6141. TEST_F(ServerTest, InvalidBaseDirMount) {
  6142. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6143. }
  6144. TEST_F(ServerTest, Binary) {
  6145. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6146. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6147. "application/octet-stream");
  6148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6149. ASSERT_EQ(StatusCode::OK_200, res->status);
  6150. ASSERT_EQ(4U, res->body.size());
  6151. res = cli_.Put("/binary", binary.data(), binary.size(),
  6152. "application/octet-stream");
  6153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6154. ASSERT_EQ(StatusCode::OK_200, res->status);
  6155. ASSERT_EQ(4U, res->body.size());
  6156. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6157. "application/octet-stream");
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. ASSERT_EQ(StatusCode::OK_200, res->status);
  6160. ASSERT_EQ(4U, res->body.size());
  6161. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6162. "application/octet-stream");
  6163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6164. ASSERT_EQ(StatusCode::OK_200, res->status);
  6165. ASSERT_EQ(4U, res->body.size());
  6166. }
  6167. TEST_F(ServerTest, BinaryString) {
  6168. auto binary = std::string("\x00\x01\x02\x03", 4);
  6169. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6171. ASSERT_EQ(StatusCode::OK_200, res->status);
  6172. ASSERT_EQ(4U, res->body.size());
  6173. res = cli_.Put("/binary", binary, "application/octet-stream");
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. ASSERT_EQ(StatusCode::OK_200, res->status);
  6176. ASSERT_EQ(4U, res->body.size());
  6177. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6179. ASSERT_EQ(StatusCode::OK_200, res->status);
  6180. ASSERT_EQ(4U, res->body.size());
  6181. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6183. ASSERT_EQ(StatusCode::OK_200, res->status);
  6184. ASSERT_EQ(4U, res->body.size());
  6185. }
  6186. TEST_F(ServerTest, EmptyRequest) {
  6187. auto res = cli_.Get("");
  6188. ASSERT_TRUE(!res);
  6189. EXPECT_EQ(Error::Connection, res.error());
  6190. }
  6191. TEST_F(ServerTest, LongRequest) {
  6192. std::string request;
  6193. for (size_t i = 0; i < 545; i++) {
  6194. request += "/TooLongRequest";
  6195. }
  6196. request += "OK";
  6197. auto res = cli_.Get(request.c_str());
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6200. }
  6201. TEST_F(ServerTest, TooLongRequest) {
  6202. std::string request;
  6203. for (size_t i = 0; i < 546; i++) {
  6204. request += "/TooLongRequest";
  6205. }
  6206. request += "_NG";
  6207. auto start = std::chrono::high_resolution_clock::now();
  6208. cli_.set_keep_alive(true);
  6209. auto res = cli_.Get(request.c_str());
  6210. auto end = std::chrono::high_resolution_clock::now();
  6211. auto elapsed =
  6212. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6213. .count();
  6214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6215. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6216. EXPECT_LE(elapsed, 1000);
  6217. EXPECT_EQ("close", res->get_header_value("Connection"));
  6218. EXPECT_FALSE(cli_.is_socket_open());
  6219. }
  6220. TEST_F(ServerTest, AlmostTooLongRequest) {
  6221. // test for #2046 - URI length check shouldn't include other content on req
  6222. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6223. // leading /, space, HTTP/1.1)
  6224. std::string request =
  6225. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6226. auto res = cli_.Get(request.c_str());
  6227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6228. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6229. }
  6230. TEST_F(ServerTest, LongHeader) {
  6231. Request req;
  6232. req.method = "GET";
  6233. req.path = "/hi";
  6234. std::string host_and_port;
  6235. host_and_port += HOST;
  6236. host_and_port += ":";
  6237. host_and_port += std::to_string(PORT);
  6238. req.headers.emplace("Host", host_and_port.c_str());
  6239. req.headers.emplace("Accept", "*/*");
  6240. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6241. req.headers.emplace(
  6242. "Header-Name",
  6243. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6244. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6245. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6246. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6247. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6248. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6249. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6250. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6251. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6252. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6253. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6254. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6255. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6256. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6257. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6271. "@@@@@@@@@@@@@@@@");
  6272. auto res = std::make_shared<Response>();
  6273. auto error = Error::Success;
  6274. auto ret = cli_.send(req, *res, error);
  6275. ASSERT_TRUE(ret);
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. }
  6278. TEST_F(ServerTest, LongQueryValue) {
  6279. auto start = std::chrono::high_resolution_clock::now();
  6280. cli_.set_keep_alive(true);
  6281. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6282. auto end = std::chrono::high_resolution_clock::now();
  6283. auto elapsed =
  6284. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6285. .count();
  6286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6287. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6288. EXPECT_LE(elapsed, 1000);
  6289. EXPECT_EQ("close", res->get_header_value("Connection"));
  6290. EXPECT_FALSE(cli_.is_socket_open());
  6291. }
  6292. TEST_F(ServerTest, TooLongQueryValue) {
  6293. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6294. ASSERT_FALSE(res);
  6295. EXPECT_EQ(Error::Read, res.error());
  6296. }
  6297. TEST_F(ServerTest, TooLongHeader) {
  6298. Request req;
  6299. req.method = "GET";
  6300. req.path = "/hi";
  6301. std::string host_and_port;
  6302. host_and_port += HOST;
  6303. host_and_port += ":";
  6304. host_and_port += std::to_string(PORT);
  6305. req.headers.emplace("Host", host_and_port.c_str());
  6306. req.headers.emplace("Accept", "*/*");
  6307. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6308. req.headers.emplace(
  6309. "Header-Name",
  6310. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6311. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6312. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6313. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6314. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6315. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6316. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6317. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6318. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6319. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6320. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6321. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6322. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6323. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6324. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6325. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6326. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6327. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6328. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6329. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6330. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6331. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6332. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6333. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6334. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6335. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6336. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6337. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6338. "@@@@@@@@@@@@@@@@@");
  6339. auto res = std::make_shared<Response>();
  6340. auto error = Error::Success;
  6341. auto ret = cli_.send(req, *res, error);
  6342. ASSERT_TRUE(ret);
  6343. EXPECT_EQ(StatusCode::OK_200, res->status);
  6344. }
  6345. TEST_F(ServerTest, HeaderCountAtLimit) {
  6346. // Test with headers just under the 100 limit
  6347. httplib::Headers headers;
  6348. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6349. // This should keep us just under the 100 header limit
  6350. for (int i = 0; i < 95; i++) {
  6351. std::string name = "X-Test-Header-" + std::to_string(i);
  6352. std::string value = "value" + std::to_string(i);
  6353. headers.emplace(name, value);
  6354. }
  6355. // This should work fine as we're under the limit
  6356. auto res = cli_.Get("/hi", headers);
  6357. EXPECT_TRUE(res);
  6358. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6359. }
  6360. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6361. // Test with many headers to exceed the 100 limit
  6362. httplib::Headers headers;
  6363. // Add 150 headers to definitely exceed the 100 limit
  6364. for (int i = 0; i < 150; i++) {
  6365. std::string name = "X-Test-Header-" + std::to_string(i);
  6366. std::string value = "value" + std::to_string(i);
  6367. headers.emplace(name, value);
  6368. }
  6369. // This should fail due to exceeding header count limit
  6370. cli_.set_keep_alive(true);
  6371. auto res = cli_.Get("/hi", headers);
  6372. // The server should respond with 400 Bad Request
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6375. EXPECT_EQ("close", res->get_header_value("Connection"));
  6376. EXPECT_FALSE(cli_.is_socket_open());
  6377. }
  6378. TEST_F(ServerTest, PercentEncoding) {
  6379. auto res = cli_.Get("/e%6edwith%");
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. EXPECT_EQ(StatusCode::OK_200, res->status);
  6382. }
  6383. TEST_F(ServerTest, PercentEncodingUnicode) {
  6384. auto res = cli_.Get("/e%u006edwith%");
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. EXPECT_EQ(StatusCode::OK_200, res->status);
  6387. }
  6388. TEST_F(ServerTest, InvalidPercentEncoding) {
  6389. auto res = cli_.Get("/%endwith%");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6392. }
  6393. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6394. auto res = cli_.Get("/%uendwith%");
  6395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6396. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6397. }
  6398. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6399. auto res = cli_.Get("/hello?aaa=bbb%");
  6400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6401. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6402. }
  6403. TEST_F(ServerTest, PlusSignEncoding) {
  6404. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6406. EXPECT_EQ(StatusCode::OK_200, res->status);
  6407. EXPECT_EQ("a +b", res->body);
  6408. }
  6409. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6410. // This test simulates a potential DoS attack using many headers
  6411. // to verify our security fix prevents memory exhaustion
  6412. httplib::Headers attack_headers;
  6413. // Attempt to add many headers like an attacker would (200 headers to far
  6414. // exceed limit)
  6415. for (int i = 0; i < 200; i++) {
  6416. std::string name = "X-Attack-Header-" + std::to_string(i);
  6417. std::string value = "attack_payload_" + std::to_string(i);
  6418. attack_headers.emplace(name, value);
  6419. }
  6420. // Try to POST with excessive headers
  6421. cli_.set_keep_alive(true);
  6422. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6423. // Should either fail or return 400 Bad Request due to security limit
  6424. if (res) {
  6425. // If we get a response, it should be 400 Bad Request
  6426. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6427. EXPECT_EQ("close", res->get_header_value("Connection"));
  6428. }
  6429. EXPECT_FALSE(cli_.is_socket_open());
  6430. }
  6431. TEST_F(ServerTest, MultipartFormData) {
  6432. UploadFormDataItems items = {
  6433. {"text1", "text default", "", ""},
  6434. {"text2", "aωb", "", ""},
  6435. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6436. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6437. {"file3", "", "", "application/octet-stream"},
  6438. {"file4", "", "", " application/json tmp-string "}};
  6439. auto res = cli_.Post("/multipart", items);
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. }
  6443. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6444. UploadFormDataItems items = {
  6445. {"text", "default text", "", ""},
  6446. {"multi_text1", "aaaaa", "", ""},
  6447. {"multi_text1", "bbbbb", "", ""},
  6448. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6449. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6450. "application/json"},
  6451. };
  6452. auto res = cli_.Post("/multipart/multi_file_values", items);
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. }
  6456. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6457. auto res = cli_.Get("/hi");
  6458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6459. EXPECT_EQ(StatusCode::OK_200, res->status);
  6460. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6461. EXPECT_EQ("Hello World!", res->body);
  6462. }
  6463. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6464. Request req;
  6465. req.method = "POST";
  6466. req.path = "/chunked";
  6467. std::string host_and_port;
  6468. host_and_port += HOST;
  6469. host_and_port += ":";
  6470. host_and_port += std::to_string(PORT);
  6471. req.headers.emplace("Host", host_and_port.c_str());
  6472. req.headers.emplace("Accept", "*/*");
  6473. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6474. req.headers.emplace("Content-Type", "text/plain");
  6475. req.headers.emplace("Content-Length", "0");
  6476. req.headers.emplace(
  6477. "Transfer-Encoding",
  6478. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6479. // Client does not chunk, so make a chunked body manually.
  6480. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6481. auto res = std::make_shared<Response>();
  6482. auto error = Error::Success;
  6483. auto ret = cli_.send(req, *res, error);
  6484. ASSERT_TRUE(ret);
  6485. EXPECT_EQ(StatusCode::OK_200, res->status);
  6486. }
  6487. template <typename ClientT>
  6488. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6489. int expected_status) {
  6490. Request req;
  6491. req.method = "POST";
  6492. req.path = "/chunked";
  6493. std::string host_and_port;
  6494. host_and_port += HOST;
  6495. host_and_port += ":";
  6496. host_and_port += std::to_string(PORT);
  6497. req.headers.emplace("Host", host_and_port.c_str());
  6498. req.headers.emplace("Content-Length", "0");
  6499. req.headers.emplace("Transfer-Encoding", "chunked");
  6500. req.body = body;
  6501. auto res = std::make_shared<Response>();
  6502. auto error = Error::Success;
  6503. ASSERT_TRUE(cli.send(req, *res, error));
  6504. EXPECT_EQ(expected_status, res->status);
  6505. }
  6506. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6507. // rather than treat them as valid lengths.
  6508. template <typename ClientT>
  6509. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6510. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6511. }
  6512. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6513. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6514. }
  6515. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6516. expect_chunked_body_rejected(
  6517. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6518. }
  6519. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6520. // chunk-size line carries no CR, LF or other control character ahead of its
  6521. // terminator. Such a line must be refused rather than read as extension text.
  6522. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6523. expect_chunked_body_rejected(
  6524. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6525. }
  6526. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6527. expect_chunked_body_rejected(
  6528. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6529. }
  6530. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6531. expect_chunked_body_rejected(
  6532. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6533. }
  6534. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6535. // The literal stays split: a hex escape consumes every hex digit that
  6536. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6537. expect_chunked_body_rejected(
  6538. cli_, "4;a\x01"
  6539. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6540. }
  6541. TEST_F(ServerTest, AcceptsChunkExtension) {
  6542. expect_chunked_body_status(cli_,
  6543. "4;name=value\r\ndech\r\n"
  6544. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6545. "0;last\r\n\r\n",
  6546. StatusCode::OK_200);
  6547. }
  6548. TEST_F(ServerTest, GetStreamed2) {
  6549. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6552. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6553. EXPECT_EQ(true, res->has_header("Content-Range"));
  6554. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6555. EXPECT_EQ(std::string("ab"), res->body);
  6556. }
  6557. TEST_F(ServerTest, GetStreamed) {
  6558. auto res = cli_.Get("/streamed");
  6559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6560. EXPECT_EQ(StatusCode::OK_200, res->status);
  6561. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6562. EXPECT_EQ(std::string("aaabbb"), res->body);
  6563. }
  6564. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6565. auto res = cli_.Get("/streamed-without-length",
  6566. Headers{make_range_header({{0, -1}})});
  6567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6568. EXPECT_EQ(StatusCode::OK_200, res->status);
  6569. EXPECT_EQ(false, res->has_header("Content-Length"));
  6570. EXPECT_EQ(false, res->has_header("Content-Range"));
  6571. EXPECT_EQ(std::string("abcdefg"), res->body);
  6572. }
  6573. TEST_F(ServerTest, GetStreamedWithRange1) {
  6574. auto res =
  6575. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6577. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6578. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6579. EXPECT_EQ(true, res->has_header("Content-Range"));
  6580. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6581. EXPECT_EQ(std::string("def"), res->body);
  6582. }
  6583. TEST_F(ServerTest, GetStreamedWithRange2) {
  6584. auto res =
  6585. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6587. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6588. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6589. EXPECT_EQ(true, res->has_header("Content-Range"));
  6590. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6591. EXPECT_EQ(std::string("bcdefg"), res->body);
  6592. }
  6593. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6594. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6596. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6597. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6598. EXPECT_EQ(true, res->has_header("Content-Range"));
  6599. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6600. EXPECT_EQ(std::string("efg"), res->body);
  6601. }
  6602. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6603. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6604. // the entire representation.
  6605. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6606. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6608. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6609. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6610. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6611. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6612. }
  6613. }
  6614. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6615. auto res =
  6616. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6619. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6620. EXPECT_EQ(false, res->has_header("Content-Range"));
  6621. EXPECT_EQ(0U, res->body.size());
  6622. }
  6623. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6624. // Only a 206 is served as a partial representation. Under any other status
  6625. // `apply_ranges()` reported the full content length, so the body must match
  6626. // that header, and the content provider must never be asked for an offset
  6627. // outside the representation.
  6628. auto check = [&](int status, const char *range) {
  6629. auto path =
  6630. std::string("/streamed-with-range?status=") + std::to_string(status);
  6631. auto ctx = path + " Range: " + range;
  6632. auto res = cli_.Get(path, Headers{{"Range", range}});
  6633. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6634. EXPECT_EQ(status, res->status) << ctx;
  6635. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6636. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6637. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6638. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6639. };
  6640. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6641. check(403, "bytes=3-5");
  6642. // The offset is far past the representation.
  6643. check(403, "bytes=100000-100200");
  6644. // `first_pos` is still -1 here, and the bounds asserts in
  6645. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6646. check(403, "bytes=-3");
  6647. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6648. // multipart branch would have written one that is empty.
  6649. check(403, "bytes=1-2, 4-5");
  6650. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6651. // covers the whole representation.
  6652. check(200, "bytes=3-5");
  6653. check(200, "bytes=1-2, 4-5");
  6654. }
  6655. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6656. auto res =
  6657. cli_.Get("/streamed-with-range",
  6658. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6659. "92233720368547758079223372036854775807"}});
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6662. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6663. EXPECT_EQ(false, res->has_header("Content-Range"));
  6664. EXPECT_EQ(0U, res->body.size());
  6665. }
  6666. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6667. auto res = cli_.Get(
  6668. "/with-range",
  6669. Headers{{"Range",
  6670. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6671. {"Accept-Encoding", ""}});
  6672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6673. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6674. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6675. EXPECT_EQ(true, res->has_header("Content-Range"));
  6676. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6677. EXPECT_EQ(std::string("abcdefg"), res->body);
  6678. }
  6679. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6680. auto res = cli_.Get("/with-range", Headers{
  6681. {"Range", "bytes=0-"},
  6682. {"Accept-Encoding", ""},
  6683. });
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6686. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6687. EXPECT_EQ(true, res->has_header("Content-Range"));
  6688. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6689. EXPECT_EQ(std::string("abcdefg"), res->body);
  6690. }
  6691. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6692. auto res = cli_.Get("/streamed-with-range",
  6693. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6696. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6697. EXPECT_EQ(false, res->has_header("Content-Range"));
  6698. EXPECT_EQ(267U, res->body.size());
  6699. // Check that both range contents are present
  6700. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6701. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6702. // Check that Content-Range headers are present for both ranges
  6703. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6704. std::string::npos);
  6705. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6706. std::string::npos);
  6707. }
  6708. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6709. Ranges ranges;
  6710. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6711. ranges.emplace_back(0, -1);
  6712. }
  6713. auto res = cli_.Get("/streamed-with-range?error",
  6714. Headers{{make_range_header(ranges)}});
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6717. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6718. EXPECT_EQ(false, res->has_header("Content-Range"));
  6719. EXPECT_EQ(0U, res->body.size());
  6720. }
  6721. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6722. auto res = cli_.Get("/streamed-with-range",
  6723. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6725. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6726. EXPECT_EQ(5U, res->body.size());
  6727. // Check that overlapping ranges are coalesced into a single range
  6728. EXPECT_EQ("bcdef", res->body);
  6729. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6730. // Should be single range, not multipart
  6731. EXPECT_TRUE(res->has_header("Content-Range"));
  6732. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6733. }
  6734. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6735. auto res = cli_.Get("/streamed-with-range",
  6736. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6738. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6739. EXPECT_EQ(268U, res->body.size());
  6740. // Check that both range contents are present
  6741. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6742. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6743. // Check that Content-Range headers are present for both ranges
  6744. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6745. std::string::npos);
  6746. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6747. std::string::npos);
  6748. }
  6749. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6750. auto res = cli_.Get("/streamed-with-range",
  6751. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6753. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6754. EXPECT_EQ(269U, res->body.size());
  6755. // Check that both duplicate range contents are present
  6756. size_t first_abc = res->body.find("abc\r\n");
  6757. EXPECT_TRUE(first_abc != std::string::npos);
  6758. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6759. EXPECT_TRUE(second_abc != std::string::npos);
  6760. // Check that Content-Range headers are present for both ranges
  6761. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6762. EXPECT_TRUE(first_range != std::string::npos);
  6763. size_t second_range =
  6764. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6765. EXPECT_TRUE(second_range != std::string::npos);
  6766. }
  6767. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6768. auto res =
  6769. cli_.Get("/streamed-with-range?error",
  6770. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6773. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6774. EXPECT_EQ(false, res->has_header("Content-Range"));
  6775. EXPECT_EQ(0U, res->body.size());
  6776. }
  6777. TEST_F(ServerTest, GetStreamedEndless) {
  6778. uint64_t offset = 0;
  6779. auto res = cli_.Get("/streamed-cancel",
  6780. [&](const char * /*data*/, uint64_t data_length) {
  6781. if (offset < 100) {
  6782. offset += data_length;
  6783. return true;
  6784. }
  6785. return false;
  6786. });
  6787. ASSERT_TRUE(!res);
  6788. EXPECT_EQ(Error::Canceled, res.error());
  6789. }
  6790. TEST_F(ServerTest, ClientStop) {
  6791. std::atomic_size_t count{4};
  6792. std::vector<std::thread> threads;
  6793. for (auto i = count.load(); i != 0; --i) {
  6794. threads.emplace_back([&]() {
  6795. auto res = cli_.Get("/streamed-cancel",
  6796. [&](const char *, uint64_t) { return true; });
  6797. --count;
  6798. ASSERT_TRUE(!res);
  6799. EXPECT_TRUE(res.error() == Error::Canceled ||
  6800. res.error() == Error::Read || res.error() == Error::Write);
  6801. });
  6802. }
  6803. std::this_thread::sleep_for(std::chrono::seconds(2));
  6804. while (count != 0) {
  6805. cli_.stop();
  6806. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6807. }
  6808. for (auto &t : threads) {
  6809. t.join();
  6810. }
  6811. }
  6812. TEST_F(ServerTest, GetWithRange1) {
  6813. auto res = cli_.Get("/with-range", Headers{
  6814. make_range_header({{3, 5}}),
  6815. {"Accept-Encoding", ""},
  6816. });
  6817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6818. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6819. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6820. EXPECT_EQ(true, res->has_header("Content-Range"));
  6821. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6822. EXPECT_EQ(std::string("def"), res->body);
  6823. }
  6824. TEST_F(ServerTest, GetWithRange2) {
  6825. auto res = cli_.Get("/with-range", Headers{
  6826. make_range_header({{1, -1}}),
  6827. {"Accept-Encoding", ""},
  6828. });
  6829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6830. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6831. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6832. EXPECT_EQ(true, res->has_header("Content-Range"));
  6833. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6834. EXPECT_EQ(std::string("bcdefg"), res->body);
  6835. }
  6836. TEST_F(ServerTest, GetWithRange3) {
  6837. auto res = cli_.Get("/with-range", Headers{
  6838. make_range_header({{0, 0}}),
  6839. {"Accept-Encoding", ""},
  6840. });
  6841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6842. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6843. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6844. EXPECT_EQ(true, res->has_header("Content-Range"));
  6845. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6846. EXPECT_EQ(std::string("a"), res->body);
  6847. }
  6848. TEST_F(ServerTest, GetWithRange4) {
  6849. auto res = cli_.Get("/with-range", Headers{
  6850. make_range_header({{-1, 2}}),
  6851. {"Accept-Encoding", ""},
  6852. });
  6853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6854. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6855. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6856. EXPECT_EQ(true, res->has_header("Content-Range"));
  6857. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6858. EXPECT_EQ(std::string("fg"), res->body);
  6859. }
  6860. TEST_F(ServerTest, GetWithRange5) {
  6861. auto res = cli_.Get("/with-range", Headers{
  6862. make_range_header({{0, 5}}),
  6863. {"Accept-Encoding", ""},
  6864. });
  6865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6866. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6867. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6868. EXPECT_EQ(true, res->has_header("Content-Range"));
  6869. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6870. EXPECT_EQ(std::string("abcdef"), res->body);
  6871. }
  6872. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6873. auto res =
  6874. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6876. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6877. }
  6878. TEST_F(ServerTest, GetWithRangeMultipart) {
  6879. auto res =
  6880. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6883. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6884. EXPECT_EQ(false, res->has_header("Content-Range"));
  6885. EXPECT_EQ(267U, res->body.size());
  6886. }
  6887. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6888. auto res = cli_.Get("/with-range",
  6889. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6891. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6892. }
  6893. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6894. auto res = cli_.Get("/with-range-customized-response",
  6895. Headers{{make_range_header({{1, 2}})}});
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6898. EXPECT_EQ(true, res->has_header("Content-Length"));
  6899. EXPECT_EQ(false, res->has_header("Content-Range"));
  6900. EXPECT_EQ(JSON_DATA, res->body);
  6901. }
  6902. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6903. auto res = cli_.Get("/with-range-customized-response",
  6904. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6907. EXPECT_EQ(true, res->has_header("Content-Length"));
  6908. EXPECT_EQ(false, res->has_header("Content-Range"));
  6909. EXPECT_EQ(JSON_DATA, res->body);
  6910. }
  6911. TEST_F(ServerTest, Issue1772) {
  6912. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6914. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6915. }
  6916. TEST_F(ServerTest, Issue609) {
  6917. auto res = cli_.Delete("/issue609");
  6918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6919. EXPECT_EQ(StatusCode::OK_200, res->status);
  6920. EXPECT_EQ(std::string("ok"), res->body);
  6921. }
  6922. TEST_F(ServerTest, GetStreamedChunked) {
  6923. auto res = cli_.Get("/streamed-chunked");
  6924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6925. EXPECT_EQ(StatusCode::OK_200, res->status);
  6926. EXPECT_EQ(std::string("123456789"), res->body);
  6927. }
  6928. TEST_F(ServerTest, GetStreamedChunked2) {
  6929. auto res = cli_.Get("/streamed-chunked2");
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::OK_200, res->status);
  6932. EXPECT_EQ(std::string("123456789"), res->body);
  6933. }
  6934. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6935. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6937. EXPECT_EQ(StatusCode::OK_200, res->status);
  6938. EXPECT_EQ(std::string("123456789"), res->body);
  6939. EXPECT_TRUE(res->has_header("Trailer"));
  6940. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6941. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6942. // Trailers are now stored separately from headers (security fix)
  6943. EXPECT_EQ(2U, res->trailers.size());
  6944. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6945. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6946. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6947. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6948. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6949. // Verify trailers are NOT in headers (security verification)
  6950. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6951. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6952. }
  6953. TEST_F(ServerTest, LargeChunkedPost) {
  6954. Request req;
  6955. req.method = "POST";
  6956. req.path = "/large-chunked";
  6957. std::string host_and_port;
  6958. host_and_port += HOST;
  6959. host_and_port += ":";
  6960. host_and_port += std::to_string(PORT);
  6961. req.headers.emplace("Host", host_and_port.c_str());
  6962. req.headers.emplace("Accept", "*/*");
  6963. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6964. req.headers.emplace("Content-Type", "text/plain");
  6965. req.headers.emplace("Content-Length", "0");
  6966. req.headers.emplace("Transfer-Encoding", "chunked");
  6967. std::string long_string(30 * 1024u, 'a');
  6968. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6969. // Attempt to make a large enough post to exceed OS buffers, to test that
  6970. // the server handles short reads if the full chunk data isn't available.
  6971. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6972. auto res = std::make_shared<Response>();
  6973. auto error = Error::Success;
  6974. auto ret = cli_.send(req, *res, error);
  6975. ASSERT_TRUE(ret);
  6976. EXPECT_EQ(StatusCode::OK_200, res->status);
  6977. }
  6978. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6979. auto res = cli_.Get("/remote_addr");
  6980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6981. EXPECT_EQ(StatusCode::OK_200, res->status);
  6982. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6983. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6984. }
  6985. TEST_F(ServerTest, GetMethodLocalAddr) {
  6986. auto res = cli_.Get("/local_addr");
  6987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6988. EXPECT_EQ(StatusCode::OK_200, res->status);
  6989. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6990. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6991. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6992. }
  6993. TEST_F(ServerTest, HTTPResponseSplitting) {
  6994. auto res = cli_.Get("/http_response_splitting");
  6995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6996. EXPECT_EQ(StatusCode::OK_200, res->status);
  6997. }
  6998. TEST_F(ServerTest, SlowRequest) {
  6999. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7000. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7001. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7002. }
  7003. #if 0
  7004. TEST_F(ServerTest, SlowPost) {
  7005. char buffer[64 * 1024];
  7006. memset(buffer, 0x42, sizeof(buffer));
  7007. auto res = cli_.Post(
  7008. "/slowpost", 64 * 1024 * 1024,
  7009. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7010. auto ret = sink.write(buffer, sizeof(buffer));
  7011. EXPECT_TRUE(ret);
  7012. return true;
  7013. },
  7014. "text/plain");
  7015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7016. EXPECT_EQ(StatusCode::OK_200, res->status);
  7017. }
  7018. TEST_F(ServerTest, SlowPostFail) {
  7019. char buffer[64 * 1024];
  7020. memset(buffer, 0x42, sizeof(buffer));
  7021. cli_.set_write_timeout(std::chrono::seconds(0));
  7022. auto res = cli_.Post(
  7023. "/slowpost", 64 * 1024 * 1024,
  7024. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7025. sink.write(buffer, sizeof(buffer));
  7026. return true;
  7027. },
  7028. "text/plain");
  7029. ASSERT_TRUE(!res);
  7030. EXPECT_EQ(Error::Write, res.error());
  7031. }
  7032. #endif
  7033. TEST_F(ServerTest, Put) {
  7034. auto res = cli_.Put("/put", "PUT", "text/plain");
  7035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7036. EXPECT_EQ(StatusCode::OK_200, res->status);
  7037. EXPECT_EQ("PUT", res->body);
  7038. }
  7039. TEST_F(ServerTest, PutWithContentProvider) {
  7040. auto res = cli_.Put(
  7041. "/put", 3,
  7042. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7043. sink.os << "PUT";
  7044. return true;
  7045. },
  7046. "text/plain");
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. EXPECT_EQ("PUT", res->body);
  7050. }
  7051. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7052. auto res = cli_.Post(
  7053. "/post", 42,
  7054. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7055. return false;
  7056. },
  7057. "text/plain");
  7058. ASSERT_TRUE(!res);
  7059. EXPECT_EQ(Error::Canceled, res.error());
  7060. }
  7061. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7062. auto res = cli_.Put(
  7063. "/put",
  7064. [](size_t /*offset*/, DataSink &sink) {
  7065. sink.os << "PUT";
  7066. sink.done();
  7067. return true;
  7068. },
  7069. "text/plain");
  7070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7071. EXPECT_EQ(StatusCode::OK_200, res->status);
  7072. EXPECT_EQ("PUT", res->body);
  7073. }
  7074. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7075. auto res = cli_.Post(
  7076. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7077. "text/plain");
  7078. ASSERT_TRUE(!res);
  7079. EXPECT_EQ(Error::Canceled, res.error());
  7080. }
  7081. TEST_F(ServerTest, PostLoopBack) {
  7082. std::string body;
  7083. auto res = cli_.Post(
  7084. "/post-loopback", 9,
  7085. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7086. EXPECT_EQ(9u, length);
  7087. sink.write("123", 3);
  7088. sink.write("456", 3);
  7089. sink.write("789", 3);
  7090. return true;
  7091. },
  7092. "text/plain",
  7093. [&body](const char *data, size_t data_length) {
  7094. body.append(data, data_length);
  7095. return true;
  7096. });
  7097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7098. EXPECT_EQ(StatusCode::OK_200, res->status);
  7099. EXPECT_EQ("123456789", body);
  7100. }
  7101. TEST_F(ServerTest, PutLoopBack) {
  7102. std::string body;
  7103. auto res = cli_.Put(
  7104. "/put-loopback", 9,
  7105. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7106. EXPECT_EQ(9u, length);
  7107. sink.write("123", 3);
  7108. sink.write("456", 3);
  7109. sink.write("789", 3);
  7110. return true;
  7111. },
  7112. "text/plain",
  7113. [&body](const char *data, size_t data_length) {
  7114. body.append(data, data_length);
  7115. return true;
  7116. });
  7117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7118. EXPECT_EQ(StatusCode::OK_200, res->status);
  7119. EXPECT_EQ("123456789", body);
  7120. }
  7121. TEST_F(ServerTest, PatchLoopBack) {
  7122. std::string body;
  7123. auto res = cli_.Patch(
  7124. "/patch-loopback", 9,
  7125. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7126. EXPECT_EQ(9u, length);
  7127. sink.write("123", 3);
  7128. sink.write("456", 3);
  7129. sink.write("789", 3);
  7130. return true;
  7131. },
  7132. "text/plain",
  7133. [&body](const char *data, size_t data_length) {
  7134. body.append(data, data_length);
  7135. return true;
  7136. });
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::OK_200, res->status);
  7139. EXPECT_EQ("123456789", body);
  7140. }
  7141. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7142. std::string body;
  7143. auto res = cli_.Post(
  7144. "/post-loopback",
  7145. [](size_t /*offset*/, DataSink &sink) {
  7146. sink.write("123", 3);
  7147. sink.write("456", 3);
  7148. sink.write("789", 3);
  7149. sink.done();
  7150. return true;
  7151. },
  7152. "text/plain",
  7153. [&body](const char *data, size_t data_length) {
  7154. body.append(data, data_length);
  7155. return true;
  7156. });
  7157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7158. EXPECT_EQ(StatusCode::OK_200, res->status);
  7159. EXPECT_EQ("123456789", body);
  7160. }
  7161. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7162. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7163. cli_.set_compress(true);
  7164. auto res = cli_.Put(
  7165. "/put", 3,
  7166. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7167. sink.os << "PUT";
  7168. return true;
  7169. },
  7170. "text/plain");
  7171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7172. EXPECT_EQ(StatusCode::OK_200, res->status);
  7173. EXPECT_EQ("PUT", res->body);
  7174. }
  7175. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7176. cli_.set_compress(true);
  7177. auto res = cli_.Post(
  7178. "/post", 42,
  7179. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7180. return false;
  7181. },
  7182. "text/plain");
  7183. ASSERT_TRUE(!res);
  7184. EXPECT_EQ(Error::Canceled, res.error());
  7185. }
  7186. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7187. cli_.set_compress(true);
  7188. auto res = cli_.Put(
  7189. "/put",
  7190. [](size_t /*offset*/, DataSink &sink) {
  7191. sink.os << "PUT";
  7192. sink.done();
  7193. return true;
  7194. },
  7195. "text/plain");
  7196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7197. EXPECT_EQ(StatusCode::OK_200, res->status);
  7198. EXPECT_EQ("PUT", res->body);
  7199. }
  7200. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7201. cli_.set_compress(true);
  7202. auto res = cli_.Post(
  7203. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7204. "text/plain");
  7205. ASSERT_TRUE(!res);
  7206. EXPECT_EQ(Error::Canceled, res.error());
  7207. }
  7208. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7209. cli_.set_compress(true);
  7210. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7212. EXPECT_EQ(StatusCode::OK_200, res->status);
  7213. EXPECT_EQ(LARGE_DATA, res->body);
  7214. }
  7215. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7216. #ifdef CPPHTTPLIB_SSL_ENABLED
  7217. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7218. Client cli(s.c_str());
  7219. cli.enable_server_certificate_verification(false);
  7220. #else
  7221. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7222. Client cli(s.c_str());
  7223. #endif
  7224. cli.set_compress(true);
  7225. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7227. EXPECT_EQ(StatusCode::OK_200, res->status);
  7228. EXPECT_EQ(LARGE_DATA, res->body);
  7229. // The compressed size should be less than a 10th of the original. May vary
  7230. // depending on the zlib library.
  7231. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7232. static_cast<uint64_t>(10 * 1024 * 1024));
  7233. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7234. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7235. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7236. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7237. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7238. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7239. #endif
  7240. }
  7241. TEST_F(ServerTest, PutContentWithDeflate) {
  7242. cli_.set_compress(false);
  7243. Headers headers;
  7244. headers.emplace("Content-Encoding", "deflate");
  7245. // PUT in deflate format:
  7246. auto res = cli_.Put("/put", headers,
  7247. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7249. EXPECT_EQ(StatusCode::OK_200, res->status);
  7250. EXPECT_EQ("PUT", res->body);
  7251. }
  7252. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7253. Headers headers;
  7254. headers.emplace("Accept-Encoding", "gzip, deflate");
  7255. auto res = cli_.Get("/streamed-chunked", headers);
  7256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7257. EXPECT_EQ(StatusCode::OK_200, res->status);
  7258. EXPECT_EQ(std::string("123456789"), res->body);
  7259. }
  7260. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7261. Headers headers;
  7262. headers.emplace("Accept-Encoding", "gzip, deflate");
  7263. auto res = cli_.Get("/streamed-chunked2", headers);
  7264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7265. EXPECT_EQ(StatusCode::OK_200, res->status);
  7266. EXPECT_EQ(std::string("123456789"), res->body);
  7267. }
  7268. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7269. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. }
  7273. TEST(GzipDecompressor, ChunkedDecompression) {
  7274. std::string data;
  7275. for (size_t i = 0; i < 32 * 1024; ++i) {
  7276. data.push_back(static_cast<char>('a' + i % 26));
  7277. }
  7278. std::string compressed_data;
  7279. {
  7280. httplib::detail::gzip_compressor compressor;
  7281. bool result = compressor.compress(
  7282. data.data(), data.size(),
  7283. /*last=*/true,
  7284. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7285. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7286. compressed_data_size);
  7287. return true;
  7288. });
  7289. ASSERT_TRUE(result);
  7290. }
  7291. std::string decompressed_data;
  7292. {
  7293. httplib::detail::gzip_decompressor decompressor;
  7294. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7295. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7296. size_t chunk_size = 130;
  7297. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7298. chunk_begin += chunk_size) {
  7299. size_t current_chunk_size =
  7300. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7301. bool result = decompressor.decompress(
  7302. compressed_data.data() + chunk_begin, current_chunk_size,
  7303. [&](const char *decompressed_data_chunk,
  7304. size_t decompressed_data_chunk_size) {
  7305. decompressed_data.insert(decompressed_data.size(),
  7306. decompressed_data_chunk,
  7307. decompressed_data_chunk_size);
  7308. return true;
  7309. });
  7310. ASSERT_TRUE(result);
  7311. }
  7312. }
  7313. ASSERT_EQ(data, decompressed_data);
  7314. }
  7315. TEST(GzipDecompressor, DeflateDecompression) {
  7316. std::string original_text = "Raw deflate without gzip";
  7317. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7318. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7319. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7320. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7321. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7322. std::string decompressed_data;
  7323. {
  7324. httplib::detail::gzip_decompressor decompressor;
  7325. bool result = decompressor.decompress(
  7326. compressed_data.data(), compressed_data.size(),
  7327. [&](const char *decompressed_data_chunk,
  7328. size_t decompressed_data_chunk_size) {
  7329. decompressed_data.insert(decompressed_data.size(),
  7330. decompressed_data_chunk,
  7331. decompressed_data_chunk_size);
  7332. return true;
  7333. });
  7334. ASSERT_TRUE(result);
  7335. }
  7336. ASSERT_EQ(original_text, decompressed_data);
  7337. }
  7338. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7339. std::string original_text = "Raw deflate without gzip";
  7340. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7341. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7342. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7343. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7344. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7345. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7346. std::string decompressed_data;
  7347. {
  7348. httplib::detail::gzip_decompressor decompressor;
  7349. bool result = decompressor.decompress(
  7350. compressed_data.data(), compressed_data.size(),
  7351. [&](const char *decompressed_data_chunk,
  7352. size_t decompressed_data_chunk_size) {
  7353. decompressed_data.insert(decompressed_data.size(),
  7354. decompressed_data_chunk,
  7355. decompressed_data_chunk_size);
  7356. return true;
  7357. });
  7358. ASSERT_TRUE(result);
  7359. }
  7360. ASSERT_EQ(original_text, decompressed_data);
  7361. }
  7362. #endif
  7363. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7364. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7365. Headers headers;
  7366. headers.emplace("Accept-Encoding", "br");
  7367. auto res = cli_.Get("/streamed-chunked", headers);
  7368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7369. EXPECT_EQ(StatusCode::OK_200, res->status);
  7370. EXPECT_EQ(std::string("123456789"), res->body);
  7371. }
  7372. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7373. Headers headers;
  7374. headers.emplace("Accept-Encoding", "br");
  7375. auto res = cli_.Get("/streamed-chunked2", headers);
  7376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7377. EXPECT_EQ(StatusCode::OK_200, res->status);
  7378. EXPECT_EQ(std::string("123456789"), res->body);
  7379. }
  7380. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7381. cli_.set_compress(true);
  7382. auto res = cli_.Put(
  7383. "/put", 3,
  7384. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7385. sink.os << "PUT";
  7386. return true;
  7387. },
  7388. "text/plain");
  7389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7390. EXPECT_EQ(StatusCode::OK_200, res->status);
  7391. EXPECT_EQ("PUT", res->body);
  7392. }
  7393. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7394. cli_.set_compress(true);
  7395. auto res = cli_.Put(
  7396. "/put",
  7397. [](size_t /*offset*/, DataSink &sink) {
  7398. sink.os << "PUT";
  7399. sink.done();
  7400. return true;
  7401. },
  7402. "text/plain");
  7403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7404. EXPECT_EQ(StatusCode::OK_200, res->status);
  7405. EXPECT_EQ("PUT", res->body);
  7406. }
  7407. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7408. cli_.set_compress(true);
  7409. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7411. EXPECT_EQ(StatusCode::OK_200, res->status);
  7412. EXPECT_EQ(LARGE_DATA, res->body);
  7413. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7414. }
  7415. #endif
  7416. TEST_F(ServerTest, Patch) {
  7417. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7419. EXPECT_EQ(StatusCode::OK_200, res->status);
  7420. EXPECT_EQ("PATCH", res->body);
  7421. }
  7422. TEST_F(ServerTest, Delete) {
  7423. auto res = cli_.Delete("/delete");
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. EXPECT_EQ("DELETE", res->body);
  7427. }
  7428. TEST_F(ServerTest, DeleteContentReceiver) {
  7429. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7431. EXPECT_EQ(StatusCode::OK_200, res->status);
  7432. EXPECT_EQ("content", res->body);
  7433. }
  7434. TEST_F(ServerTest, Options) {
  7435. auto res = cli_.Options("*");
  7436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7437. EXPECT_EQ(StatusCode::OK_200, res->status);
  7438. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7439. EXPECT_TRUE(res->body.empty());
  7440. }
  7441. TEST_F(ServerTest, URL) {
  7442. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7444. EXPECT_EQ(StatusCode::OK_200, res->status);
  7445. }
  7446. TEST_F(ServerTest, ArrayParam) {
  7447. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7449. EXPECT_EQ(StatusCode::OK_200, res->status);
  7450. }
  7451. TEST_F(ServerTest, ArrayParamValues) {
  7452. auto res =
  7453. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7455. EXPECT_EQ(StatusCode::OK_200, res->status);
  7456. }
  7457. TEST_F(ServerTest, NoMultipleHeaders) {
  7458. Headers headers = {{"Content-Length", "5"}};
  7459. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7460. "text/plain");
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::OK_200, res->status);
  7463. }
  7464. TEST_F(ServerTest, PostContentReceiver) {
  7465. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. ASSERT_EQ(StatusCode::OK_200, res->status);
  7468. ASSERT_EQ("content", res->body);
  7469. }
  7470. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7471. UploadFormDataItems items = {
  7472. {"text1", "text default", "", ""},
  7473. {"text2", "aωb", "", ""},
  7474. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7475. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7476. {"file3", "", "", "application/octet-stream"},
  7477. };
  7478. auto res = cli_.Post("/content_receiver", items);
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_EQ(StatusCode::OK_200, res->status);
  7481. }
  7482. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7483. UploadFormDataItems items = {
  7484. {"text1", "text default", "", ""},
  7485. {"text2", "aωb", "", ""},
  7486. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7487. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7488. {"file3", "", "", "application/octet-stream"},
  7489. };
  7490. auto boundary = std::string("+++++");
  7491. std::string body;
  7492. for (const auto &item : items) {
  7493. body += "--" + boundary + "\r\n";
  7494. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7495. if (!item.filename.empty()) {
  7496. body += "; filename=\"" + item.filename + "\"";
  7497. }
  7498. body += "\r\n";
  7499. if (!item.content_type.empty()) {
  7500. body += "Content-Type: " + item.content_type + "\r\n";
  7501. }
  7502. body += "\r\n";
  7503. body += item.content + "\r\n";
  7504. }
  7505. body += "--" + boundary + "--\r\n";
  7506. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7507. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7509. EXPECT_EQ(StatusCode::OK_200, res->status);
  7510. }
  7511. TEST(MultipartFormDataTest, FieldEscaping) {
  7512. Server svr;
  7513. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7514. const ContentReader &content_reader) {
  7515. ASSERT_TRUE(req.is_multipart_form_data());
  7516. std::vector<FormData> received;
  7517. content_reader(
  7518. [&](const FormData &file) {
  7519. received.push_back(file);
  7520. return true;
  7521. },
  7522. [&](const char *data, size_t data_length) {
  7523. received.back().content.append(data, data_length);
  7524. return true;
  7525. });
  7526. // '"', CR and LF in names and filenames are escaped following the
  7527. // WHATWG HTML standard, so each part still parses as a single part
  7528. // with no injected headers. Content types get CR/LF escaped too,
  7529. // while '"' (legal there, e.g. quoted charset) is preserved.
  7530. ASSERT_EQ(4U, received.size());
  7531. EXPECT_EQ("na%22me", received[0].name);
  7532. EXPECT_EQ("quoted name", received[0].content);
  7533. EXPECT_EQ("file", received[1].name);
  7534. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7535. received[1].filename);
  7536. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7537. EXPECT_EQ("injected", received[1].content);
  7538. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7539. EXPECT_EQ("my%22file.txt", received[2].filename);
  7540. EXPECT_EQ("cr lf name", received[2].content);
  7541. EXPECT_EQ("typed", received[3].name);
  7542. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7543. received[3].content_type);
  7544. EXPECT_EQ("typed content", received[3].content);
  7545. });
  7546. auto port = svr.bind_to_any_port("localhost");
  7547. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7548. auto se = detail::scope_exit([&] {
  7549. svr.stop();
  7550. t.join();
  7551. ASSERT_FALSE(svr.is_running());
  7552. });
  7553. svr.wait_until_ready();
  7554. Client cli("localhost", port);
  7555. UploadFormDataItems items = {
  7556. {"na\"me", "quoted name", "", ""},
  7557. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7558. "application/octet-stream"},
  7559. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7560. {"typed", "typed content", "",
  7561. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7562. };
  7563. auto res = cli.Post("/post", items);
  7564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7565. EXPECT_EQ(StatusCode::OK_200, res->status);
  7566. }
  7567. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7568. const UploadFormDataItems items = {
  7569. {"name1", "Content 1", "", ""},
  7570. {"name2", "Content 2", "file2.txt", "text/plain"},
  7571. };
  7572. Server svr;
  7573. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7574. const ContentReader &content_reader) {
  7575. ASSERT_TRUE(req.is_multipart_form_data());
  7576. std::vector<FormData> received;
  7577. content_reader(
  7578. [&](const FormData &file) {
  7579. received.push_back(file);
  7580. return true;
  7581. },
  7582. [&](const char *data, size_t data_length) {
  7583. received.back().content.append(data, data_length);
  7584. return true;
  7585. });
  7586. ASSERT_EQ(2U, received.size());
  7587. EXPECT_EQ("name1", received[0].name);
  7588. EXPECT_EQ("Content 1", received[0].content);
  7589. EXPECT_EQ("name2", received[1].name);
  7590. EXPECT_EQ("Content 2", received[1].content);
  7591. EXPECT_EQ("file2.txt", received[1].filename);
  7592. EXPECT_EQ("text/plain", received[1].content_type);
  7593. });
  7594. auto port = svr.bind_to_any_port("localhost");
  7595. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7596. auto se = detail::scope_exit([&] {
  7597. svr.stop();
  7598. t.join();
  7599. ASSERT_FALSE(svr.is_running());
  7600. });
  7601. svr.wait_until_ready();
  7602. Client cli("localhost", port);
  7603. // Whole-body serialization with a generated boundary
  7604. {
  7605. MultipartFormDataWriter writer;
  7606. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7607. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7608. writer.content_type());
  7609. auto body = writer.serialize(items);
  7610. EXPECT_EQ(body.size(), writer.content_length(items));
  7611. auto res = cli.Post("/post", body, writer.content_type());
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ(StatusCode::OK_200, res->status);
  7614. }
  7615. // Per-part framing with a custom boundary via a content provider
  7616. {
  7617. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7618. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7619. MultipartFormDataWriter writer("custom-boundary_123");
  7620. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7621. std::string body;
  7622. for (const auto &item : items) {
  7623. body += writer.item_begin(item);
  7624. body += item.content;
  7625. body += MultipartFormDataWriter::item_end();
  7626. }
  7627. body += writer.finish();
  7628. EXPECT_EQ(body.size(), writer.content_length(items));
  7629. auto res = cli.Post(
  7630. "/post", body.size(),
  7631. [&](size_t offset, size_t length, DataSink &sink) {
  7632. sink.write(body.data() + offset, length);
  7633. return true;
  7634. },
  7635. writer.content_type());
  7636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7637. EXPECT_EQ(StatusCode::OK_200, res->status);
  7638. }
  7639. }
  7640. TEST_F(ServerTest, PostContentReceiverGzip) {
  7641. cli_.set_compress(true);
  7642. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7644. ASSERT_EQ(StatusCode::OK_200, res->status);
  7645. ASSERT_EQ("content", res->body);
  7646. }
  7647. TEST_F(ServerTest, PutContentReceiver) {
  7648. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7650. ASSERT_EQ(StatusCode::OK_200, res->status);
  7651. ASSERT_EQ("content", res->body);
  7652. }
  7653. TEST_F(ServerTest, PatchContentReceiver) {
  7654. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7656. ASSERT_EQ(StatusCode::OK_200, res->status);
  7657. ASSERT_EQ("content", res->body);
  7658. }
  7659. template <typename ClientType>
  7660. void TestWithHeadersAndContentReceiver(
  7661. ClientType &cli,
  7662. std::function<Result(ClientType &, const std::string &, const Headers &,
  7663. const std::string &, const std::string &,
  7664. ContentReceiver, DownloadProgress)>
  7665. request_func) {
  7666. Headers headers;
  7667. headers.emplace("X-Custom-Header", "test-value");
  7668. std::string received_body;
  7669. auto res = request_func(
  7670. cli, "/content_receiver", headers, "content", "application/json",
  7671. [&](const char *data, size_t data_length) {
  7672. received_body.append(data, data_length);
  7673. return true;
  7674. },
  7675. nullptr);
  7676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7677. EXPECT_EQ(StatusCode::OK_200, res->status);
  7678. EXPECT_EQ("content", received_body);
  7679. }
  7680. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7681. #ifdef CPPHTTPLIB_SSL_ENABLED
  7682. using ClientT = SSLClient;
  7683. #else
  7684. using ClientT = Client;
  7685. #endif
  7686. TestWithHeadersAndContentReceiver<ClientT>(
  7687. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7688. const std::string &body, const std::string &content_type,
  7689. ContentReceiver receiver, DownloadProgress progress) {
  7690. return cli.Post(path, headers, body, content_type, receiver, progress);
  7691. });
  7692. }
  7693. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7694. #ifdef CPPHTTPLIB_SSL_ENABLED
  7695. using ClientT = SSLClient;
  7696. #else
  7697. using ClientT = Client;
  7698. #endif
  7699. TestWithHeadersAndContentReceiver<ClientT>(
  7700. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7701. const std::string &body, const std::string &content_type,
  7702. ContentReceiver receiver, DownloadProgress progress) {
  7703. return cli.Put(path, headers, body, content_type, receiver, progress);
  7704. });
  7705. }
  7706. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7707. #ifdef CPPHTTPLIB_SSL_ENABLED
  7708. using ClientT = SSLClient;
  7709. #else
  7710. using ClientT = Client;
  7711. #endif
  7712. TestWithHeadersAndContentReceiver<ClientT>(
  7713. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7714. const std::string &body, const std::string &content_type,
  7715. ContentReceiver receiver, DownloadProgress progress) {
  7716. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7717. });
  7718. }
  7719. template <typename ClientType>
  7720. void TestWithHeadersAndContentReceiverWithProgress(
  7721. ClientType &cli,
  7722. std::function<Result(ClientType &, const std::string &, const Headers &,
  7723. const std::string &, const std::string &,
  7724. ContentReceiver, DownloadProgress)>
  7725. request_func) {
  7726. Headers headers;
  7727. headers.emplace("X-Test-Header", "progress-test");
  7728. std::string received_body;
  7729. auto progress_called = false;
  7730. auto res = request_func(
  7731. cli, "/content_receiver", headers, "content", "text/plain",
  7732. [&](const char *data, size_t data_length) {
  7733. received_body.append(data, data_length);
  7734. return true;
  7735. },
  7736. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7737. progress_called = true;
  7738. return true;
  7739. });
  7740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7741. EXPECT_EQ(StatusCode::OK_200, res->status);
  7742. EXPECT_EQ("content", received_body);
  7743. EXPECT_TRUE(progress_called);
  7744. }
  7745. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7746. #ifdef CPPHTTPLIB_SSL_ENABLED
  7747. using ClientT = SSLClient;
  7748. #else
  7749. using ClientT = Client;
  7750. #endif
  7751. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7752. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7753. const std::string &body, const std::string &content_type,
  7754. ContentReceiver receiver, DownloadProgress progress) {
  7755. return cli.Post(path, headers, body, content_type, receiver, progress);
  7756. });
  7757. }
  7758. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7759. #ifdef CPPHTTPLIB_SSL_ENABLED
  7760. using ClientT = SSLClient;
  7761. #else
  7762. using ClientT = Client;
  7763. #endif
  7764. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7765. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7766. const std::string &body, const std::string &content_type,
  7767. ContentReceiver receiver, DownloadProgress progress) {
  7768. return cli.Put(path, headers, body, content_type, receiver, progress);
  7769. });
  7770. }
  7771. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7772. #ifdef CPPHTTPLIB_SSL_ENABLED
  7773. using ClientT = SSLClient;
  7774. #else
  7775. using ClientT = Client;
  7776. #endif
  7777. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7778. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7779. const std::string &body, const std::string &content_type,
  7780. ContentReceiver receiver, DownloadProgress progress) {
  7781. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7782. });
  7783. }
  7784. template <typename ClientType>
  7785. void TestWithHeadersAndContentReceiverError(
  7786. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7787. const Headers &, const std::string &,
  7788. const std::string &, ContentReceiver)>
  7789. request_func) {
  7790. Headers headers;
  7791. headers.emplace("X-Error-Test", "true");
  7792. std::string received_body;
  7793. auto receiver_failed = false;
  7794. auto res =
  7795. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7796. [&](const char *data, size_t data_length) {
  7797. received_body.append(data, data_length);
  7798. receiver_failed = true;
  7799. return false;
  7800. });
  7801. ASSERT_FALSE(res);
  7802. EXPECT_TRUE(receiver_failed);
  7803. }
  7804. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7805. #ifdef CPPHTTPLIB_SSL_ENABLED
  7806. using ClientT = SSLClient;
  7807. #else
  7808. using ClientT = Client;
  7809. #endif
  7810. TestWithHeadersAndContentReceiverError<ClientT>(
  7811. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7812. const std::string &body, const std::string &content_type,
  7813. ContentReceiver receiver) {
  7814. return cli.Post(path, headers, body, content_type, receiver);
  7815. });
  7816. }
  7817. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7818. #ifdef CPPHTTPLIB_SSL_ENABLED
  7819. using ClientT = SSLClient;
  7820. #else
  7821. using ClientT = Client;
  7822. #endif
  7823. TestWithHeadersAndContentReceiverError<ClientT>(
  7824. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7825. const std::string &body, const std::string &content_type,
  7826. ContentReceiver receiver) {
  7827. return cli.Put(path, headers, body, content_type, receiver);
  7828. });
  7829. }
  7830. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7831. #ifdef CPPHTTPLIB_SSL_ENABLED
  7832. using ClientT = SSLClient;
  7833. #else
  7834. using ClientT = Client;
  7835. #endif
  7836. TestWithHeadersAndContentReceiverError<ClientT>(
  7837. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7838. const std::string &body, const std::string &content_type,
  7839. ContentReceiver receiver) {
  7840. return cli.Patch(path, headers, body, content_type, receiver);
  7841. });
  7842. }
  7843. TEST_F(ServerTest, PostQueryStringAndBody) {
  7844. auto res =
  7845. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7847. ASSERT_EQ(StatusCode::OK_200, res->status);
  7848. }
  7849. TEST_F(ServerTest, HTTP2Magic) {
  7850. Request req;
  7851. req.method = "PRI";
  7852. req.path = "*";
  7853. req.body = "SM";
  7854. auto res = std::make_shared<Response>();
  7855. auto error = Error::Success;
  7856. auto ret = cli_.send(req, *res, error);
  7857. ASSERT_TRUE(ret);
  7858. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7859. }
  7860. TEST_F(ServerTest, KeepAlive) {
  7861. auto res = cli_.Get("/hi");
  7862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7863. EXPECT_EQ(StatusCode::OK_200, res->status);
  7864. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7865. EXPECT_EQ("Hello World!", res->body);
  7866. res = cli_.Get("/hi");
  7867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7868. EXPECT_EQ(StatusCode::OK_200, res->status);
  7869. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7870. EXPECT_EQ("Hello World!", res->body);
  7871. res = cli_.Get("/hi");
  7872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7873. EXPECT_EQ(StatusCode::OK_200, res->status);
  7874. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7875. EXPECT_EQ("Hello World!", res->body);
  7876. res = cli_.Get("/not-exist");
  7877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7878. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7879. res = cli_.Post("/empty", "", "text/plain");
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ(StatusCode::OK_200, res->status);
  7882. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7883. EXPECT_EQ("empty", res->body);
  7884. EXPECT_EQ("close", res->get_header_value("Connection"));
  7885. res = cli_.Post(
  7886. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7887. "text/plain");
  7888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7889. EXPECT_EQ(StatusCode::OK_200, res->status);
  7890. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7891. EXPECT_EQ("empty", res->body);
  7892. cli_.set_keep_alive(false);
  7893. res = cli_.Get("/last-request");
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ(StatusCode::OK_200, res->status);
  7896. EXPECT_EQ("close", res->get_header_value("Connection"));
  7897. }
  7898. TEST_F(ServerTest, TooManyRedirect) {
  7899. cli_.set_follow_location(true);
  7900. auto res = cli_.Get("/redirect/0");
  7901. ASSERT_TRUE(!res);
  7902. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7903. }
  7904. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7905. Request req;
  7906. req.method = "FOOBAR";
  7907. req.path = "/hi";
  7908. cli_.set_keep_alive(true);
  7909. auto res = cli_.send(req);
  7910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7911. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7912. EXPECT_EQ("close", res->get_header_value("Connection"));
  7913. EXPECT_FALSE(cli_.is_socket_open());
  7914. }
  7915. TEST_F(ServerTest, CustomRouteReadsBody) {
  7916. const std::string xml =
  7917. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7918. Request req;
  7919. req.method = "PROPFIND";
  7920. req.path = "/dav/dir";
  7921. req.set_header("Depth", "1");
  7922. req.body = xml;
  7923. auto res = cli_.send(req);
  7924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7925. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7926. EXPECT_EQ(xml, res->body);
  7927. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7928. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7929. }
  7930. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7931. Request req;
  7932. req.method = "PROPFIND";
  7933. req.path = "/dav/42";
  7934. auto res = cli_.send(req);
  7935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7936. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7937. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7938. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7939. }
  7940. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7941. Request req;
  7942. req.method = "PROPFIND";
  7943. req.path = "/dav-re/123";
  7944. auto res = cli_.send(req);
  7945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7946. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7947. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7948. }
  7949. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7950. Request req;
  7951. req.method = "MKCOL";
  7952. req.path = "/dav-mkcol";
  7953. auto res = cli_.send(req);
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(StatusCode::Created_201, res->status);
  7956. }
  7957. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7958. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7959. Request req;
  7960. req.method = "REPORT";
  7961. req.path = "/dav-report";
  7962. req.body = xml;
  7963. auto res = cli_.send(req);
  7964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7965. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7966. EXPECT_EQ(xml, res->body);
  7967. }
  7968. // A content reader route must fire even when the request carries no body,
  7969. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7970. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7971. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7972. Request req;
  7973. req.method = "REPORT";
  7974. req.path = "/dav-report";
  7975. auto res = cli_.send(req);
  7976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7977. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7978. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7979. }
  7980. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7981. Request req;
  7982. req.method = "PROPFIND";
  7983. req.path = "/not-dav";
  7984. auto res = cli_.send(req);
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7987. }
  7988. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7989. Request req;
  7990. req.method = "UNLOCK";
  7991. req.path = "/dav/dir";
  7992. cli_.set_keep_alive(true);
  7993. auto res = cli_.send(req);
  7994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7995. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7996. EXPECT_EQ("close", res->get_header_value("Connection"));
  7997. EXPECT_FALSE(cli_.is_socket_open());
  7998. }
  7999. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8000. // The mount point serves this path, but only for GET and HEAD.
  8001. auto get_res = cli_.Get("/dir/index.html");
  8002. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8003. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8004. Request req;
  8005. req.method = "PROPFIND";
  8006. req.path = "/dir/index.html";
  8007. auto res = cli_.send(req);
  8008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8009. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8010. }
  8011. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8012. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8013. cli_.set_keep_alive(true);
  8014. for (auto i = 0; i < 2; i++) {
  8015. Request req;
  8016. req.method = "PROPFIND";
  8017. req.path = "/dav/dir";
  8018. req.body = xml;
  8019. auto res = cli_.send(req);
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8022. EXPECT_EQ(xml, res->body);
  8023. EXPECT_TRUE(cli_.is_socket_open());
  8024. }
  8025. // A built-in method must still be served on the same connection.
  8026. cli_.set_keep_alive(false);
  8027. auto res = cli_.Get("/hi");
  8028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8029. EXPECT_EQ(StatusCode::OK_200, res->status);
  8030. EXPECT_EQ("close", res->get_header_value("Connection"));
  8031. }
  8032. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8033. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8034. Request req;
  8035. req.method = "PROPFIND";
  8036. req.path = "/dav/dir";
  8037. req.set_header("Expect", "100-continue");
  8038. req.body = xml;
  8039. auto res = cli_.send(req);
  8040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8041. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8042. EXPECT_EQ(xml, res->body);
  8043. }
  8044. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8045. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8046. TEST_F(ServerTest, Gzip) {
  8047. Headers headers;
  8048. headers.emplace("Accept-Encoding", "gzip, deflate");
  8049. auto res = cli_.Get("/compress", headers);
  8050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8051. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8052. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8053. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8054. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8055. "7890123456789012345678901234567890",
  8056. res->body);
  8057. EXPECT_EQ(StatusCode::OK_200, res->status);
  8058. }
  8059. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8060. Headers headers;
  8061. headers.emplace("Accept-Encoding", "gzip, deflate");
  8062. auto res = cli_.Get("/compress-with-charset", headers);
  8063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8064. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8065. EXPECT_EQ("application/json; charset=utf-8",
  8066. res->get_header_value("Content-Type"));
  8067. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8068. "7890123456789012345678901234567890",
  8069. res->body);
  8070. EXPECT_EQ(StatusCode::OK_200, res->status);
  8071. }
  8072. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8073. Headers headers;
  8074. headers.emplace("Accept-Encoding", "");
  8075. auto res = cli_.Get("/compress", headers);
  8076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8077. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8079. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8080. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8081. "7890123456789012345678901234567890",
  8082. res->body);
  8083. EXPECT_EQ(StatusCode::OK_200, res->status);
  8084. }
  8085. TEST_F(ServerTest, GzipWithContentReceiver) {
  8086. Headers headers;
  8087. headers.emplace("Accept-Encoding", "gzip, deflate");
  8088. std::string body;
  8089. auto res = cli_.Get("/compress", headers,
  8090. [&](const char *data, uint64_t data_length) {
  8091. EXPECT_EQ(100U, data_length);
  8092. body.append(data, data_length);
  8093. return true;
  8094. });
  8095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8096. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8097. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8098. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8099. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8100. "7890123456789012345678901234567890",
  8101. body);
  8102. EXPECT_EQ(StatusCode::OK_200, res->status);
  8103. }
  8104. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8105. Headers headers;
  8106. headers.emplace("Accept-Encoding", "gzip, deflate");
  8107. cli_.set_decompress(false);
  8108. auto res = cli_.Get("/compress", headers);
  8109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8110. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8111. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8112. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8113. EXPECT_EQ(33U, res->body.size());
  8114. EXPECT_EQ(StatusCode::OK_200, res->status);
  8115. }
  8116. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8117. Headers headers;
  8118. headers.emplace("Accept-Encoding", "");
  8119. std::string body;
  8120. auto res = cli_.Get("/compress", headers,
  8121. [&](const char *data, uint64_t data_length) {
  8122. EXPECT_EQ(100U, data_length);
  8123. body.append(data, data_length);
  8124. return true;
  8125. });
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8128. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8129. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8130. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8131. "7890123456789012345678901234567890",
  8132. body);
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. }
  8135. TEST_F(ServerTest, NoGzip) {
  8136. Headers headers;
  8137. headers.emplace("Accept-Encoding", "gzip, deflate");
  8138. auto res = cli_.Get("/nocompress", headers);
  8139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8140. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8141. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8142. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8143. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8144. "7890123456789012345678901234567890",
  8145. res->body);
  8146. EXPECT_EQ(StatusCode::OK_200, res->status);
  8147. }
  8148. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8149. Headers headers;
  8150. headers.emplace("Accept-Encoding", "gzip, deflate");
  8151. std::string body;
  8152. auto res = cli_.Get("/nocompress", headers,
  8153. [&](const char *data, uint64_t data_length) {
  8154. EXPECT_EQ(100U, data_length);
  8155. body.append(data, data_length);
  8156. return true;
  8157. });
  8158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8159. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8160. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8161. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8162. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8163. "7890123456789012345678901234567890",
  8164. body);
  8165. EXPECT_EQ(StatusCode::OK_200, res->status);
  8166. }
  8167. TEST_F(ServerTest, MultipartFormDataGzip) {
  8168. UploadFormDataItems items = {
  8169. {"key1", "test", "", ""},
  8170. {"key2", "--abcdefg123", "", ""},
  8171. };
  8172. cli_.set_compress(true);
  8173. auto res = cli_.Post("/compress-multipart", items);
  8174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8175. EXPECT_EQ(StatusCode::OK_200, res->status);
  8176. }
  8177. #endif
  8178. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8179. // Static file compression is opt-in, so these run their own server rather than
  8180. // flipping it on for the shared ServerTest fixture, which would silently
  8181. // rewrite what every other static file test is asserting.
  8182. class StaticFileCompressionTest : public ::testing::Test {
  8183. protected:
  8184. void TearDown() override {
  8185. if (t_.joinable()) {
  8186. svr_.stop();
  8187. t_.join();
  8188. }
  8189. }
  8190. int start(const std::function<void(Server &)> &configure = nullptr) {
  8191. // Serves the same tree as a directory of build-time compressed assets
  8192. // would be served: the mount point names the coding the files are already
  8193. // stored in. Registered before "/" so it is the one that matches.
  8194. svr_.set_mount_point("/pre-encoded", "./www",
  8195. {{"Content-Encoding", "gzip"}});
  8196. svr_.set_mount_point("/", "./www");
  8197. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8198. res.set_file_content("./www/dir/index.html", "text/html");
  8199. });
  8200. svr_.Get("/pre-encoded-file-content",
  8201. [](const Request & /*req*/, Response &res) {
  8202. res.set_header("Content-Encoding", "gzip");
  8203. res.set_file_content("./www/dir/index.html", "text/html");
  8204. });
  8205. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8206. res.set_content_provider(
  8207. 6, "text/plain",
  8208. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8209. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8210. return true;
  8211. });
  8212. });
  8213. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8214. res.set_content_provider(
  8215. 1000, "text/plain",
  8216. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8217. if (offset < 100) {
  8218. std::string data(100, 'A');
  8219. sink.write(data.data(), data.size());
  8220. return true;
  8221. }
  8222. std::this_thread::sleep_for(std::chrono::seconds(2));
  8223. std::string data(900, 'B');
  8224. sink.write(data.data(), data.size());
  8225. return true;
  8226. });
  8227. });
  8228. if (configure) { configure(svr_); }
  8229. auto port = svr_.bind_to_any_port(HOST);
  8230. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8231. svr_.wait_until_ready();
  8232. return port;
  8233. }
  8234. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8235. // Every file under ./www except 1MB.txt is smaller than the default
  8236. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8237. // it out of the way.
  8238. static void enable_without_floor(Server &svr) {
  8239. svr.set_static_file_compression(true);
  8240. svr.set_static_file_compression_min_length(0);
  8241. }
  8242. Server svr_;
  8243. std::thread t_;
  8244. };
  8245. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8246. auto port = start();
  8247. Client cli(HOST, port);
  8248. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8250. EXPECT_EQ(StatusCode::OK_200, res->status);
  8251. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8252. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8253. EXPECT_EQ(1048576U, res->body.size());
  8254. }
  8255. TEST_F(StaticFileCompressionTest, MountPoint) {
  8256. auto port = start(enable);
  8257. Client cli(HOST, port);
  8258. cli.set_decompress(false);
  8259. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8261. EXPECT_EQ(StatusCode::OK_200, res->status);
  8262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8263. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8264. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8265. // The response stays self-delimiting: a length, not a chunked body.
  8266. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8267. EXPECT_EQ(std::to_string(res->body.size()),
  8268. res->get_header_value("Content-Length"));
  8269. EXPECT_LT(res->body.size(), 1048576U);
  8270. EXPECT_FALSE(res->body.empty());
  8271. }
  8272. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8273. auto port = start(enable);
  8274. Client cli(HOST, port);
  8275. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8277. EXPECT_EQ(StatusCode::OK_200, res->status);
  8278. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8279. EXPECT_EQ(1048576U, res->body.size());
  8280. }
  8281. TEST_F(StaticFileCompressionTest, FileContent) {
  8282. auto port = start(enable_without_floor);
  8283. Client cli(HOST, port);
  8284. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8286. EXPECT_EQ(StatusCode::OK_200, res->status);
  8287. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8288. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8289. EXPECT_EQ(104U, res->body.size());
  8290. }
  8291. // A handler that serves an already-encoded file names the coding itself. The
  8292. // file-backed path decided its coding from Accept-Encoding and the content
  8293. // type alone, so it compressed the stored bytes a second time and appended a
  8294. // second Content-Encoding field line.
  8295. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8296. auto port = start(enable_without_floor);
  8297. Client cli(HOST, port);
  8298. cli.set_decompress(false);
  8299. auto res = cli.Get("/pre-encoded-file-content",
  8300. Headers{{"Accept-Encoding", "gzip"}});
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(StatusCode::OK_200, res->status);
  8303. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8304. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8305. // Vary belongs to a coding the server chose, and it chose none here.
  8306. EXPECT_FALSE(res->has_header("Vary"));
  8307. // The file travels exactly as it is stored on disk.
  8308. EXPECT_EQ(104U, res->body.size());
  8309. }
  8310. // The 1MB file clears the default floor, so this one runs the configuration a
  8311. // deployment would actually have.
  8312. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8313. auto port = start(enable);
  8314. Client cli(HOST, port);
  8315. cli.set_decompress(false);
  8316. auto res =
  8317. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8319. EXPECT_EQ(StatusCode::OK_200, res->status);
  8320. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8321. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8322. EXPECT_FALSE(res->has_header("Vary"));
  8323. EXPECT_EQ(1048576U, res->body.size());
  8324. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8325. }
  8326. TEST_F(StaticFileCompressionTest, Head) {
  8327. auto port = start(enable);
  8328. Client cli(HOST, port);
  8329. cli.set_decompress(false);
  8330. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8331. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8332. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8334. EXPECT_EQ(StatusCode::OK_200, res->status);
  8335. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8336. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8337. // HEAD still reports the size a GET would return.
  8338. EXPECT_EQ(get->get_header_value("Content-Length"),
  8339. res->get_header_value("Content-Length"));
  8340. EXPECT_TRUE(res->body.empty());
  8341. }
  8342. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8343. auto port = start(enable);
  8344. Client cli(HOST, port);
  8345. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8346. {"Accept-Encoding", "gzip"}});
  8347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8348. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8349. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8350. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8351. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8352. EXPECT_EQ("cd", res->body);
  8353. }
  8354. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8355. auto port = start(enable);
  8356. Client cli(HOST, port);
  8357. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8359. EXPECT_EQ(StatusCode::OK_200, res->status);
  8360. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8361. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8362. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8363. }
  8364. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8365. auto port = start(enable);
  8366. Client cli(HOST, port);
  8367. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8369. EXPECT_EQ(StatusCode::OK_200, res->status);
  8370. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8371. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8372. EXPECT_TRUE(res->body.empty());
  8373. }
  8374. TEST_F(StaticFileCompressionTest, MinLength) {
  8375. auto port = start(enable);
  8376. Client cli(HOST, port);
  8377. // 104 bytes, well under the default floor. Compressing it would add the
  8378. // gzip header and trailer to a body that already fits in one packet.
  8379. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8381. EXPECT_EQ(StatusCode::OK_200, res->status);
  8382. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8383. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8384. }
  8385. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8386. auto port = start([](Server &svr) {
  8387. svr.set_static_file_compression(true);
  8388. svr.set_static_file_compression_min_length(1);
  8389. });
  8390. Client cli(HOST, port);
  8391. cli.set_decompress(false);
  8392. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8394. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8395. // A 9-byte file comes back larger than it went in, because gzip's header and
  8396. // trailer outweigh anything deflate can save. That is the end of the range
  8397. // the floor exists to keep out.
  8398. EXPECT_GT(res->body.size(), 9U);
  8399. }
  8400. TEST_F(StaticFileCompressionTest, MaxLength) {
  8401. auto port = start([](Server &svr) {
  8402. svr.set_static_file_compression(true);
  8403. svr.set_static_file_compression_min_length(0);
  8404. svr.set_static_file_compression_max_length(1024);
  8405. });
  8406. Client cli(HOST, port);
  8407. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8408. // defines `small` as a macro on Windows.
  8409. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8410. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8411. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8412. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8413. // Under it: compressed.
  8414. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8415. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8416. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8417. }
  8418. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8419. auto port = start(enable_without_floor);
  8420. Client cli(HOST, port);
  8421. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8422. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8423. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8424. auto identity_etag = identity->get_header_value("ETag");
  8425. ASSERT_FALSE(identity_etag.empty());
  8426. auto gzipped =
  8427. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8428. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8429. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8430. auto gzip_etag = gzipped->get_header_value("ETag");
  8431. ASSERT_FALSE(gzip_etag.empty());
  8432. // Two representations, two validators.
  8433. EXPECT_NE(identity_etag, gzip_etag);
  8434. // Each one revalidates against the request that would produce it...
  8435. auto fresh =
  8436. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8437. {"If-None-Match", gzip_etag}});
  8438. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8439. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8440. auto fresh_identity =
  8441. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8442. {"If-None-Match", identity_etag}});
  8443. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8444. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8445. // ...and not against the other representation.
  8446. auto crossed =
  8447. cli.Get("/dir/index.html",
  8448. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8449. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8450. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8451. }
  8452. // The opt-in covers responses the server reads off disk itself. A caller's own
  8453. // known-length provider keeps its Content-Length and, more importantly, keeps
  8454. // delivering incrementally: routing it through a compressor would hold every
  8455. // write back until zlib's window filled.
  8456. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8457. auto port = start(enable);
  8458. Client cli(HOST, port);
  8459. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8461. EXPECT_EQ(StatusCode::OK_200, res->status);
  8462. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8463. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8464. EXPECT_EQ("aaabbb", res->body);
  8465. }
  8466. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8467. auto port = start(enable);
  8468. Client cli(HOST, port);
  8469. cli.set_read_timeout(1, 0);
  8470. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8471. Headers{{"Accept-Encoding", "gzip"}});
  8472. ASSERT_TRUE(handle.is_valid());
  8473. // The provider writes 100 bytes and then stalls for longer than the read
  8474. // timeout. Those first bytes have to arrive anyway: run the response through
  8475. // a compressor and zlib holds them until its window fills, so the read would
  8476. // come back empty instead.
  8477. char buf[256];
  8478. auto n = handle.read(buf, sizeof(buf));
  8479. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8480. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8481. }
  8482. #endif
  8483. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8484. TEST_F(ServerTest, Brotli) {
  8485. Headers headers;
  8486. headers.emplace("Accept-Encoding", "br");
  8487. auto res = cli_.Get("/compress", headers);
  8488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8489. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8490. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8491. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8492. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8493. "7890123456789012345678901234567890",
  8494. res->body);
  8495. EXPECT_EQ(StatusCode::OK_200, res->status);
  8496. }
  8497. #endif
  8498. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8499. TEST_F(ServerTest, Zstd) {
  8500. Headers headers;
  8501. headers.emplace("Accept-Encoding", "zstd");
  8502. auto res = cli_.Get("/compress", headers);
  8503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8504. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8505. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8506. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8507. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8508. "7890123456789012345678901234567890",
  8509. res->body);
  8510. EXPECT_EQ(StatusCode::OK_200, res->status);
  8511. }
  8512. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8513. Headers headers;
  8514. headers.emplace("Accept-Encoding", "");
  8515. auto res = cli_.Get("/compress", headers);
  8516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8517. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8518. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8519. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8520. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8521. "7890123456789012345678901234567890",
  8522. res->body);
  8523. EXPECT_EQ(StatusCode::OK_200, res->status);
  8524. }
  8525. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8526. Headers headers;
  8527. headers.emplace("Accept-Encoding", "zstd");
  8528. std::string body;
  8529. auto res = cli_.Get("/compress", headers,
  8530. [&](const char *data, uint64_t data_length) {
  8531. EXPECT_EQ(100U, data_length);
  8532. body.append(data, data_length);
  8533. return true;
  8534. });
  8535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8536. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8537. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8538. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8539. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8540. "7890123456789012345678901234567890",
  8541. body);
  8542. EXPECT_EQ(StatusCode::OK_200, res->status);
  8543. }
  8544. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8545. Headers headers;
  8546. headers.emplace("Accept-Encoding", "zstd");
  8547. cli_.set_decompress(false);
  8548. auto res = cli_.Get("/compress", headers);
  8549. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8550. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8551. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8552. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8554. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8556. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8557. EXPECT_EQ(StatusCode::OK_200, res->status);
  8558. ASSERT_EQ(26U, res->body.size());
  8559. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8560. 0);
  8561. }
  8562. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8563. Headers headers;
  8564. headers.emplace("Accept-Encoding", "");
  8565. std::string body;
  8566. auto res = cli_.Get("/compress", headers,
  8567. [&](const char *data, uint64_t data_length) {
  8568. EXPECT_EQ(100U, data_length);
  8569. body.append(data, data_length);
  8570. return true;
  8571. });
  8572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8573. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8575. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8576. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8577. "7890123456789012345678901234567890",
  8578. body);
  8579. EXPECT_EQ(StatusCode::OK_200, res->status);
  8580. }
  8581. TEST_F(ServerTest, NoZstd) {
  8582. Headers headers;
  8583. headers.emplace("Accept-Encoding", "zstd");
  8584. auto res = cli_.Get("/nocompress", headers);
  8585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8586. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8587. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8588. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8589. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8590. "7890123456789012345678901234567890",
  8591. res->body);
  8592. EXPECT_EQ(StatusCode::OK_200, res->status);
  8593. }
  8594. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8595. Headers headers;
  8596. headers.emplace("Accept-Encoding", "zstd");
  8597. std::string body;
  8598. auto res = cli_.Get("/nocompress", headers,
  8599. [&](const char *data, uint64_t data_length) {
  8600. EXPECT_EQ(100U, data_length);
  8601. body.append(data, data_length);
  8602. return true;
  8603. });
  8604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8605. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8606. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8607. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8608. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8609. "7890123456789012345678901234567890",
  8610. body);
  8611. EXPECT_EQ(StatusCode::OK_200, res->status);
  8612. }
  8613. // TODO: How to enable zstd ??
  8614. TEST_F(ServerTest, MultipartFormDataZstd) {
  8615. UploadFormDataItems items = {
  8616. {"key1", "test", "", ""},
  8617. {"key2", "--abcdefg123", "", ""},
  8618. };
  8619. Headers headers;
  8620. headers.emplace("Accept-Encoding", "zstd");
  8621. cli_.set_compress(true);
  8622. auto res = cli_.Post("/compress-multipart", headers, items);
  8623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8624. EXPECT_EQ(StatusCode::OK_200, res->status);
  8625. }
  8626. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8627. Headers headers;
  8628. headers.emplace("Accept-Encoding", "zstd");
  8629. cli_.set_compress(true);
  8630. auto res = cli_.Put(
  8631. "/put", headers, 3,
  8632. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8633. sink.os << "PUT";
  8634. return true;
  8635. },
  8636. "text/plain");
  8637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8638. EXPECT_EQ(StatusCode::OK_200, res->status);
  8639. EXPECT_EQ("PUT", res->body);
  8640. }
  8641. // Pre-compression logging tests
  8642. TEST_F(ServerTest, PreCompressionLogging) {
  8643. // Test data for compression (matches the actual /compress endpoint content)
  8644. const std::string test_content =
  8645. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8646. "3456789012345678901234567890";
  8647. // Variables to capture logging data
  8648. std::string pre_compression_body;
  8649. std::string pre_compression_content_type;
  8650. std::string pre_compression_content_encoding;
  8651. std::string post_compression_body;
  8652. std::string post_compression_content_type;
  8653. std::string post_compression_content_encoding;
  8654. // Set up pre-compression logger
  8655. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8656. const Response &res) {
  8657. pre_compression_body = res.body;
  8658. pre_compression_content_type = res.get_header_value("Content-Type");
  8659. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8660. });
  8661. // Set up post-compression logger
  8662. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8663. post_compression_body = res.body;
  8664. post_compression_content_type = res.get_header_value("Content-Type");
  8665. post_compression_content_encoding =
  8666. res.get_header_value("Content-Encoding");
  8667. });
  8668. // Test with gzip compression
  8669. Headers headers;
  8670. headers.emplace("Accept-Encoding", "gzip");
  8671. auto res = cli_.Get("/compress", headers);
  8672. // Verify response was compressed
  8673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8674. EXPECT_EQ(StatusCode::OK_200, res->status);
  8675. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8676. // Verify pre-compression logger captured uncompressed content
  8677. EXPECT_EQ(test_content, pre_compression_body);
  8678. EXPECT_EQ("text/plain", pre_compression_content_type);
  8679. EXPECT_TRUE(pre_compression_content_encoding
  8680. .empty()); // No encoding header before compression
  8681. // Verify post-compression logger captured compressed content
  8682. EXPECT_NE(test_content,
  8683. post_compression_body); // Should be different after compression
  8684. EXPECT_EQ("text/plain", post_compression_content_type);
  8685. EXPECT_EQ("gzip", post_compression_content_encoding);
  8686. // Verify compressed content is smaller
  8687. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8688. }
  8689. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8690. const std::string test_content =
  8691. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8692. "3456789012345678901234567890";
  8693. std::string pre_compression_body;
  8694. std::string post_compression_body;
  8695. svr_.set_pre_compression_logger(
  8696. [&](const Request & /*req*/, const Response &res) {
  8697. pre_compression_body = res.body;
  8698. });
  8699. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8700. post_compression_body = res.body;
  8701. });
  8702. Headers headers;
  8703. headers.emplace("Accept-Encoding", "br");
  8704. auto res = cli_.Get("/compress", headers);
  8705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8706. EXPECT_EQ(StatusCode::OK_200, res->status);
  8707. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8708. // Verify pre-compression content is uncompressed
  8709. EXPECT_EQ(test_content, pre_compression_body);
  8710. // Verify post-compression content is compressed
  8711. EXPECT_NE(test_content, post_compression_body);
  8712. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8713. }
  8714. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8715. const std::string test_content =
  8716. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8717. "3456789012345678901234567890";
  8718. std::string pre_compression_body;
  8719. std::string post_compression_body;
  8720. svr_.set_pre_compression_logger(
  8721. [&](const Request & /*req*/, const Response &res) {
  8722. pre_compression_body = res.body;
  8723. });
  8724. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8725. post_compression_body = res.body;
  8726. });
  8727. // Request without compression (use /nocompress endpoint)
  8728. Headers headers;
  8729. auto res = cli_.Get("/nocompress", headers);
  8730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8731. EXPECT_EQ(StatusCode::OK_200, res->status);
  8732. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8733. // Pre-compression logger should not be called when no compression is applied
  8734. EXPECT_TRUE(
  8735. pre_compression_body.empty()); // Pre-compression logger not called
  8736. EXPECT_EQ(
  8737. test_content,
  8738. post_compression_body); // Post-compression logger captures final content
  8739. }
  8740. TEST_F(ServerTest, LoggerSeesContentLength) {
  8741. size_t logged_content_length = 0;
  8742. std::string logged_content_length_header;
  8743. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8744. logged_content_length = res.content_length_;
  8745. logged_content_length_header = res.get_header_value("Content-Length");
  8746. });
  8747. auto res = cli_.Get("/nocompress");
  8748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8749. EXPECT_EQ(StatusCode::OK_200, res->status);
  8750. EXPECT_EQ(res->body.size(), logged_content_length);
  8751. EXPECT_EQ(std::to_string(logged_content_length),
  8752. logged_content_length_header);
  8753. }
  8754. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8755. const std::string test_content =
  8756. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8757. "3456789012345678901234567890";
  8758. std::string pre_compression_body;
  8759. bool pre_logger_called = false;
  8760. // Set only pre-compression logger
  8761. svr_.set_pre_compression_logger(
  8762. [&](const Request & /*req*/, const Response &res) {
  8763. pre_compression_body = res.body;
  8764. pre_logger_called = true;
  8765. });
  8766. Headers headers;
  8767. headers.emplace("Accept-Encoding", "gzip");
  8768. auto res = cli_.Get("/compress", headers);
  8769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8770. EXPECT_EQ(StatusCode::OK_200, res->status);
  8771. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8772. // Verify pre-compression logger was called
  8773. EXPECT_TRUE(pre_logger_called);
  8774. EXPECT_EQ(test_content, pre_compression_body);
  8775. }
  8776. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8777. {
  8778. // Test with Expect: 100-continue header - success case
  8779. // Server returns 100 Continue, client sends body, server returns 200 OK
  8780. Request req;
  8781. req.method = "POST";
  8782. req.path = "/post-large";
  8783. req.set_header("Expect", "100-continue");
  8784. req.body = LARGE_DATA;
  8785. Response res;
  8786. auto error = Error::Success;
  8787. cli_.set_keep_alive(true);
  8788. auto ret = cli_.send(req, res, error);
  8789. EXPECT_TRUE(ret);
  8790. EXPECT_EQ(StatusCode::OK_200, res.status);
  8791. EXPECT_EQ(LARGE_DATA, res.body);
  8792. }
  8793. {
  8794. // Test with Expect: 100-continue header - error case
  8795. // Client should not send the body when server returns an error
  8796. Request req;
  8797. req.method = "POST";
  8798. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8799. req.set_header("Expect", "100-continue");
  8800. req.body = LARGE_DATA;
  8801. Response res;
  8802. auto error = Error::Success;
  8803. auto start = std::chrono::high_resolution_clock::now();
  8804. cli_.set_keep_alive(true);
  8805. auto ret = cli_.send(req, res, error);
  8806. auto end = std::chrono::high_resolution_clock::now();
  8807. auto elapsed =
  8808. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8809. .count();
  8810. // With Expect: 100-continue, request completes successfully but with error
  8811. EXPECT_TRUE(ret);
  8812. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8813. EXPECT_EQ("close", res.get_header_value("Connection"));
  8814. EXPECT_FALSE(cli_.is_socket_open());
  8815. EXPECT_LE(elapsed, 2000);
  8816. }
  8817. {
  8818. // Send an extra GET request to ensure error recovery without hanging
  8819. Request req;
  8820. req.method = "GET";
  8821. req.path = "/hi";
  8822. auto start = std::chrono::high_resolution_clock::now();
  8823. auto res = cli_.send(req);
  8824. auto end = std::chrono::high_resolution_clock::now();
  8825. auto elapsed =
  8826. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8827. .count();
  8828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8829. EXPECT_EQ(StatusCode::OK_200, res->status);
  8830. EXPECT_EQ("Hello World!", res->body);
  8831. EXPECT_LE(elapsed, 500);
  8832. }
  8833. }
  8834. TEST(ZstdDecompressor, ChunkedDecompression) {
  8835. std::string data;
  8836. for (size_t i = 0; i < 32 * 1024; ++i) {
  8837. data.push_back(static_cast<char>('a' + i % 26));
  8838. }
  8839. std::string compressed_data;
  8840. {
  8841. httplib::detail::zstd_compressor compressor;
  8842. bool result = compressor.compress(
  8843. data.data(), data.size(),
  8844. /*last=*/true,
  8845. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8846. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8847. compressed_data_size);
  8848. return true;
  8849. });
  8850. ASSERT_TRUE(result);
  8851. }
  8852. std::string decompressed_data;
  8853. {
  8854. httplib::detail::zstd_decompressor decompressor;
  8855. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8856. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8857. size_t chunk_size = 130;
  8858. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8859. chunk_begin += chunk_size) {
  8860. size_t current_chunk_size =
  8861. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8862. bool result = decompressor.decompress(
  8863. compressed_data.data() + chunk_begin, current_chunk_size,
  8864. [&](const char *decompressed_data_chunk,
  8865. size_t decompressed_data_chunk_size) {
  8866. decompressed_data.insert(decompressed_data.size(),
  8867. decompressed_data_chunk,
  8868. decompressed_data_chunk_size);
  8869. return true;
  8870. });
  8871. ASSERT_TRUE(result);
  8872. }
  8873. }
  8874. ASSERT_EQ(data, decompressed_data);
  8875. }
  8876. TEST(ZstdDecompressor, Decompress) {
  8877. std::string original_text = "Compressed with ZSTD";
  8878. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8879. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8880. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8881. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8882. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8883. std::string decompressed_data;
  8884. {
  8885. httplib::detail::zstd_decompressor decompressor;
  8886. bool result = decompressor.decompress(
  8887. compressed_data.data(), compressed_data.size(),
  8888. [&](const char *decompressed_data_chunk,
  8889. size_t decompressed_data_chunk_size) {
  8890. decompressed_data.insert(decompressed_data.size(),
  8891. decompressed_data_chunk,
  8892. decompressed_data_chunk_size);
  8893. return true;
  8894. });
  8895. ASSERT_TRUE(result);
  8896. }
  8897. ASSERT_EQ(original_text, decompressed_data);
  8898. }
  8899. #endif
  8900. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8901. // separate chunks so that the server sees each part in its own read(). Used to
  8902. // place a read boundary at a specific offset of a request body.
  8903. static bool send_request_in_parts(time_t read_timeout_sec,
  8904. const std::vector<std::string> &parts,
  8905. std::string *resp = nullptr,
  8906. int port = PORT) {
  8907. auto error = Error::Success;
  8908. auto client_sock = detail::create_client_socket(
  8909. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8910. /*connection_timeout_sec=*/5, 0,
  8911. /*read_timeout_sec=*/5, 0,
  8912. /*write_timeout_sec=*/5, 0, std::string(), error);
  8913. if (client_sock == INVALID_SOCKET) { return false; }
  8914. auto ret = detail::process_client_socket(
  8915. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8916. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8917. for (size_t i = 0; i < parts.size(); i++) {
  8918. const auto &part = parts[i];
  8919. if (part.size() !=
  8920. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8921. return false;
  8922. }
  8923. if (i + 1 < parts.size()) {
  8924. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8925. }
  8926. }
  8927. char buf[512];
  8928. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8929. while (line_reader.getline()) {
  8930. if (resp) { *resp += line_reader.ptr(); }
  8931. }
  8932. return true;
  8933. });
  8934. detail::close_socket(client_sock);
  8935. return ret;
  8936. }
  8937. // Sends a raw request to a server listening at HOST:PORT.
  8938. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8939. std::string *resp = nullptr, int port = PORT) {
  8940. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8941. }
  8942. #ifdef CPPHTTPLIB_SSL_ENABLED
  8943. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8944. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8945. ASSERT_TRUE(svr.is_valid());
  8946. svr.set_read_timeout(1, 0);
  8947. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8948. auto se = detail::scope_exit([&] {
  8949. svr.stop();
  8950. t.join();
  8951. ASSERT_FALSE(svr.is_running());
  8952. });
  8953. svr.wait_until_ready();
  8954. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8955. // keeps each wait well within the read timeout. The server gives up a
  8956. // second in, so the bytes sent after that fail.
  8957. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8958. parts.resize(26, std::string(1, '\0'));
  8959. EXPECT_FALSE(send_request_in_parts(5, parts));
  8960. }
  8961. #endif
  8962. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8963. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  8964. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  8965. const std::vector<std::string> &parts,
  8966. std::string *resp = nullptr,
  8967. int port = PORT) {
  8968. auto error = Error::Success;
  8969. auto sock = detail::create_client_socket(
  8970. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8971. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  8972. /*write_timeout_sec=*/5, 0, std::string(), error);
  8973. if (sock == INVALID_SOCKET) { return false; }
  8974. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  8975. auto ctx = SSL_CTX_new(TLS_client_method());
  8976. auto ssl = SSL_new(ctx);
  8977. auto ssl_se = detail::scope_exit([&] {
  8978. SSL_free(ssl);
  8979. SSL_CTX_free(ctx);
  8980. });
  8981. SSL_set_fd(ssl, static_cast<int>(sock));
  8982. if (SSL_connect(ssl) != 1) { return false; }
  8983. for (size_t i = 0; i < parts.size(); i++) {
  8984. const auto &part = parts[i];
  8985. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  8986. static_cast<int>(part.size())) {
  8987. return false;
  8988. }
  8989. if (i + 1 < parts.size()) {
  8990. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8991. }
  8992. }
  8993. char buf[512];
  8994. int n;
  8995. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  8996. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  8997. }
  8998. return true;
  8999. }
  9000. #endif
  9001. // The request line, then a header value a byte at a time.
  9002. static std::vector<std::string> slow_request_head_parts() {
  9003. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9004. parts.resize(26, "a");
  9005. parts.emplace_back("\r\n\r\n");
  9006. return parts;
  9007. }
  9008. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9009. // within the one-second read timeout. The server gives up a second in, before
  9010. // the head is complete.
  9011. static void
  9012. expect_slow_request_head_dropped(Server &svr,
  9013. const std::function<std::string()> &send) {
  9014. std::atomic<bool> handled(false);
  9015. svr.Get("/", [&](const Request &, Response &res) {
  9016. handled = true;
  9017. res.set_content("ok", "text/plain");
  9018. });
  9019. svr.set_read_timeout(1, 0);
  9020. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9021. auto se = detail::scope_exit([&] {
  9022. svr.stop();
  9023. t.join();
  9024. ASSERT_FALSE(svr.is_running());
  9025. });
  9026. svr.wait_until_ready();
  9027. auto resp = send();
  9028. EXPECT_FALSE(handled);
  9029. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9030. }
  9031. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9032. Server svr;
  9033. expect_slow_request_head_dropped(svr, [] {
  9034. std::string resp;
  9035. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9036. return resp;
  9037. });
  9038. }
  9039. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9040. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9042. ASSERT_TRUE(svr.is_valid());
  9043. expect_slow_request_head_dropped(svr, [] {
  9044. std::string resp;
  9045. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9046. return resp;
  9047. });
  9048. }
  9049. #endif
  9050. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9051. Server svr;
  9052. std::string header_value;
  9053. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9054. header_value = req.get_header_value("foo");
  9055. res.set_content("ok", "text/plain");
  9056. });
  9057. thread t = thread([&] { svr.listen(HOST, PORT); });
  9058. auto se = detail::scope_exit([&] {
  9059. svr.stop();
  9060. t.join();
  9061. ASSERT_FALSE(svr.is_running());
  9062. });
  9063. svr.wait_until_ready();
  9064. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9065. // like characters are not treated the same - use vertical tab and escape.
  9066. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9067. "foo: \t \v bar \x1B\t \r\n"
  9068. "Connection: close\r\n"
  9069. "\r\n";
  9070. std::string res;
  9071. ASSERT_TRUE(send_request(5, req, &res));
  9072. EXPECT_EQ(header_value, "");
  9073. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9074. }
  9075. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9076. Server svr;
  9077. std::string received;
  9078. svr.Get("/order", [&](const Request &req, Response &res) {
  9079. received = entries_to_string(req.headers);
  9080. res.set_content("ok", "text/plain");
  9081. });
  9082. auto port = svr.bind_to_any_port(HOST);
  9083. thread t = thread([&] { svr.listen_after_bind(); });
  9084. auto se = detail::scope_exit([&] {
  9085. svr.stop();
  9086. t.join();
  9087. ASSERT_FALSE(svr.is_running());
  9088. });
  9089. svr.wait_until_ready();
  9090. const std::string req = "GET /order HTTP/1.1\r\n"
  9091. "Host: localhost\r\n"
  9092. "X-First: 1\r\n"
  9093. "X-Dup: a\r\n"
  9094. "X-Second: 2\r\n"
  9095. "X-Dup: b\r\n"
  9096. "Connection: close\r\n"
  9097. "\r\n";
  9098. std::string res;
  9099. ASSERT_TRUE(send_request(5, req, &res, port));
  9100. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9101. EXPECT_EQ(
  9102. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9103. received);
  9104. }
  9105. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9106. Server svr;
  9107. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9108. res.set_header("Set-Cookie", "first=1");
  9109. res.set_header("X-Between", "y");
  9110. res.set_header("Set-Cookie", "second=2");
  9111. res.set_content("ok", "text/plain");
  9112. });
  9113. auto port = svr.bind_to_any_port(HOST);
  9114. thread t = thread([&] { svr.listen_after_bind(); });
  9115. auto se = detail::scope_exit([&] {
  9116. svr.stop();
  9117. t.join();
  9118. ASSERT_FALSE(svr.is_running());
  9119. });
  9120. svr.wait_until_ready();
  9121. Client cli(HOST, port);
  9122. auto res = cli.Get("/cookies");
  9123. ASSERT_TRUE(res);
  9124. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9125. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9126. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9127. }
  9128. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9129. Server svr;
  9130. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9131. auto i = new int(0);
  9132. res.set_header("Trailer", "X-Safe, X-Reflected");
  9133. res.set_chunked_content_provider(
  9134. "text/plain",
  9135. [i](size_t /*offset*/, DataSink &sink) {
  9136. if (*i == 0) {
  9137. sink.os << "body";
  9138. } else {
  9139. Headers trailer;
  9140. // A valid trailer that must survive.
  9141. trailer.emplace("X-Safe", "safe");
  9142. // Attacker-controlled value carrying CR/LF (response splitting).
  9143. trailer.emplace("X-Reflected",
  9144. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9145. // Attacker-controlled name carrying CR/LF.
  9146. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9147. sink.done_with_trailer(trailer);
  9148. }
  9149. (*i)++;
  9150. return true;
  9151. },
  9152. [i](bool /*success*/) { delete i; });
  9153. });
  9154. thread t = thread([&] { svr.listen(HOST, PORT); });
  9155. auto se = detail::scope_exit([&] {
  9156. svr.stop();
  9157. t.join();
  9158. ASSERT_FALSE(svr.is_running());
  9159. });
  9160. svr.wait_until_ready();
  9161. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9162. "Host: " + HOST +
  9163. "\r\n"
  9164. "Connection: close\r\n"
  9165. "\r\n";
  9166. std::string res;
  9167. ASSERT_TRUE(send_request(5, req, &res));
  9168. // The injected fields must not appear anywhere in the raw response.
  9169. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9170. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9171. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9172. // Invalid trailers are dropped entirely, matching set_header().
  9173. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9174. // The valid trailer still passes through.
  9175. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9176. }
  9177. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9178. Server svr;
  9179. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9180. // res.headers is a public field an application can populate directly,
  9181. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9182. // A valid header that must survive.
  9183. res.headers.emplace("X-Safe", "safe");
  9184. // Attacker-controlled value carrying CR/LF (response splitting).
  9185. res.headers.emplace("X-Reflected",
  9186. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9187. // Attacker-controlled name carrying CR/LF.
  9188. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9189. res.set_content("body", "text/plain");
  9190. });
  9191. thread t = thread([&] { svr.listen(HOST, PORT); });
  9192. auto se = detail::scope_exit([&] {
  9193. svr.stop();
  9194. t.join();
  9195. ASSERT_FALSE(svr.is_running());
  9196. });
  9197. svr.wait_until_ready();
  9198. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9199. "Host: " + HOST +
  9200. "\r\n"
  9201. "Connection: close\r\n"
  9202. "\r\n";
  9203. std::string res;
  9204. ASSERT_TRUE(send_request(5, req, &res));
  9205. // The injected fields must not appear anywhere in the raw response.
  9206. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9207. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9208. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9209. // Invalid headers are dropped entirely, matching set_header().
  9210. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9211. // The valid header still passes through.
  9212. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9213. }
  9214. // Forward declaration: in split builds split.py strips `inline` and moves the
  9215. // definition into httplib.cc, so detail::write_request_line is not visible from
  9216. // the public httplib.h. Re-declaring it here lets the tests link against the
  9217. // symbol in both header-only and split builds.
  9218. namespace httplib {
  9219. namespace detail {
  9220. ssize_t write_request_line(Stream &strm, const std::string &method,
  9221. const std::string &path);
  9222. } // namespace detail
  9223. } // namespace httplib
  9224. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9225. // A well-formed target is written verbatim.
  9226. {
  9227. detail::BufferStream strm;
  9228. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9229. EXPECT_GT(n, 0);
  9230. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9231. }
  9232. // A target carrying CR/LF, SP or other control octets must be rejected
  9233. // before anything reaches the wire, otherwise it splits the request line and
  9234. // injects a header or a whole request.
  9235. const std::string evil_targets[] = {
  9236. "/a\r\nInjected: pwned",
  9237. "/a\rInjected",
  9238. "/a\nInjected",
  9239. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9240. "/a b",
  9241. "/a\tb",
  9242. "/a\x7f",
  9243. };
  9244. for (const auto &evil : evil_targets) {
  9245. detail::BufferStream strm;
  9246. auto n = detail::write_request_line(strm, "GET", evil);
  9247. EXPECT_LT(n, 0);
  9248. EXPECT_TRUE(strm.get_buffer().empty());
  9249. }
  9250. }
  9251. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9252. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9253. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9254. // target reaches write_request. The client must fail cleanly with
  9255. // Error::Write instead of putting a request-line-less, header-injecting
  9256. // request on the wire.
  9257. Server svr;
  9258. svr.Get("/a", [](const Request &, Response &res) {
  9259. res.set_content("ok", "text/plain");
  9260. });
  9261. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9262. auto se = detail::scope_exit([&] {
  9263. svr.stop();
  9264. thread.join();
  9265. ASSERT_FALSE(svr.is_running());
  9266. });
  9267. svr.wait_until_ready();
  9268. {
  9269. Client cli(HOST, PORT);
  9270. cli.set_path_encode(false);
  9271. // The request is rejected before anything is written, so the connection
  9272. // stays silent and the subsequent response read would otherwise block for
  9273. // the full default read timeout. Shorten it -- the assertion is on the
  9274. // error, not the timeout.
  9275. cli.set_read_timeout(1, 0);
  9276. auto res = cli.Get("/a\r\nInjected: pwned");
  9277. EXPECT_FALSE(res);
  9278. EXPECT_EQ(Error::Write, res.error());
  9279. }
  9280. }
  9281. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9282. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9283. // including extension methods.
  9284. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9285. for (const auto &method : good_methods) {
  9286. detail::BufferStream strm;
  9287. auto n = detail::write_request_line(strm, method, "/");
  9288. EXPECT_GT(n, 0);
  9289. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9290. }
  9291. // A method carrying CR/LF would split the request line and smuggle a whole
  9292. // request ahead of the real one. A space or an empty method corrupts the
  9293. // request line. All must be rejected before anything reaches the wire.
  9294. const std::string evil_methods[] = {
  9295. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9296. "GET\r\nInjected: pwned",
  9297. "GET\r",
  9298. "GET\n",
  9299. "GE T",
  9300. "",
  9301. };
  9302. for (const auto &evil : evil_methods) {
  9303. detail::BufferStream strm;
  9304. auto n = detail::write_request_line(strm, evil, "/");
  9305. EXPECT_LT(n, 0);
  9306. EXPECT_TRUE(strm.get_buffer().empty());
  9307. }
  9308. }
  9309. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9310. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9311. // through Client::send must fail with Error::Write and no request, neither
  9312. // the smuggled one nor the real one, may reach the server.
  9313. Server svr;
  9314. std::atomic<int> request_count(0);
  9315. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9316. request_count++;
  9317. res.status = StatusCode::OK_200;
  9318. return Server::HandlerResponse::Handled;
  9319. });
  9320. auto port = svr.bind_to_any_port(HOST);
  9321. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9322. auto se = detail::scope_exit([&] {
  9323. svr.stop();
  9324. thread.join();
  9325. ASSERT_FALSE(svr.is_running());
  9326. });
  9327. svr.wait_until_ready();
  9328. {
  9329. Client cli(HOST, port);
  9330. const std::string evil_methods[] = {
  9331. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9332. "GE T",
  9333. "",
  9334. };
  9335. for (const auto &evil : evil_methods) {
  9336. Request req;
  9337. req.method = evil;
  9338. req.path = "/";
  9339. auto res = cli.send(req);
  9340. EXPECT_FALSE(res);
  9341. EXPECT_EQ(Error::Write, res.error());
  9342. }
  9343. auto handle =
  9344. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9345. EXPECT_FALSE(handle.is_valid());
  9346. EXPECT_EQ(Error::Write, handle.error);
  9347. // A valid request on the same client still goes through.
  9348. auto res = cli.Get("/");
  9349. ASSERT_TRUE(res);
  9350. EXPECT_EQ(StatusCode::OK_200, res->status);
  9351. }
  9352. EXPECT_EQ(1, request_count.load());
  9353. }
  9354. // Sends a raw request and verifies that there isn't a crash or exception.
  9355. static void test_raw_request(const std::string &req,
  9356. std::string *out = nullptr) {
  9357. Server svr;
  9358. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9359. res.set_content("ok", "text/plain");
  9360. });
  9361. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9362. res.set_content("ok", "text/plain");
  9363. });
  9364. svr.Get("/header_field_value_check",
  9365. [&](const Request & /*req*/, Response &res) {
  9366. res.set_content("ok", "text/plain");
  9367. });
  9368. svr.CustomRoute("PROPFIND", "/dav",
  9369. [&](const Request & /*req*/, Response &res) {
  9370. res.status = StatusCode::MultiStatus_207;
  9371. });
  9372. // Server read timeout must be longer than the client read timeout for the
  9373. // bug to reproduce, probably to force the server to process a request
  9374. // without a trailing blank line.
  9375. const time_t client_read_timeout_sec = 1;
  9376. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9377. bool listen_thread_ok = false;
  9378. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9379. auto se = detail::scope_exit([&] {
  9380. svr.stop();
  9381. t.join();
  9382. ASSERT_FALSE(svr.is_running());
  9383. EXPECT_TRUE(listen_thread_ok);
  9384. });
  9385. svr.wait_until_ready();
  9386. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9387. }
  9388. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9389. // A certain header line causes an exception if the header property is parsed
  9390. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9391. test_raw_request(
  9392. "GET /hi HTTP/1.1\r\n"
  9393. " : "
  9394. " "
  9395. " ");
  9396. }
  9397. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9398. // A certain header line causes an exception if the header property *name* is
  9399. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9400. // greedy matcher and requires backtracking when there are a lot of ":"
  9401. // characters.
  9402. // This occurs with libc++ but not libstdc++.
  9403. test_raw_request(
  9404. "GET /hi HTTP/1.1\r\n"
  9405. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9406. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9407. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9408. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9409. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9410. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9411. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9412. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9413. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9414. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9415. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9416. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9417. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9418. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9419. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9420. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9421. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9422. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9423. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9424. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9425. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9426. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9427. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9428. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9429. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9430. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9431. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9432. "&&&%%%");
  9433. }
  9434. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9435. // Make sure this doesn't crash the server.
  9436. // In a previous version of the header line regex, the "\r" rendered the line
  9437. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9438. // a new position where the leading white space ended and the field value
  9439. // began.
  9440. // The crash occurs with libc++ but not libstdc++.
  9441. test_raw_request("GET /hi HTTP/1.1\r\n"
  9442. "a:" +
  9443. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9444. "\r\n"
  9445. "\r\n");
  9446. }
  9447. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9448. const char *rejected[] = {
  9449. // RFC 9112 §3: one SP between the parts, and nothing else
  9450. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9451. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9452. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9453. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9454. // A request-target has no fragment
  9455. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9456. // An HTTP/1.1 request needs a Host
  9457. "GET /hi HTTP/1.1\r\n\r\n",
  9458. };
  9459. for (auto request : rejected) {
  9460. std::string out;
  9461. test_raw_request(request, &out);
  9462. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9463. }
  9464. std::string out;
  9465. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9466. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9467. }
  9468. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9469. // RFC 9112 §6.1
  9470. const char *requests[] = {
  9471. "PUT /put_hi HTTP/1.1\r\n"
  9472. "Host: localhost\r\n"
  9473. "Content-Length: 0\r\n"
  9474. "Transfer-Encoding: chunked\r\n"
  9475. "\r\n"
  9476. "0\r\n\r\n",
  9477. "PUT /put_hi HTTP/1.0\r\n"
  9478. "Connection: keep-alive\r\n"
  9479. "Transfer-Encoding: chunked\r\n"
  9480. "\r\n"
  9481. "0\r\n\r\n",
  9482. };
  9483. for (auto request : requests) {
  9484. std::string out;
  9485. test_raw_request(request, &out);
  9486. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9487. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9488. }
  9489. }
  9490. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9491. std::string out;
  9492. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9493. "Content-Type: text/plain\r\n"
  9494. "Transfer-Encoding: chunked\r\n"
  9495. "\r\n"
  9496. "nothex\r\n",
  9497. &out);
  9498. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9499. }
  9500. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9501. std::string out;
  9502. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9503. "Content-Type: text/plain\r\n"
  9504. "Transfer-Encoding: chunked\r\n"
  9505. "\r\n"
  9506. "3\r\n"
  9507. "xyz\r\n"
  9508. "NaN\r\n",
  9509. &out);
  9510. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9511. }
  9512. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9513. std::string out;
  9514. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9515. "Content-Type: text/plain\r\n"
  9516. "Transfer-Encoding: chunked\r\n"
  9517. "\r\n"
  9518. // Length is too large for 64 bits.
  9519. "1ffffffffffffffff\r\n"
  9520. "xyz\r\n",
  9521. &out);
  9522. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9523. }
  9524. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9525. test_raw_request("GET /hi HTTP/1.1\r\n"
  9526. "Content-Type: text/plain\r\n\r");
  9527. }
  9528. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9529. std::string out;
  9530. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9531. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9532. }
  9533. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9534. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9535. std::string out;
  9536. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9537. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9538. }
  9539. }
  9540. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9541. std::string out;
  9542. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9543. "Host: localhost\r\n"
  9544. "Connection: close\r\n\r\n",
  9545. &out);
  9546. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9547. }
  9548. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9549. Server svr;
  9550. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9551. EXPECT_TRUE(!req.remote_addr.empty());
  9552. });
  9553. thread t = thread([&] { svr.listen(HOST, PORT); });
  9554. auto se = detail::scope_exit([&] {
  9555. svr.stop();
  9556. t.join();
  9557. ASSERT_FALSE(svr.is_running());
  9558. });
  9559. svr.wait_until_ready();
  9560. // Send an invalid request line to trigger Bad Request
  9561. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9562. std::string out;
  9563. ASSERT_TRUE(send_request(5, bad_req, &out));
  9564. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9565. }
  9566. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9567. // answered right away rather than blocking on a read that waits for EOF.
  9568. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9569. std::string out;
  9570. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9571. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9572. }
  9573. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9574. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9575. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9576. for (const auto *method : methods) {
  9577. Server svr;
  9578. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9579. EXPECT_FALSE(svr.is_valid()) << method;
  9580. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9581. }
  9582. }
  9583. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9584. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9585. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9586. for (const auto *method : methods) {
  9587. Server svr;
  9588. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9589. EXPECT_FALSE(svr.is_valid()) << method;
  9590. }
  9591. }
  9592. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9593. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9594. "COPY", "MOVE", "LOCK",
  9595. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9596. Server svr;
  9597. for (const auto *method : methods) {
  9598. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9599. }
  9600. EXPECT_TRUE(svr.is_valid());
  9601. }
  9602. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9603. Server svr;
  9604. svr.CustomRoute("POST", "/x",
  9605. [](const Request &, Response &, const ContentReader &) {});
  9606. EXPECT_FALSE(svr.is_valid());
  9607. }
  9608. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9609. Server svr;
  9610. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9611. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9612. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9613. EXPECT_FALSE(svr.is_valid());
  9614. }
  9615. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9616. Server svr;
  9617. auto captured = Error::Success;
  9618. svr.set_error_logger(
  9619. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9620. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9621. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9622. }
  9623. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9624. std::string out;
  9625. std::string request(
  9626. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9627. test_raw_request(request, &out);
  9628. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9629. }
  9630. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9631. std::string out;
  9632. std::string request(
  9633. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9634. test_raw_request(request, &out);
  9635. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9636. }
  9637. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9638. std::string out;
  9639. std::string request(
  9640. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9641. test_raw_request(request, &out);
  9642. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9643. }
  9644. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9645. std::string out;
  9646. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9647. "Host: localhost\r\n"
  9648. "Test: \r\n\r\n",
  9649. &out);
  9650. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9651. }
  9652. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9653. Server svr;
  9654. std::string x_custom;
  9655. std::string cookie;
  9656. std::string xff;
  9657. std::string x_unicode;
  9658. std::string x_iis;
  9659. svr.Get("/check", [&](const Request &req, Response &res) {
  9660. x_custom = req.get_header_value("X-Custom");
  9661. cookie = req.get_header_value("Cookie");
  9662. xff = req.get_header_value("X-Forwarded-For");
  9663. x_unicode = req.get_header_value("X-Unicode");
  9664. x_iis = req.get_header_value("X-IIS");
  9665. res.set_content("ok", "text/plain");
  9666. });
  9667. thread t = thread([&] { svr.listen(HOST, PORT); });
  9668. auto se = detail::scope_exit([&] {
  9669. svr.stop();
  9670. t.join();
  9671. ASSERT_FALSE(svr.is_running());
  9672. });
  9673. svr.wait_until_ready();
  9674. const std::string req = "GET /check HTTP/1.1\r\n"
  9675. "Host: localhost\r\n"
  9676. "X-Custom: a%0D%0AInjected: b\r\n"
  9677. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9678. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9679. "X-Unicode: %E3%81%82\r\n"
  9680. "X-IIS: %u00E9\r\n"
  9681. "Connection: close\r\n"
  9682. "\r\n";
  9683. std::string res;
  9684. ASSERT_TRUE(send_request(5, req, &res));
  9685. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9686. // Every value must be returned verbatim (wire form), with no decoding.
  9687. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9688. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9689. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9690. EXPECT_EQ("%E3%81%82", x_unicode);
  9691. EXPECT_EQ("%u00E9", x_iis);
  9692. }
  9693. // Applications that previously relied on automatic percent-decoding can
  9694. // reproduce the old behavior by explicitly calling decode_path_component()
  9695. // or, for RFC 3986 conformance, decode_uri_component().
  9696. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9697. Server svr;
  9698. std::string decoded;
  9699. svr.Get("/check", [&](const Request &req, Response &res) {
  9700. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9701. res.set_content("ok", "text/plain");
  9702. });
  9703. thread t = thread([&] { svr.listen(HOST, PORT); });
  9704. auto se = detail::scope_exit([&] {
  9705. svr.stop();
  9706. t.join();
  9707. ASSERT_FALSE(svr.is_running());
  9708. });
  9709. svr.wait_until_ready();
  9710. const std::string req = "GET /check HTTP/1.1\r\n"
  9711. "Host: localhost\r\n"
  9712. "X-Custom: hello%20world\r\n"
  9713. "Connection: close\r\n"
  9714. "\r\n";
  9715. std::string res;
  9716. ASSERT_TRUE(send_request(5, req, &res));
  9717. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9718. EXPECT_EQ("hello world", decoded);
  9719. }
  9720. // Regression test for #2033. Browsers send Referer values that include
  9721. // percent-encoded characters such as %0A inside the URL. Decoding the
  9722. // header value would either trip the post-decode CR/LF/NUL guard (the
  9723. // original bug, returning 400) or, after that guard was relaxed, silently
  9724. // store a literal LF — both unacceptable. The wire form must round-trip.
  9725. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9726. Server svr;
  9727. std::string referer;
  9728. svr.Get("/check", [&](const Request &req, Response &res) {
  9729. referer = req.get_header_value("Referer");
  9730. res.set_content("ok", "text/plain");
  9731. });
  9732. thread t = thread([&] { svr.listen(HOST, PORT); });
  9733. auto se = detail::scope_exit([&] {
  9734. svr.stop();
  9735. t.join();
  9736. ASSERT_FALSE(svr.is_running());
  9737. });
  9738. svr.wait_until_ready();
  9739. const std::string req = "GET /check HTTP/1.1\r\n"
  9740. "Host: localhost\r\n"
  9741. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9742. "Connection: close\r\n"
  9743. "\r\n";
  9744. std::string res;
  9745. ASSERT_TRUE(send_request(5, req, &res));
  9746. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9747. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9748. }
  9749. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9750. Server svr;
  9751. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9752. res.set_header("Cache-Control", "no-cache");
  9753. res.set_chunked_content_provider(
  9754. "text/event-stream", [](size_t offset, DataSink &sink) {
  9755. std::string s = "data:";
  9756. s += std::to_string(offset);
  9757. s += "\n\n";
  9758. auto ret = sink.write(s.data(), s.size());
  9759. EXPECT_TRUE(ret);
  9760. std::this_thread::sleep_for(std::chrono::seconds(1));
  9761. return true;
  9762. });
  9763. });
  9764. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9765. svr.wait_until_ready();
  9766. Client client(HOST, PORT);
  9767. const Headers headers = {{"Accept", "text/event-stream"}};
  9768. auto get_thread = std::thread([&client, &headers]() {
  9769. auto res = client.Get(
  9770. "/events", headers,
  9771. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9772. });
  9773. auto se = detail::scope_exit([&] {
  9774. svr.stop();
  9775. get_thread.join();
  9776. listen_thread.join();
  9777. ASSERT_FALSE(svr.is_running());
  9778. });
  9779. // Give GET time to get a few messages.
  9780. std::this_thread::sleep_for(std::chrono::seconds(2));
  9781. }
  9782. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9783. httplib::Server svr;
  9784. svr.Post("/hi",
  9785. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9786. res.status = StatusCode::OK_200;
  9787. });
  9788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9789. svr.wait_until_ready();
  9790. Client cli(HOST, PORT);
  9791. auto res = cli.Post("/hi", "data", "text/plain");
  9792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9793. EXPECT_EQ(StatusCode::OK_200, res->status);
  9794. svr.stop();
  9795. thread.join();
  9796. ASSERT_FALSE(svr.is_running());
  9797. res = cli.Post("/hi", "data", "text/plain");
  9798. ASSERT_FALSE(res);
  9799. }
  9800. TEST(ServerStopTest, ListenFailure) {
  9801. Server svr;
  9802. auto t = thread([&]() {
  9803. auto ret = svr.listen("????", PORT);
  9804. EXPECT_FALSE(ret);
  9805. });
  9806. svr.wait_until_ready();
  9807. svr.stop();
  9808. t.join();
  9809. }
  9810. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9811. TEST(ServerStopTest, Decommision) {
  9812. Server svr;
  9813. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9814. for (int i = 0; i < 4; i++) {
  9815. auto is_even = !(i % 2);
  9816. std::thread t{[&] {
  9817. try {
  9818. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9819. if (is_even) {
  9820. throw std::runtime_error("Some thing that happens to go wrong.");
  9821. }
  9822. svr.listen(HOST, PORT);
  9823. } catch (...) { svr.decommission(); }
  9824. }};
  9825. svr.wait_until_ready();
  9826. // Server is up
  9827. {
  9828. Client cli(HOST, PORT);
  9829. auto res = cli.Get("/hi");
  9830. if (is_even) {
  9831. EXPECT_FALSE(res);
  9832. } else {
  9833. EXPECT_TRUE(res);
  9834. EXPECT_EQ("hi...", res->body);
  9835. }
  9836. }
  9837. svr.stop();
  9838. t.join();
  9839. // Server is down...
  9840. {
  9841. Client cli(HOST, PORT);
  9842. auto res = cli.Get("/hi");
  9843. EXPECT_FALSE(res);
  9844. }
  9845. }
  9846. }
  9847. #endif
  9848. // Helper function for string body upload progress tests
  9849. template <typename SetupHandler, typename ClientCall>
  9850. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9851. ClientCall &&client_call,
  9852. const string &body) {
  9853. Server svr;
  9854. setup_handler(svr);
  9855. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9856. auto se = detail::scope_exit([&] {
  9857. svr.stop();
  9858. t.join();
  9859. });
  9860. svr.wait_until_ready();
  9861. Client cli(HOST, PORT);
  9862. vector<uint64_t> progress_values;
  9863. bool progress_called = false;
  9864. auto res =
  9865. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9866. progress_values.push_back(current);
  9867. progress_called = true;
  9868. return true;
  9869. });
  9870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9871. EXPECT_EQ(200, res->status);
  9872. EXPECT_TRUE(progress_called);
  9873. }
  9874. TEST(UploadProgressTest, PostStringBodyBasic) {
  9875. TestStringBodyUploadProgress(
  9876. [](Server &svr) {
  9877. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9878. res.set_content("received", "text/plain");
  9879. });
  9880. },
  9881. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9882. return cli.Post("/test", body, "text/plain", progress_callback);
  9883. },
  9884. "test data for upload progress");
  9885. }
  9886. TEST(UploadProgressTest, PutStringBodyBasic) {
  9887. TestStringBodyUploadProgress(
  9888. [](Server &svr) {
  9889. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9890. res.set_content("put received", "text/plain");
  9891. });
  9892. },
  9893. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9894. return cli.Put("/test", body, "text/plain", progress_callback);
  9895. },
  9896. "put test data for upload progress");
  9897. }
  9898. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9899. TestStringBodyUploadProgress(
  9900. [](Server &svr) {
  9901. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9902. res.set_content("patch received", "text/plain");
  9903. });
  9904. },
  9905. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9906. return cli.Patch("/test", body, "text/plain", progress_callback);
  9907. },
  9908. "patch test data for upload progress");
  9909. }
  9910. // Helper function for content provider upload progress tests
  9911. template <typename SetupHandler, typename ClientCall>
  9912. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9913. ClientCall &&client_call) {
  9914. Server svr;
  9915. setup_handler(svr);
  9916. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9917. auto se = detail::scope_exit([&] {
  9918. svr.stop();
  9919. t.join();
  9920. });
  9921. svr.wait_until_ready();
  9922. Client cli(HOST, PORT);
  9923. vector<uint64_t> progress_values;
  9924. auto res =
  9925. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9926. progress_values.push_back(current);
  9927. return true;
  9928. });
  9929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9930. EXPECT_EQ(200, res->status);
  9931. EXPECT_FALSE(progress_values.empty());
  9932. }
  9933. TEST(UploadProgressTest, PostContentProviderProgress) {
  9934. TestContentProviderUploadProgress(
  9935. [](Server &svr) {
  9936. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9937. res.set_content("provider received", "text/plain");
  9938. });
  9939. },
  9940. [](Client &cli, UploadProgress progress_callback) {
  9941. return cli.Post(
  9942. "/test", 9,
  9943. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9944. sink.os << "test data";
  9945. return true;
  9946. },
  9947. "text/plain", progress_callback);
  9948. });
  9949. }
  9950. // Helper function for multipart upload progress tests
  9951. template <typename SetupHandler, typename ClientCall>
  9952. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9953. ClientCall &&client_call,
  9954. const string &endpoint) {
  9955. Server svr;
  9956. setup_handler(svr);
  9957. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9958. auto se = detail::scope_exit([&] {
  9959. svr.stop();
  9960. t.join();
  9961. });
  9962. svr.wait_until_ready();
  9963. Client cli(HOST, PORT);
  9964. vector<uint64_t> progress_values;
  9965. UploadFormDataItems items = {
  9966. {"field1", "value1", "", ""},
  9967. {"field2", "longer value for progress tracking test", "", ""},
  9968. {"file1", "file content data for upload progress", "test.txt",
  9969. "text/plain"}};
  9970. auto res = client_call(cli, endpoint, items,
  9971. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9972. progress_values.push_back(current);
  9973. return true;
  9974. });
  9975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9976. EXPECT_EQ(200, res->status);
  9977. EXPECT_FALSE(progress_values.empty());
  9978. }
  9979. TEST(UploadProgressTest, PostMultipartProgress) {
  9980. TestMultipartUploadProgress(
  9981. [](Server &svr) {
  9982. svr.Post("/multipart", [](const Request &req, Response &res) {
  9983. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9984. res.set_content("multipart received", "text/plain");
  9985. });
  9986. },
  9987. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9988. UploadProgress progress_callback) {
  9989. return cli.Post(endpoint, items, progress_callback);
  9990. },
  9991. "/multipart");
  9992. }
  9993. // Helper function for basic download progress tests
  9994. template <typename SetupHandler, typename ClientCall>
  9995. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9996. ClientCall &&client_call, const string &endpoint,
  9997. size_t expected_content_size) {
  9998. Server svr;
  9999. setup_handler(svr);
  10000. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10001. auto se = detail::scope_exit([&] {
  10002. svr.stop();
  10003. t.join();
  10004. });
  10005. svr.wait_until_ready();
  10006. Client cli(HOST, PORT);
  10007. vector<uint64_t> progress_values;
  10008. auto res = client_call(cli, endpoint,
  10009. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10010. progress_values.push_back(current);
  10011. return true;
  10012. });
  10013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10014. EXPECT_EQ(200, res->status);
  10015. EXPECT_FALSE(progress_values.empty());
  10016. EXPECT_EQ(expected_content_size, res->body.size());
  10017. }
  10018. TEST(DownloadProgressTest, GetBasic) {
  10019. TestBasicDownloadProgress(
  10020. [](Server &svr) {
  10021. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10022. string content(1000, 'D');
  10023. res.set_content(content, "text/plain");
  10024. });
  10025. },
  10026. [](Client &cli, const string &endpoint,
  10027. DownloadProgress progress_callback) {
  10028. return cli.Get(endpoint, progress_callback);
  10029. },
  10030. "/download", 1000u);
  10031. }
  10032. // Helper function for content receiver download progress tests
  10033. template <typename SetupHandler, typename ClientCall>
  10034. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10035. ClientCall &&client_call,
  10036. const string &endpoint,
  10037. size_t expected_content_size) {
  10038. Server svr;
  10039. setup_handler(svr);
  10040. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10041. auto se = detail::scope_exit([&] {
  10042. svr.stop();
  10043. t.join();
  10044. });
  10045. svr.wait_until_ready();
  10046. Client cli(HOST, PORT);
  10047. vector<uint64_t> progress_values;
  10048. string received_body;
  10049. auto res = client_call(
  10050. cli, endpoint,
  10051. [&](const char *data, size_t data_length) -> bool {
  10052. received_body.append(data, data_length);
  10053. return true;
  10054. },
  10055. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10056. progress_values.push_back(current);
  10057. return true;
  10058. });
  10059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10060. EXPECT_EQ(200, res->status);
  10061. EXPECT_FALSE(progress_values.empty());
  10062. EXPECT_EQ(expected_content_size, received_body.size());
  10063. EXPECT_TRUE(res->body.empty());
  10064. }
  10065. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10066. TestContentReceiverDownloadProgress(
  10067. [](Server &svr) {
  10068. svr.Get("/download-receiver",
  10069. [](const Request & /*req*/, Response &res) {
  10070. string content(2000, 'R');
  10071. res.set_content(content, "text/plain");
  10072. });
  10073. },
  10074. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10075. DownloadProgress progress_callback) {
  10076. return cli.Get(endpoint, content_receiver, progress_callback);
  10077. },
  10078. "/download-receiver", 2000u);
  10079. }
  10080. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10081. // A provider reaching a pass with nothing to hand over - an empty buffer
  10082. // popped off a queue, say - must not be taken to mean the body is finished.
  10083. // It used to end the loop with the terminating chunk unwritten while the
  10084. // server still considered the response complete, so the peer waited for an
  10085. // end that never arrived.
  10086. Server svr;
  10087. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10088. auto step = std::make_shared<int>(0);
  10089. res.set_chunked_content_provider("text/plain",
  10090. [step](size_t /*offset*/, DataSink &sink) {
  10091. switch ((*step)++) {
  10092. case 0: sink.write("", 0); break;
  10093. case 1: sink.write("hello", 5); break;
  10094. default: sink.done(); break;
  10095. }
  10096. return true;
  10097. });
  10098. });
  10099. auto port = svr.bind_to_any_port(HOST);
  10100. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10101. auto listen_se = detail::scope_exit([&] {
  10102. svr.stop();
  10103. listen_thread.join();
  10104. ASSERT_FALSE(svr.is_running());
  10105. });
  10106. svr.wait_until_ready();
  10107. Client cli(HOST, port);
  10108. // Without the fix the body is never terminated, so bound the wait rather
  10109. // than letting the test hang on the default read timeout.
  10110. cli.set_read_timeout(5, 0);
  10111. auto res = cli.Get("/stream");
  10112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10113. EXPECT_EQ(StatusCode::OK_200, res->status);
  10114. EXPECT_EQ("hello", res->body);
  10115. }
  10116. TEST(StreamingTest, NoContentLengthStreaming) {
  10117. Server svr;
  10118. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10119. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10120. if (offset < 6) {
  10121. sink.os << (offset < 3 ? "a" : "b");
  10122. } else {
  10123. sink.done();
  10124. }
  10125. return true;
  10126. });
  10127. });
  10128. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10129. auto listen_se = detail::scope_exit([&] {
  10130. svr.stop();
  10131. listen_thread.join();
  10132. ASSERT_FALSE(svr.is_running());
  10133. });
  10134. svr.wait_until_ready();
  10135. Client client(HOST, PORT);
  10136. auto get_thread = std::thread([&client]() {
  10137. std::string s;
  10138. auto res =
  10139. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10140. s += std::string(data, len);
  10141. return true;
  10142. });
  10143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10144. EXPECT_EQ(StatusCode::OK_200, res->status);
  10145. EXPECT_EQ("aaabbb", s);
  10146. });
  10147. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10148. // Give GET time to get a few messages.
  10149. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10150. }
  10151. TEST(MountTest, Unmount) {
  10152. Server svr;
  10153. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10154. auto se = detail::scope_exit([&] {
  10155. svr.stop();
  10156. listen_thread.join();
  10157. ASSERT_FALSE(svr.is_running());
  10158. });
  10159. svr.wait_until_ready();
  10160. Client cli("localhost", PORT);
  10161. svr.set_mount_point("/mount2", "./www2");
  10162. auto res = cli.Get("/");
  10163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10164. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10165. res = cli.Get("/mount2/dir/test.html");
  10166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10167. EXPECT_EQ(StatusCode::OK_200, res->status);
  10168. svr.set_mount_point("/", "./www");
  10169. res = cli.Get("/dir/");
  10170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10171. EXPECT_EQ(StatusCode::OK_200, res->status);
  10172. svr.remove_mount_point("/");
  10173. res = cli.Get("/dir/");
  10174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10175. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10176. svr.remove_mount_point("/mount2");
  10177. res = cli.Get("/mount2/dir/test.html");
  10178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10179. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10180. }
  10181. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10182. Server svr;
  10183. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10184. svr.Get("/api/hello", [](const Request &, Response &res) {
  10185. res.set_content("api", "text/plain");
  10186. });
  10187. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10188. auto se = detail::scope_exit([&] {
  10189. svr.stop();
  10190. listen_thread.join();
  10191. ASSERT_FALSE(svr.is_running());
  10192. });
  10193. svr.wait_until_ready();
  10194. Client cli(HOST, PORT);
  10195. auto res = cli.Get("/dir/test.html");
  10196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10197. EXPECT_EQ(StatusCode::OK_200, res->status);
  10198. res = cli.Get("/api/hello");
  10199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10200. EXPECT_EQ(StatusCode::OK_200, res->status);
  10201. EXPECT_EQ("api", res->body);
  10202. }
  10203. TEST(MountTest, PathSegmentBoundary) {
  10204. Server svr;
  10205. svr.set_mount_point("/mount2", "./www2");
  10206. svr.set_mount_point("/", "./www");
  10207. auto port = svr.bind_to_any_port(HOST);
  10208. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10209. auto se = detail::scope_exit([&] {
  10210. svr.stop();
  10211. listen_thread.join();
  10212. ASSERT_FALSE(svr.is_running());
  10213. });
  10214. svr.wait_until_ready();
  10215. Client cli(HOST, port);
  10216. auto res = cli.Get("/mount2/dir/test.html");
  10217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10218. EXPECT_EQ(StatusCode::OK_200, res->status);
  10219. // "/mount2" must not match part-way through a path segment.
  10220. res = cli.Get("/mount2dir/test.html");
  10221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10223. // A mount point ending in '/' keeps matching every path below it.
  10224. res = cli.Get("/dir/test.html");
  10225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10226. EXPECT_EQ(StatusCode::OK_200, res->status);
  10227. }
  10228. TEST(MountTest, Redicect) {
  10229. Server svr;
  10230. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10231. auto se = detail::scope_exit([&] {
  10232. svr.stop();
  10233. listen_thread.join();
  10234. ASSERT_FALSE(svr.is_running());
  10235. });
  10236. svr.set_mount_point("/", "./www");
  10237. svr.wait_until_ready();
  10238. Client cli("localhost", PORT);
  10239. auto res = cli.Get("/dir/");
  10240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10241. EXPECT_EQ(StatusCode::OK_200, res->status);
  10242. res = cli.Get("/dir");
  10243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10244. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10245. res = cli.Get("/file");
  10246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10247. EXPECT_EQ(StatusCode::OK_200, res->status);
  10248. res = cli.Get("/file/");
  10249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10250. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10251. cli.set_follow_location(true);
  10252. res = cli.Get("/dir");
  10253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10254. EXPECT_EQ(StatusCode::OK_200, res->status);
  10255. }
  10256. TEST(MountTest, MultibytesPathName) {
  10257. Server svr;
  10258. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10259. auto se = detail::scope_exit([&] {
  10260. svr.stop();
  10261. listen_thread.join();
  10262. ASSERT_FALSE(svr.is_running());
  10263. });
  10264. svr.set_mount_point("/", "./www");
  10265. svr.wait_until_ready();
  10266. Client cli("localhost", PORT);
  10267. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10269. EXPECT_EQ(StatusCode::OK_200, res->status);
  10270. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10271. }
  10272. #ifdef _WIN32
  10273. // Issue #2435: mmap::open() must succeed even when another handle holds
  10274. // the file open for writing (e.g. an active log file).
  10275. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10276. const char *path = "mmap_concurrent_writer_test.txt";
  10277. const char *content = "hello";
  10278. {
  10279. std::ofstream f(path, std::ios::binary);
  10280. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10281. }
  10282. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10283. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10284. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10285. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10286. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10287. detail::mmap m(path);
  10288. ASSERT_TRUE(m.is_open());
  10289. EXPECT_EQ(strlen(content), m.size());
  10290. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  10291. }
  10292. #endif
  10293. #ifndef _WIN32
  10294. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  10295. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  10296. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  10297. TEST(MmapTest, FailedMappingIsNotOpen) {
  10298. const char *path = "./mmap_failed_mapping_test_dir";
  10299. ASSERT_EQ(0, ::mkdir(path, 0755));
  10300. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10301. detail::mmap m(path);
  10302. EXPECT_FALSE(m.is_open());
  10303. EXPECT_EQ(0U, m.size());
  10304. EXPECT_NE(static_cast<const void *>(m.data()),
  10305. static_cast<const void *>(MAP_FAILED));
  10306. }
  10307. #endif
  10308. TEST(KeepAliveTest, ReadTimeout) {
  10309. Server svr;
  10310. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10311. std::this_thread::sleep_for(std::chrono::seconds(2));
  10312. res.set_content("a", "text/plain");
  10313. });
  10314. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10315. res.set_content("b", "text/plain");
  10316. });
  10317. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10318. auto se = detail::scope_exit([&] {
  10319. svr.stop();
  10320. listen_thread.join();
  10321. ASSERT_FALSE(svr.is_running());
  10322. });
  10323. svr.wait_until_ready();
  10324. Client cli("localhost", PORT);
  10325. cli.set_keep_alive(true);
  10326. cli.set_read_timeout(std::chrono::seconds(1));
  10327. auto resa = cli.Get("/a");
  10328. ASSERT_FALSE(resa);
  10329. EXPECT_EQ(Error::Read, resa.error());
  10330. auto resb = cli.Get("/b");
  10331. ASSERT_TRUE(resb);
  10332. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10333. EXPECT_EQ("b", resb->body);
  10334. }
  10335. TEST(KeepAliveTest, MaxCount) {
  10336. size_t keep_alive_max_count = 3;
  10337. Server svr;
  10338. svr.set_keep_alive_max_count(keep_alive_max_count);
  10339. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10340. res.set_content("Hello World!", "text/plain");
  10341. });
  10342. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10343. auto se = detail::scope_exit([&] {
  10344. svr.stop();
  10345. listen_thread.join();
  10346. ASSERT_FALSE(svr.is_running());
  10347. });
  10348. svr.wait_until_ready();
  10349. Client cli(HOST, PORT);
  10350. cli.set_keep_alive(true);
  10351. for (size_t i = 0; i < 5; i++) {
  10352. auto result = cli.Get("/hi");
  10353. ASSERT_TRUE(result);
  10354. EXPECT_EQ(StatusCode::OK_200, result->status);
  10355. if (i == keep_alive_max_count - 1) {
  10356. EXPECT_EQ("close", result->get_header_value("Connection"));
  10357. } else {
  10358. EXPECT_FALSE(result->has_header("Connection"));
  10359. }
  10360. }
  10361. }
  10362. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10363. // can pull the next one into the server's buffer. The server must serve it
  10364. // without waiting for the socket to become readable again. The keep-alive
  10365. // timeout outlasts the client's read timeout, so a request left waiting for it
  10366. // shows up as a missing response.
  10367. static void serve_pipelining_routes(Server &svr,
  10368. const std::function<void(int)> &client) {
  10369. svr.set_keep_alive_timeout(5);
  10370. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10371. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10372. });
  10373. svr.Post("/echo", [](const Request &req, Response &res) {
  10374. res.set_content("echo " + req.body, "text/plain");
  10375. });
  10376. auto port = svr.bind_to_any_port(HOST);
  10377. thread t = thread([&] { svr.listen_after_bind(); });
  10378. auto se = detail::scope_exit([&] {
  10379. svr.stop();
  10380. t.join();
  10381. });
  10382. svr.wait_until_ready();
  10383. client(port);
  10384. }
  10385. static std::string
  10386. send_pipelined_requests(const std::vector<std::string> &parts) {
  10387. Server svr;
  10388. std::string res;
  10389. serve_pipelining_routes(svr, [&](int port) {
  10390. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10391. });
  10392. return res;
  10393. }
  10394. static void expect_in_order(const std::string &res,
  10395. const std::vector<std::string> &bodies) {
  10396. size_t pos = 0;
  10397. for (const auto &body : bodies) {
  10398. pos = res.find(body, pos);
  10399. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10400. pos += body.size();
  10401. }
  10402. }
  10403. TEST(KeepAliveTest, PipelinedRequests) {
  10404. auto res = send_pipelined_requests(
  10405. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10406. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10407. "Content-Length: 4\r\n\r\nbody"
  10408. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10409. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10410. }
  10411. // The second request starts in the server's buffer and ends on the socket.
  10412. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10413. auto res =
  10414. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10415. "GET /hi/2 HTTP/1.1\r\nHo",
  10416. "st: localhost\r\nConnection: close\r\n\r\n"});
  10417. expect_in_order(res, {"hi 1", "hi 2"});
  10418. }
  10419. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10420. // CRLF after a body does not turn into a 400 for the next request.
  10421. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10422. auto res = send_pipelined_requests(
  10423. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10424. "Content-Length: 4\r\n\r\nbody\r\n"
  10425. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10426. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10427. expect_in_order(res, {"echo body", "hi 2"});
  10428. }
  10429. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10430. // must not be served as the next request.
  10431. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10432. auto res = send_pipelined_requests(
  10433. {"INVALID REQUEST LINE\r\n\r\n"
  10434. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10435. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10436. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10437. }
  10438. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10439. // Over TLS, the next request is held by the TLS library as already decrypted
  10440. // data rather than on the socket.
  10441. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10443. std::string res;
  10444. serve_pipelining_routes(svr, [&](int port) {
  10445. // One part, so all three requests arrive in one TLS record
  10446. EXPECT_TRUE(send_ssl_request_in_parts(
  10447. 2,
  10448. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10449. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10450. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10451. &res, port));
  10452. });
  10453. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10454. }
  10455. #endif
  10456. TEST(KeepAliveTest, Issue1041) {
  10457. Server svr;
  10458. svr.set_keep_alive_timeout(3);
  10459. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10460. res.set_content("Hello World!", "text/plain");
  10461. });
  10462. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10463. auto se = detail::scope_exit([&] {
  10464. svr.stop();
  10465. listen_thread.join();
  10466. ASSERT_FALSE(svr.is_running());
  10467. });
  10468. svr.wait_until_ready();
  10469. Client cli(HOST, PORT);
  10470. cli.set_keep_alive(true);
  10471. auto result = cli.Get("/hi");
  10472. ASSERT_TRUE(result);
  10473. EXPECT_EQ(StatusCode::OK_200, result->status);
  10474. std::this_thread::sleep_for(std::chrono::seconds(5));
  10475. result = cli.Get("/hi");
  10476. ASSERT_TRUE(result);
  10477. EXPECT_EQ(StatusCode::OK_200, result->status);
  10478. }
  10479. TEST(KeepAliveTest, Issue1959) {
  10480. Server svr;
  10481. svr.set_keep_alive_timeout(5);
  10482. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10483. res.set_content("a", "text/plain");
  10484. });
  10485. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10486. auto se = detail::scope_exit([&] {
  10487. if (!svr.is_running()) return;
  10488. svr.stop();
  10489. listen_thread.join();
  10490. ASSERT_FALSE(svr.is_running());
  10491. });
  10492. svr.wait_until_ready();
  10493. Client cli("localhost", PORT);
  10494. cli.set_keep_alive(true);
  10495. using namespace std::chrono;
  10496. auto start = steady_clock::now();
  10497. cli.Get("/a");
  10498. svr.stop();
  10499. listen_thread.join();
  10500. auto end = steady_clock::now();
  10501. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10502. EXPECT_LT(elapsed, 5000);
  10503. }
  10504. #ifdef CPPHTTPLIB_SSL_ENABLED
  10505. TEST(KeepAliveTest, SSLClientReconnection) {
  10506. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10507. ASSERT_TRUE(svr.is_valid());
  10508. svr.set_keep_alive_timeout(1);
  10509. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10510. res.set_content("Hello World!", "text/plain");
  10511. });
  10512. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10513. auto se = detail::scope_exit([&] {
  10514. svr.stop();
  10515. listen_thread.join();
  10516. ASSERT_FALSE(svr.is_running());
  10517. });
  10518. svr.wait_until_ready();
  10519. SSLClient cli(HOST, PORT);
  10520. cli.enable_server_certificate_verification(false);
  10521. cli.set_keep_alive(true);
  10522. auto result = cli.Get("/hi");
  10523. ASSERT_TRUE(result);
  10524. EXPECT_EQ(StatusCode::OK_200, result->status);
  10525. result = cli.Get("/hi");
  10526. ASSERT_TRUE(result);
  10527. EXPECT_EQ(StatusCode::OK_200, result->status);
  10528. std::this_thread::sleep_for(std::chrono::seconds(2));
  10529. // Recoonect
  10530. result = cli.Get("/hi");
  10531. ASSERT_TRUE(result);
  10532. EXPECT_EQ(StatusCode::OK_200, result->status);
  10533. result = cli.Get("/hi");
  10534. ASSERT_TRUE(result);
  10535. EXPECT_EQ(StatusCode::OK_200, result->status);
  10536. }
  10537. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10539. ASSERT_TRUE(svr.is_valid());
  10540. svr.set_keep_alive_timeout(1);
  10541. std::string content = "reconnect";
  10542. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10543. res.set_content("Hello World!", "text/plain");
  10544. });
  10545. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10546. auto se = detail::scope_exit([&] {
  10547. svr.stop();
  10548. listen_thread.join();
  10549. ASSERT_FALSE(svr.is_running());
  10550. });
  10551. svr.wait_until_ready();
  10552. SSLClient cli(HOST, PORT);
  10553. cli.enable_server_certificate_verification(false);
  10554. cli.set_keep_alive(true);
  10555. auto result = cli.Post(
  10556. "/hi", content.size(),
  10557. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10558. sink.write(content.c_str(), content.size());
  10559. return true;
  10560. },
  10561. "text/plain");
  10562. ASSERT_TRUE(result);
  10563. EXPECT_EQ(200, result->status);
  10564. std::this_thread::sleep_for(std::chrono::seconds(2));
  10565. // Recoonect
  10566. result = cli.Post(
  10567. "/hi", content.size(),
  10568. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10569. sink.write(content.c_str(), content.size());
  10570. return true;
  10571. },
  10572. "text/plain");
  10573. ASSERT_TRUE(result);
  10574. EXPECT_EQ(200, result->status);
  10575. result = cli.Post(
  10576. "/hi", content.size(),
  10577. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10578. sink.write(content.c_str(), content.size());
  10579. return true;
  10580. },
  10581. "text/plain");
  10582. ASSERT_TRUE(result);
  10583. EXPECT_EQ(200, result->status);
  10584. }
  10585. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10586. using namespace httplib::tls;
  10587. {
  10588. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10589. ASSERT_TRUE(svr.is_valid());
  10590. svr.Get("/sni", [&](const Request &req, Response &res) {
  10591. std::string expected = req.sni();
  10592. EXPECT_EQ(expected, req.get_param_value("expected"));
  10593. res.set_content("ok", "text/plain");
  10594. });
  10595. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10596. auto se = detail::scope_exit([&] {
  10597. svr.stop();
  10598. listen_thread.join();
  10599. ASSERT_FALSE(svr.is_running());
  10600. });
  10601. svr.wait_until_ready();
  10602. {
  10603. SSLClient cli("localhost", PORT);
  10604. cli.enable_server_certificate_verification(false);
  10605. auto res = cli.Get("/sni?expected=localhost");
  10606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10607. }
  10608. {
  10609. SSLClient cli("::1", PORT);
  10610. cli.enable_server_certificate_verification(false);
  10611. auto res = cli.Get("/sni?expected=");
  10612. // NOTE: This may fail if the server is listening on IPv4 only
  10613. // (e.g., when localhost resolves to 127.0.0.1 only)
  10614. if (res) {
  10615. EXPECT_EQ(StatusCode::OK_200, res->status);
  10616. } else {
  10617. EXPECT_EQ(Error::Connection, res.error());
  10618. }
  10619. }
  10620. }
  10621. }
  10622. #endif
  10623. TEST(ClientProblemDetectionTest, ContentProvider) {
  10624. Server svr;
  10625. size_t content_length = 1024 * 1024;
  10626. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10627. res.set_content_provider(
  10628. content_length, "text/plain",
  10629. [&](size_t offset, size_t length, DataSink &sink) {
  10630. auto out_len = std::min(length, static_cast<size_t>(1024));
  10631. std::string out(out_len, '@');
  10632. sink.write(out.data(), out_len);
  10633. return offset < 4096;
  10634. },
  10635. [](bool success) { ASSERT_FALSE(success); });
  10636. });
  10637. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10638. res.set_content_provider(
  10639. 0, "text/plain",
  10640. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10641. EXPECT_TRUE(false);
  10642. return true;
  10643. },
  10644. [](bool success) { ASSERT_FALSE(success); });
  10645. });
  10646. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10647. auto se = detail::scope_exit([&] {
  10648. svr.stop();
  10649. listen_thread.join();
  10650. ASSERT_FALSE(svr.is_running());
  10651. });
  10652. svr.wait_until_ready();
  10653. Client cli("localhost", PORT);
  10654. {
  10655. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10656. size_t /*data_length*/) { return false; });
  10657. ASSERT_FALSE(res);
  10658. }
  10659. {
  10660. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10661. size_t /*data_length*/) { return false; });
  10662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10663. }
  10664. }
  10665. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10666. // A provider that reports success without writing anything and without
  10667. // calling done() used to be handed the same offset and length again on every
  10668. // pass, so it spun for as long as the peer stayed connected.
  10669. Server svr;
  10670. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10671. res.set_content("ok", "text/plain");
  10672. });
  10673. auto port = svr.bind_to_any_port(HOST);
  10674. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10675. auto se = detail::scope_exit([&] {
  10676. svr.stop();
  10677. listen_thread.join();
  10678. ASSERT_FALSE(svr.is_running());
  10679. });
  10680. svr.wait_until_ready();
  10681. std::atomic<int> call_count{0};
  10682. Client cli(HOST, port);
  10683. auto res = cli.Post(
  10684. "/", 1024,
  10685. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10686. // Give up after enough passes to show the spin, so that losing the
  10687. // check below fails this test instead of hanging it.
  10688. return ++call_count < 100;
  10689. },
  10690. "text/plain");
  10691. ASSERT_FALSE(res);
  10692. EXPECT_EQ(Error::Write, res.error());
  10693. EXPECT_EQ(1, call_count.load());
  10694. }
  10695. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10696. // A writer only has to assign `write`. The other three used to be left as
  10697. // empty std::functions, so a provider calling one threw
  10698. // std::bad_function_call out of the thread running it and took the whole
  10699. // process down.
  10700. DataSink sink;
  10701. std::string written;
  10702. sink.write = [&](const char *data, size_t data_len) {
  10703. written.append(data, data_len);
  10704. return true;
  10705. };
  10706. EXPECT_TRUE(sink.is_writable());
  10707. sink.done();
  10708. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10709. EXPECT_TRUE(written.empty());
  10710. }
  10711. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10712. // A sink that cannot carry trailers still has to finish.
  10713. DataSink sink;
  10714. auto done_count = 0;
  10715. sink.done = [&]() { done_count++; };
  10716. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10717. EXPECT_EQ(1, done_count);
  10718. }
  10719. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10720. Server svr;
  10721. const std::string body(4096, 'x');
  10722. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10723. res.set_content_provider(body.size(), "text/plain",
  10724. [&](size_t offset, size_t length, DataSink &sink) {
  10725. sink.write(body.data() + offset, length);
  10726. sink.done();
  10727. return true;
  10728. });
  10729. });
  10730. auto port = svr.bind_to_any_port(HOST);
  10731. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10732. auto se = detail::scope_exit([&] {
  10733. svr.stop();
  10734. listen_thread.join();
  10735. ASSERT_FALSE(svr.is_running());
  10736. });
  10737. svr.wait_until_ready();
  10738. Client cli(HOST, port);
  10739. auto res = cli.Get("/");
  10740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10741. EXPECT_EQ(StatusCode::OK_200, res->status);
  10742. EXPECT_EQ(body, res->body);
  10743. }
  10744. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10745. Server svr;
  10746. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10747. res.set_content_provider(
  10748. 1024, "text/plain",
  10749. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10750. sink.write("hello", 5);
  10751. sink.done(); // short of the 1024 bytes the response promised
  10752. return true;
  10753. });
  10754. });
  10755. auto port = svr.bind_to_any_port(HOST);
  10756. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10757. auto se = detail::scope_exit([&] {
  10758. svr.stop();
  10759. listen_thread.join();
  10760. ASSERT_FALSE(svr.is_running());
  10761. });
  10762. svr.wait_until_ready();
  10763. Client cli(HOST, port);
  10764. cli.set_read_timeout(5, 0);
  10765. // The response is short of its Content-Length, so the client cannot read a
  10766. // complete body. What matters is that this returns at all: a no-op done()
  10767. // would leave the writer looping over a provider that never makes progress.
  10768. auto res = cli.Get("/");
  10769. EXPECT_FALSE(res);
  10770. }
  10771. // Read as the next response by a peer that sees it after a framed body.
  10772. static const std::string smuggled_response =
  10773. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  10774. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  10775. Server svr;
  10776. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10777. res.set_content_provider(
  10778. 5, "text/plain",
  10779. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10780. auto data = "AAAAA" + smuggled_response;
  10781. sink.write(data.data(), data.size());
  10782. return true;
  10783. });
  10784. });
  10785. thread t = thread([&] { svr.listen(HOST, PORT); });
  10786. auto se = detail::scope_exit([&] {
  10787. svr.stop();
  10788. t.join();
  10789. ASSERT_FALSE(svr.is_running());
  10790. });
  10791. svr.wait_until_ready();
  10792. std::string resp;
  10793. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10794. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  10795. resp.clear();
  10796. ASSERT_TRUE(send_request(
  10797. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  10798. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  10799. }
  10800. TEST(NoContentTest, BodyIsNotSent) {
  10801. Server svr;
  10802. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  10803. res.status = StatusCode::NoContent_204;
  10804. res.set_content(smuggled_response, "text/plain");
  10805. });
  10806. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  10807. res.status = StatusCode::NotModified_304;
  10808. res.set_chunked_content_provider(
  10809. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  10810. sink.write(smuggled_response.data(), smuggled_response.size());
  10811. sink.done();
  10812. return true;
  10813. });
  10814. });
  10815. thread t = thread([&] { svr.listen(HOST, PORT); });
  10816. auto se = detail::scope_exit([&] {
  10817. svr.stop();
  10818. t.join();
  10819. ASSERT_FALSE(svr.is_running());
  10820. });
  10821. svr.wait_until_ready();
  10822. for (auto path : {"/204", "/304"}) {
  10823. std::string resp;
  10824. ASSERT_TRUE(send_request(
  10825. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10826. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  10827. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  10828. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  10829. }
  10830. }
  10831. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  10832. Server svr;
  10833. std::atomic<bool> smuggled(false);
  10834. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10835. res.set_content("ok", "text/plain");
  10836. });
  10837. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  10838. smuggled = true;
  10839. });
  10840. auto port = svr.bind_to_any_port(HOST);
  10841. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10842. auto se = detail::scope_exit([&] {
  10843. svr.stop();
  10844. listen_thread.join();
  10845. ASSERT_FALSE(svr.is_running());
  10846. });
  10847. svr.wait_until_ready();
  10848. // What follows the body would be read as the next request.
  10849. Client cli(HOST, port);
  10850. auto res = cli.Post(
  10851. "/", 5,
  10852. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10853. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  10854. sink.write(data.data(), data.size());
  10855. return true;
  10856. },
  10857. "text/plain");
  10858. ASSERT_FALSE(res);
  10859. EXPECT_EQ(Error::Write, res.error());
  10860. EXPECT_FALSE(smuggled);
  10861. }
  10862. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10863. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10864. // The compressed path builds the whole body before connecting, so this
  10865. // fails client-side and never reaches a server.
  10866. Client cli(HOST, PORT);
  10867. cli.set_compress(true);
  10868. auto res = cli.Post(
  10869. "/", 1024,
  10870. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10871. sink.write("hello", 5);
  10872. sink.done(); // short of the 1024 bytes the request announced
  10873. return true;
  10874. },
  10875. "text/plain");
  10876. ASSERT_FALSE(res);
  10877. EXPECT_EQ(Error::Write, res.error());
  10878. }
  10879. #endif
  10880. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10881. Server svr;
  10882. svr.set_error_handler([](Request const &, Response &res) -> void {
  10883. res.set_chunked_content_provider(
  10884. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10885. sink.os << "hello";
  10886. sink.os << "world";
  10887. sink.done();
  10888. return true;
  10889. });
  10890. });
  10891. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10892. auto se = detail::scope_exit([&] {
  10893. svr.stop();
  10894. listen_thread.join();
  10895. ASSERT_FALSE(svr.is_running());
  10896. });
  10897. svr.wait_until_ready();
  10898. Client cli("localhost", PORT);
  10899. auto res = cli.Get("/");
  10900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10901. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10902. EXPECT_EQ("helloworld", res->body);
  10903. }
  10904. // A body set after a content provider must replace it, not be sent through it.
  10905. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10906. Server svr;
  10907. svr.set_mount_point("/", "./www");
  10908. svr.set_file_request_handler([](const Request &req, Response &res) {
  10909. if (req.path == "/dir/test.html") {
  10910. res.status = StatusCode::Forbidden_403;
  10911. res.set_content(std::string(5000, 'D'), "text/plain");
  10912. } else if (req.path == "/file") {
  10913. res.status = StatusCode::Forbidden_403;
  10914. res.body = "Denied";
  10915. }
  10916. });
  10917. auto port = svr.bind_to_any_port(HOST);
  10918. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10919. auto se = detail::scope_exit([&] {
  10920. svr.stop();
  10921. t.join();
  10922. ASSERT_FALSE(svr.is_running());
  10923. });
  10924. svr.wait_until_ready();
  10925. Client cli(HOST, port);
  10926. {
  10927. auto res = cli.Get("/dir/test.html");
  10928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10929. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10930. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10931. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10932. }
  10933. {
  10934. auto res = cli.Get("/file");
  10935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10936. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10937. EXPECT_EQ("Denied", res->body);
  10938. }
  10939. {
  10940. auto res = cli.Get("/dir/index.html");
  10941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10942. EXPECT_EQ(StatusCode::OK_200, res->status);
  10943. EXPECT_EQ(0U, res->body.find("<html>"));
  10944. }
  10945. }
  10946. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10947. Server svr;
  10948. std::vector<bool> released;
  10949. std::mutex released_mutex;
  10950. auto releaser = [&](bool success) {
  10951. std::lock_guard<std::mutex> guard(released_mutex);
  10952. released.push_back(success);
  10953. };
  10954. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10955. return sink.write(&"hello"[offset], length);
  10956. };
  10957. svr.Get("/sized", [&](const Request &, Response &res) {
  10958. res.status = StatusCode::NotFound_404;
  10959. res.set_content_provider(5, "text/plain", provider, releaser);
  10960. });
  10961. svr.Get("/chunked", [&](const Request &, Response &res) {
  10962. res.status = StatusCode::ServiceUnavailable_503;
  10963. res.set_chunked_content_provider(
  10964. "text/plain",
  10965. [](size_t, DataSink &sink) {
  10966. sink.os << "chunk";
  10967. sink.done();
  10968. return true;
  10969. },
  10970. releaser);
  10971. });
  10972. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10973. res.set_content_provider(5, "text/plain", provider, releaser);
  10974. throw std::runtime_error("after the provider");
  10975. });
  10976. svr.set_error_handler([](const Request &req, Response &res) {
  10977. // Leave the exception handler's content to it.
  10978. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10979. res.set_content(std::string(1000, 'E'), "text/html");
  10980. return Server::HandlerResponse::Handled;
  10981. });
  10982. svr.set_exception_handler(
  10983. [](const Request &, Response &res, std::exception_ptr) {
  10984. res.status = StatusCode::InternalServerError_500;
  10985. res.set_content(std::string(1000, 'X'), "text/html");
  10986. });
  10987. auto port = svr.bind_to_any_port(HOST);
  10988. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10989. auto se = detail::scope_exit([&] {
  10990. svr.stop();
  10991. t.join();
  10992. ASSERT_FALSE(svr.is_running());
  10993. });
  10994. svr.wait_until_ready();
  10995. Client cli(HOST, port);
  10996. {
  10997. auto res = cli.Get("/sized");
  10998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10999. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11000. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11001. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11002. }
  11003. {
  11004. auto res = cli.Get("/chunked");
  11005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11006. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11007. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11008. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11009. }
  11010. {
  11011. auto res = cli.Get("/throw");
  11012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11013. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11014. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11015. }
  11016. std::lock_guard<std::mutex> guard(released_mutex);
  11017. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11018. }
  11019. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11020. Server svr;
  11021. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11022. return sink.write(&"abc"[offset], length);
  11023. };
  11024. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11025. res.set_file_content("./www/dir/test.html");
  11026. res.set_content("body", "text/plain");
  11027. });
  11028. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11029. res.set_content(std::string(100, 'B'), "text/plain");
  11030. res.set_file_content("./www/dir/test.html");
  11031. });
  11032. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11033. res.set_content(std::string(100, 'B'), "text/plain");
  11034. res.set_content_provider(3, "text/plain", abc);
  11035. });
  11036. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11037. res.set_content_provider(3, "text/plain", abc);
  11038. res.set_content(std::string(100, 'B'), "text/plain");
  11039. });
  11040. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11041. res.set_content_provider(3, "text/plain", abc);
  11042. res.body = "direct";
  11043. });
  11044. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11045. res.set_file_content("./www/dir/test.html");
  11046. res.body = "direct";
  11047. });
  11048. auto port = svr.bind_to_any_port(HOST);
  11049. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11050. auto se = detail::scope_exit([&] {
  11051. svr.stop();
  11052. t.join();
  11053. ASSERT_FALSE(svr.is_running());
  11054. });
  11055. svr.wait_until_ready();
  11056. Client cli(HOST, port);
  11057. auto expect_body = [&](const char *path, const std::string &body) {
  11058. // Uncompressed, so Content-Length can be compared with the body.
  11059. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11060. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11061. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11062. EXPECT_EQ(body, res->body) << path;
  11063. EXPECT_EQ(std::to_string(body.size()),
  11064. res->get_header_value("Content-Length"))
  11065. << path;
  11066. };
  11067. expect_body("/file-then-body", "body");
  11068. expect_body("/body-then-file", "test.html");
  11069. expect_body("/body-then-provider", "abc");
  11070. expect_body("/provider-then-body", std::string(100, 'B'));
  11071. expect_body("/provider-then-direct-body", "direct");
  11072. expect_body("/file-then-direct-body", "direct");
  11073. // Ranges are checked against the body, not the dropped provider.
  11074. {
  11075. auto res = cli.Get("/provider-then-direct-body",
  11076. Headers{{make_range_header({{1, 2}})}});
  11077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11078. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11079. EXPECT_EQ("ir", res->body);
  11080. }
  11081. {
  11082. auto res = cli.Get("/file-then-direct-body",
  11083. Headers{{make_range_header({{7, 8}})}});
  11084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11085. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11086. }
  11087. }
  11088. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11089. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11090. const char *path = "./truncated_while_served.txt";
  11091. const size_t size = 32 * 1024 * 1024;
  11092. {
  11093. std::ofstream f(path, std::ios::binary);
  11094. f << std::string(size, 'x');
  11095. }
  11096. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11097. // Over TLS, where the bytes are encrypted in this process rather than
  11098. // copied by send().
  11099. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11100. svr.Get("/file", [&](const Request &, Response &res) {
  11101. res.set_file_content(path, "text/plain");
  11102. });
  11103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11104. auto se = detail::scope_exit([&] {
  11105. svr.stop();
  11106. thread.join();
  11107. ASSERT_FALSE(svr.is_running());
  11108. });
  11109. svr.wait_until_ready();
  11110. // The file shrinks once the first bytes are in, as a rewrite in place
  11111. // would, and reading the mapping past its new end used to raise SIGBUS.
  11112. SSLClient cli(HOST, PORT);
  11113. cli.enable_server_certificate_verification(false);
  11114. size_t received = 0;
  11115. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11116. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11117. received += len;
  11118. return true;
  11119. });
  11120. EXPECT_FALSE(res);
  11121. EXPECT_LT(received, size);
  11122. }
  11123. #endif
  11124. // Forward declaration (see the base64_encode note).
  11125. namespace httplib {
  11126. namespace detail {
  11127. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11128. const std::string &content_type,
  11129. EncodingType encoding);
  11130. } // namespace detail
  11131. } // namespace httplib
  11132. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11133. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11134. ASSERT_TRUE(mm->is_open());
  11135. Response res;
  11136. detail::set_file_content_provider(res, mm, "text/html",
  11137. detail::EncodingType::None);
  11138. std::string out;
  11139. DataSink sink;
  11140. sink.write = [&](const char *d, size_t l) {
  11141. out.append(d, l);
  11142. return true;
  11143. };
  11144. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11145. EXPECT_EQ("test.html", out);
  11146. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11147. EXPECT_EQ("test.html", out);
  11148. }
  11149. TEST(LongPollingTest, ClientCloseDetection) {
  11150. Server svr;
  11151. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11152. res.set_chunked_content_provider(
  11153. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11154. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11155. sink.os << "hello";
  11156. auto count = 10;
  11157. while (count > 0 && sink.is_writable()) {
  11158. this_thread::sleep_for(chrono::milliseconds(10));
  11159. count--;
  11160. }
  11161. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11162. return true;
  11163. });
  11164. });
  11165. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11166. auto se = detail::scope_exit([&] {
  11167. svr.stop();
  11168. listen_thread.join();
  11169. ASSERT_FALSE(svr.is_running());
  11170. });
  11171. svr.wait_until_ready();
  11172. Client cli("localhost", PORT);
  11173. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11174. EXPECT_EQ("hello", string(data, data_length));
  11175. return false; // close the socket immediately.
  11176. });
  11177. ASSERT_FALSE(res);
  11178. }
  11179. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11180. Server svr;
  11181. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11182. res.set_chunked_content_provider(
  11183. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11184. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11185. sink.os << "hello";
  11186. EXPECT_TRUE(sink.os.good());
  11187. // Wait for the client to close the connection
  11188. auto count = 10;
  11189. while (count > 0 && sink.is_writable()) {
  11190. this_thread::sleep_for(chrono::milliseconds(10));
  11191. count--;
  11192. }
  11193. // After client disconnect, write repeatedly until the socket
  11194. // write actually fails (small writes may be absorbed by the
  11195. // kernel buffer)
  11196. std::string chunk(1024, 'x');
  11197. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11198. sink.os << chunk;
  11199. }
  11200. EXPECT_TRUE(sink.os.fail());
  11201. return true;
  11202. });
  11203. });
  11204. auto port = svr.bind_to_any_port("localhost");
  11205. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11206. auto se = detail::scope_exit([&] {
  11207. svr.stop();
  11208. listen_thread.join();
  11209. ASSERT_FALSE(svr.is_running());
  11210. });
  11211. svr.wait_until_ready();
  11212. Client cli("localhost", port);
  11213. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11214. EXPECT_EQ("hello", string(data, data_length));
  11215. return false; // close the socket immediately.
  11216. });
  11217. ASSERT_FALSE(res);
  11218. }
  11219. TEST(GetWithParametersTest, GetWithParameters) {
  11220. Server svr;
  11221. svr.Get("/", [&](const Request &req, Response &) {
  11222. EXPECT_EQ("world", req.get_param_value("hello"));
  11223. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11224. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11225. });
  11226. svr.Get("/params", [&](const Request &req, Response &) {
  11227. EXPECT_EQ("world", req.get_param_value("hello"));
  11228. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11229. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11230. });
  11231. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11232. EXPECT_EQ("resource-id", req.matches[1]);
  11233. EXPECT_EQ("foo", req.get_param_value("param1"));
  11234. EXPECT_EQ("bar", req.get_param_value("param2"));
  11235. });
  11236. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11237. EXPECT_EQ("user-id", req.path_params.at("id"));
  11238. EXPECT_EQ("foo", req.get_param_value("param1"));
  11239. EXPECT_EQ("bar", req.get_param_value("param2"));
  11240. });
  11241. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11242. auto se = detail::scope_exit([&] {
  11243. svr.stop();
  11244. listen_thread.join();
  11245. ASSERT_FALSE(svr.is_running());
  11246. });
  11247. svr.wait_until_ready();
  11248. {
  11249. Client cli(HOST, PORT);
  11250. Params params;
  11251. params.emplace("hello", "world");
  11252. params.emplace("hello2", "world2");
  11253. params.emplace("hello3", "world3");
  11254. auto res = cli.Get("/", params, Headers{});
  11255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11256. EXPECT_EQ(StatusCode::OK_200, res->status);
  11257. }
  11258. {
  11259. Client cli(HOST, PORT);
  11260. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11262. EXPECT_EQ(StatusCode::OK_200, res->status);
  11263. }
  11264. {
  11265. Client cli(HOST, PORT);
  11266. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11268. EXPECT_EQ(StatusCode::OK_200, res->status);
  11269. }
  11270. {
  11271. Client cli(HOST, PORT);
  11272. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11274. EXPECT_EQ(StatusCode::OK_200, res->status);
  11275. }
  11276. }
  11277. TEST(GetWithParametersTest, GetWithParameters2) {
  11278. Server svr;
  11279. svr.Get("/", [&](const Request &req, Response &res) {
  11280. auto text = req.get_param_value("hello");
  11281. res.set_content(text, "text/plain");
  11282. });
  11283. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11284. auto se = detail::scope_exit([&] {
  11285. svr.stop();
  11286. listen_thread.join();
  11287. ASSERT_FALSE(svr.is_running());
  11288. });
  11289. svr.wait_until_ready();
  11290. Client cli("localhost", PORT);
  11291. Params params;
  11292. params.emplace("hello", "world");
  11293. std::string body;
  11294. auto res = cli.Get("/", params, Headers{},
  11295. [&](const char *data, size_t data_length) {
  11296. body.append(data, data_length);
  11297. return true;
  11298. });
  11299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11300. EXPECT_EQ(StatusCode::OK_200, res->status);
  11301. EXPECT_EQ("world", body);
  11302. }
  11303. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11304. Server svr;
  11305. svr.Get("/search", [&](const Request &req, Response &res) {
  11306. auto q = req.get_param_value("q");
  11307. res.set_content(q, "text/plain");
  11308. });
  11309. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11310. auto se = detail::scope_exit([&] {
  11311. svr.stop();
  11312. listen_thread.join();
  11313. ASSERT_FALSE(svr.is_running());
  11314. });
  11315. svr.wait_until_ready();
  11316. Client cli("localhost", PORT);
  11317. // Verify that Get(path, params) works without requiring Headers argument
  11318. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11320. EXPECT_EQ(StatusCode::OK_200, res->status);
  11321. EXPECT_EQ("cpp-httplib", res->body);
  11322. }
  11323. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11324. auto host = "httpbingo.org";
  11325. auto path = std::string{"/range/32"};
  11326. #ifdef CPPHTTPLIB_SSL_ENABLED
  11327. SSLClient cli(host);
  11328. #else
  11329. Client cli(host);
  11330. #endif
  11331. cli.set_default_headers({make_range_header({{1, 10}})});
  11332. cli.set_connection_timeout(5);
  11333. {
  11334. auto res = cli.Get(path);
  11335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11336. EXPECT_EQ("bcdefghijk", res->body);
  11337. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11338. }
  11339. {
  11340. auto res = cli.Get(path);
  11341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11342. EXPECT_EQ("bcdefghijk", res->body);
  11343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11344. }
  11345. }
  11346. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11347. Server svr;
  11348. svr.set_default_headers({{"Hello", "World"}});
  11349. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11350. res.set_content("ok", "text/plain");
  11351. });
  11352. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11353. auto se = detail::scope_exit([&] {
  11354. svr.stop();
  11355. listen_thread.join();
  11356. ASSERT_FALSE(svr.is_running());
  11357. });
  11358. svr.wait_until_ready();
  11359. Client cli("localhost", PORT);
  11360. auto res = cli.Get("/");
  11361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11362. EXPECT_EQ(StatusCode::OK_200, res->status);
  11363. EXPECT_EQ("ok", res->body);
  11364. EXPECT_EQ("World", res->get_header_value("Hello"));
  11365. }
  11366. #ifdef CPPHTTPLIB_SSL_ENABLED
  11367. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11368. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11369. ASSERT_TRUE(svr.is_valid());
  11370. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11371. std::this_thread::sleep_for(std::chrono::seconds(2));
  11372. res.set_content("a", "text/plain");
  11373. });
  11374. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11375. res.set_content("b", "text/plain");
  11376. });
  11377. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11378. auto se = detail::scope_exit([&] {
  11379. svr.stop();
  11380. listen_thread.join();
  11381. ASSERT_FALSE(svr.is_running());
  11382. });
  11383. svr.wait_until_ready();
  11384. SSLClient cli("localhost", PORT);
  11385. cli.enable_server_certificate_verification(false);
  11386. cli.set_keep_alive(true);
  11387. cli.set_read_timeout(std::chrono::seconds(1));
  11388. auto resa = cli.Get("/a");
  11389. ASSERT_TRUE(!resa);
  11390. EXPECT_EQ(Error::Read, resa.error());
  11391. auto resb = cli.Get("/b");
  11392. ASSERT_TRUE(resb);
  11393. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11394. EXPECT_EQ("b", resb->body);
  11395. }
  11396. // Closing an idle keep-alive connection sends close_notify and returns. The
  11397. // server must not wait for the client's close_notify: an idle client never
  11398. // sends one, so the worker would be held until the read timeout expires, and
  11399. // stop() would wait for it.
  11400. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11402. ASSERT_TRUE(svr.is_valid());
  11403. svr.set_keep_alive_timeout(1);
  11404. svr.set_read_timeout(10, 0);
  11405. svr.Get("/", [](const Request &, Response &res) {
  11406. res.set_content("ok", "text/plain");
  11407. });
  11408. auto port = svr.bind_to_any_port(HOST);
  11409. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11410. auto se = detail::scope_exit([&] {
  11411. if (listen_thread.joinable()) {
  11412. svr.stop();
  11413. listen_thread.join();
  11414. }
  11415. });
  11416. svr.wait_until_ready();
  11417. SSLClient cli(HOST, port);
  11418. cli.enable_server_certificate_verification(false);
  11419. cli.set_keep_alive(true);
  11420. auto res = cli.Get("/");
  11421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11422. EXPECT_EQ(StatusCode::OK_200, res->status);
  11423. // Stay idle past the keep-alive timeout so the server closes the connection.
  11424. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11425. auto start = std::chrono::steady_clock::now();
  11426. svr.stop();
  11427. listen_thread.join();
  11428. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11429. std::chrono::steady_clock::now() - start)
  11430. .count();
  11431. EXPECT_LT(elapsed, 3000);
  11432. }
  11433. #endif
  11434. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11435. protected:
  11436. ServerTestWithAI_PASSIVE()
  11437. : cli_(HOST, PORT)
  11438. #ifdef CPPHTTPLIB_SSL_ENABLED
  11439. ,
  11440. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11441. #endif
  11442. {
  11443. #ifdef CPPHTTPLIB_SSL_ENABLED
  11444. cli_.enable_server_certificate_verification(false);
  11445. #endif
  11446. }
  11447. virtual void SetUp() {
  11448. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11449. res.set_content("Hello World!", "text/plain");
  11450. });
  11451. t_ = thread(
  11452. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11453. svr_.wait_until_ready();
  11454. }
  11455. virtual void TearDown() {
  11456. svr_.stop();
  11457. t_.join();
  11458. }
  11459. #ifdef CPPHTTPLIB_SSL_ENABLED
  11460. SSLClient cli_;
  11461. SSLServer svr_;
  11462. #else
  11463. Client cli_;
  11464. Server svr_;
  11465. #endif
  11466. thread t_;
  11467. };
  11468. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11469. auto res = cli_.Get("/hi");
  11470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11471. EXPECT_EQ(StatusCode::OK_200, res->status);
  11472. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11473. EXPECT_EQ("Hello World!", res->body);
  11474. }
  11475. class ServerUpDownTest : public ::testing::Test {
  11476. protected:
  11477. ServerUpDownTest() : cli_(HOST, PORT) {}
  11478. virtual void SetUp() {
  11479. t_ = thread([&]() {
  11480. svr_.bind_to_any_port(HOST);
  11481. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11482. ASSERT_TRUE(svr_.listen_after_bind());
  11483. });
  11484. svr_.wait_until_ready();
  11485. }
  11486. virtual void TearDown() {
  11487. svr_.stop();
  11488. t_.join();
  11489. }
  11490. Client cli_;
  11491. Server svr_;
  11492. thread t_;
  11493. };
  11494. TEST_F(ServerUpDownTest, QuickStartStop) {
  11495. // Should not crash, especially when run with
  11496. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11497. }
  11498. class PayloadMaxLengthTest : public ::testing::Test {
  11499. protected:
  11500. PayloadMaxLengthTest()
  11501. : cli_(HOST, PORT)
  11502. #ifdef CPPHTTPLIB_SSL_ENABLED
  11503. ,
  11504. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11505. #endif
  11506. {
  11507. #ifdef CPPHTTPLIB_SSL_ENABLED
  11508. cli_.enable_server_certificate_verification(false);
  11509. #endif
  11510. }
  11511. virtual void SetUp() {
  11512. svr_.set_payload_max_length(8);
  11513. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11514. res.set_content("test", "text/plain");
  11515. });
  11516. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11517. svr_.wait_until_ready();
  11518. }
  11519. virtual void TearDown() {
  11520. svr_.stop();
  11521. t_.join();
  11522. }
  11523. #ifdef CPPHTTPLIB_SSL_ENABLED
  11524. SSLClient cli_;
  11525. SSLServer svr_;
  11526. #else
  11527. Client cli_;
  11528. Server svr_;
  11529. #endif
  11530. thread t_;
  11531. };
  11532. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11533. auto res = cli_.Post("/test", "123456789", "text/plain");
  11534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11535. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11536. res = cli_.Post("/test", "12345678", "text/plain");
  11537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11538. EXPECT_EQ(StatusCode::OK_200, res->status);
  11539. }
  11540. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11541. // Test chunked encoding with payload exceeding the 8-byte limit
  11542. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11543. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11545. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11546. }
  11547. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11548. // Test chunked encoding with payload within the 8-byte limit
  11549. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11550. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11552. EXPECT_EQ(StatusCode::OK_200, res->status);
  11553. }
  11554. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11555. // Test using send_request to send chunked data exceeding payload limit
  11556. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11557. "Host: " +
  11558. std::string(HOST) + ":" + std::to_string(PORT) +
  11559. "\r\n"
  11560. "Transfer-Encoding: chunked\r\n"
  11561. "Connection: close\r\n"
  11562. "\r\n"
  11563. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11564. "0123456789\r\n"
  11565. "0\r\n" // End chunk
  11566. "\r\n";
  11567. std::string response;
  11568. bool result = send_request(1, chunked_request, &response);
  11569. if (!result) {
  11570. // If send_request fails, it might be because the server closed the
  11571. // connection due to payload limit enforcement, which is acceptable
  11572. SUCCEED()
  11573. << "Server rejected oversized chunked request (connection closed)";
  11574. } else {
  11575. // If we got a response, check if it's an error response or connection was
  11576. // closed early Short response length indicates connection was closed due to
  11577. // payload limit
  11578. if (response.length() <= 10) {
  11579. SUCCEED() << "Server closed connection for oversized chunked request";
  11580. } else {
  11581. // Check for error status codes
  11582. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11583. response.find("Payload Too Large") != std::string::npos ||
  11584. response.find("400") != std::string::npos);
  11585. }
  11586. }
  11587. }
  11588. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11589. // Test request without Content-Length header exceeding payload limit
  11590. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11591. "Host: " +
  11592. std::string(HOST) + ":" +
  11593. std::to_string(PORT) +
  11594. "\r\n"
  11595. "Connection: close\r\n"
  11596. "\r\n";
  11597. // Add payload exceeding the 8-byte limit
  11598. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11599. request_without_content_length += large_payload;
  11600. std::string response;
  11601. bool result = send_request(1, request_without_content_length, &response);
  11602. if (!result) {
  11603. // If send_request fails, server likely closed connection due to payload
  11604. // limit
  11605. SUCCEED() << "Server rejected oversized request without Content-Length "
  11606. "(connection closed)";
  11607. } else {
  11608. // Check if server responded with error or closed connection early
  11609. if (response.length() <= 10) {
  11610. SUCCEED() << "Server closed connection for oversized request without "
  11611. "Content-Length";
  11612. } else {
  11613. // Check for error status codes
  11614. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11615. response.find("Payload Too Large") != std::string::npos ||
  11616. response.find("400") != std::string::npos);
  11617. }
  11618. }
  11619. }
  11620. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11621. // Test request without Content-Length header within payload limit
  11622. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11623. "Host: " +
  11624. std::string(HOST) + ":" +
  11625. std::to_string(PORT) +
  11626. "\r\n"
  11627. "Connection: close\r\n"
  11628. "\r\n";
  11629. // Add payload within the 8-byte limit
  11630. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11631. request_without_content_length += small_payload;
  11632. std::string response;
  11633. bool result = send_request(1, request_without_content_length, &response);
  11634. // For requests without Content-Length, the server may have different behavior
  11635. // The key is that it should not reject due to payload limit for small
  11636. // payloads
  11637. if (result) {
  11638. // Check for any HTTP response (success or error, but not connection closed)
  11639. if (response.length() > 10) {
  11640. SUCCEED()
  11641. << "Server processed request without Content-Length within limit";
  11642. } else {
  11643. // Short response might indicate connection closed, which is acceptable
  11644. SUCCEED() << "Server closed connection for request without "
  11645. "Content-Length (acceptable behavior)";
  11646. }
  11647. } else {
  11648. // Connection failure might be due to protocol requirements
  11649. SUCCEED() << "Connection issue with request without Content-Length "
  11650. "(environment-specific)";
  11651. }
  11652. }
  11653. class LargePayloadMaxLengthTest : public ::testing::Test {
  11654. protected:
  11655. LargePayloadMaxLengthTest()
  11656. : cli_(HOST, PORT)
  11657. #ifdef CPPHTTPLIB_SSL_ENABLED
  11658. ,
  11659. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11660. #endif
  11661. {
  11662. #ifdef CPPHTTPLIB_SSL_ENABLED
  11663. cli_.enable_server_certificate_verification(false);
  11664. #endif
  11665. }
  11666. virtual void SetUp() {
  11667. // Set 10MB payload limit
  11668. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11669. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11670. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11671. res.set_content("Large payload test", "text/plain");
  11672. });
  11673. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11674. svr_.wait_until_ready();
  11675. }
  11676. virtual void TearDown() {
  11677. svr_.stop();
  11678. t_.join();
  11679. }
  11680. #ifdef CPPHTTPLIB_SSL_ENABLED
  11681. SSLClient cli_;
  11682. SSLServer svr_;
  11683. #else
  11684. Client cli_;
  11685. Server svr_;
  11686. #endif
  11687. thread t_;
  11688. };
  11689. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11690. // Test chunked encoding with payload within 10MB limit
  11691. std::string medium_payload(5 * 1024 * 1024,
  11692. 'A'); // 5MB payload, within 10MB limit
  11693. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11695. EXPECT_EQ(StatusCode::OK_200, res->status);
  11696. }
  11697. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11698. // Test chunked encoding with payload exceeding 10MB limit
  11699. std::string large_payload(12 * 1024 * 1024,
  11700. 'B'); // 12MB payload, exceeds 10MB limit
  11701. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11702. // Server may either return 413 or close the connection
  11703. if (res) {
  11704. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11705. } else {
  11706. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11707. }
  11708. }
  11709. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11710. // Test request without Content-Length header within 10MB limit
  11711. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11712. "Host: " +
  11713. std::string(HOST) + ":" +
  11714. std::to_string(PORT) +
  11715. "\r\n"
  11716. "Connection: close\r\n"
  11717. "\r\n";
  11718. // Add 1MB payload (within 10MB limit)
  11719. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11720. request_without_content_length += medium_payload;
  11721. std::string response;
  11722. bool result = send_request(5, request_without_content_length, &response);
  11723. if (result) {
  11724. // Should get a proper HTTP response for payloads within limit
  11725. if (response.length() > 10) {
  11726. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11727. "10MB limit";
  11728. } else {
  11729. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11730. "Content-Length)";
  11731. }
  11732. } else {
  11733. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11734. }
  11735. }
  11736. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11737. // Test request without Content-Length header exceeding 10MB limit
  11738. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11739. "Host: " +
  11740. std::string(HOST) + ":" +
  11741. std::to_string(PORT) +
  11742. "\r\n"
  11743. "Connection: close\r\n"
  11744. "\r\n";
  11745. // Add 12MB payload (exceeds 10MB limit)
  11746. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11747. request_without_content_length += large_payload;
  11748. std::string response;
  11749. bool result = send_request(10, request_without_content_length, &response);
  11750. if (!result) {
  11751. // Server should close connection due to payload limit
  11752. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11753. "(connection closed)";
  11754. } else {
  11755. // Check for error response
  11756. if (response.length() <= 10) {
  11757. SUCCEED()
  11758. << "Server closed connection for 12MB request exceeding 10MB limit";
  11759. } else {
  11760. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11761. response.find("Payload Too Large") != std::string::npos ||
  11762. response.find("400") != std::string::npos);
  11763. }
  11764. }
  11765. }
  11766. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11767. Server svr;
  11768. svr.Get("/", [](const Request &, Response &res) {
  11769. // Claims far more than it sends, then drops the connection.
  11770. res.set_content_provider(size_t(1) << 41, "text/plain",
  11771. [](size_t, size_t, DataSink &sink) {
  11772. sink.write("abc", 3);
  11773. return false;
  11774. });
  11775. });
  11776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11777. auto se = detail::scope_exit([&] {
  11778. svr.stop();
  11779. thread.join();
  11780. ASSERT_FALSE(svr.is_running());
  11781. });
  11782. svr.wait_until_ready();
  11783. Client cli(HOST, PORT);
  11784. cli.set_payload_max_length(0);
  11785. EXPECT_FALSE(cli.Get("/"));
  11786. }
  11787. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11788. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11789. // path.
  11790. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11791. Server svr;
  11792. const size_t LIMIT = 64 * 1024; // 64KB
  11793. svr.set_payload_max_length(LIMIT);
  11794. size_t total = 0;
  11795. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11796. const ContentReader &content_reader) {
  11797. content_reader([&](const char * /*data*/, size_t len) {
  11798. total += len;
  11799. return true;
  11800. });
  11801. res.status = 200;
  11802. res.set_content("stream_ok", "text/plain");
  11803. });
  11804. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11805. auto se = detail::scope_exit([&] {
  11806. svr.stop();
  11807. thread.join();
  11808. ASSERT_FALSE(svr.is_running());
  11809. });
  11810. svr.wait_until_ready();
  11811. // Prepare 256KB raw data and gzip-compress it
  11812. std::string raw(256 * 1024, 'A');
  11813. std::string gz;
  11814. {
  11815. z_stream zs{};
  11816. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11817. Z_DEFAULT_STRATEGY);
  11818. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11819. zs.avail_in = static_cast<uInt>(raw.size());
  11820. char outbuf[4096];
  11821. int ret;
  11822. do {
  11823. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11824. zs.avail_out = sizeof(outbuf);
  11825. ret = deflate(&zs, Z_FINISH);
  11826. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11827. } while (ret != Z_STREAM_END);
  11828. deflateEnd(&zs);
  11829. }
  11830. Client cli(HOST, PORT);
  11831. cli.set_connection_timeout(std::chrono::seconds(5));
  11832. Headers headers = {{"Content-Encoding", "gzip"}};
  11833. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11834. "application/octet-stream");
  11835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11836. // Server must reject oversized decompressed payloads with 413.
  11837. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11838. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11839. EXPECT_LE(total, LIMIT);
  11840. }
  11841. #ifndef CPPHTTPLIB_SSL_ENABLED
  11842. // For a request with neither Content-Length nor Transfer-Encoding, the
  11843. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11844. // compressed wire bytes straight to the ContentReader without ever routing
  11845. // them through the decompressor, so payload_max_length_ only bounded the
  11846. // compressed size on the wire, not the decompressed size.
  11847. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11848. Server svr;
  11849. const size_t LIMIT = 64 * 1024; // 64KB
  11850. svr.set_payload_max_length(LIMIT);
  11851. size_t total = 0;
  11852. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11853. const ContentReader &content_reader) {
  11854. content_reader([&](const char * /*data*/, size_t len) {
  11855. total += len;
  11856. return true;
  11857. });
  11858. res.status = 200;
  11859. res.set_content("stream_ok", "text/plain");
  11860. });
  11861. auto port = svr.bind_to_any_port(HOST);
  11862. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11863. auto se = detail::scope_exit([&] {
  11864. svr.stop();
  11865. thread.join();
  11866. ASSERT_FALSE(svr.is_running());
  11867. });
  11868. svr.wait_until_ready();
  11869. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11870. // StreamingGzipDecompression test above.
  11871. std::string raw(256 * 1024, 'A');
  11872. std::string gz;
  11873. {
  11874. httplib::detail::gzip_compressor compressor;
  11875. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11876. [&](const char *chunk, size_t len) {
  11877. gz.append(chunk, len);
  11878. return true;
  11879. });
  11880. ASSERT_TRUE(result);
  11881. }
  11882. // Send the gzip body over raw TCP with neither Content-Length nor
  11883. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11884. // kicks in.
  11885. std::string req = "POST /stream HTTP/1.1\r\n"
  11886. "Host: " +
  11887. std::string(HOST) + ":" + std::to_string(port) +
  11888. "\r\n"
  11889. "Content-Encoding: gzip\r\n"
  11890. "Connection: close\r\n"
  11891. "\r\n" +
  11892. gz;
  11893. std::string response;
  11894. ASSERT_TRUE(send_request(5, req, &response, port));
  11895. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11896. EXPECT_LE(total, LIMIT);
  11897. }
  11898. #endif
  11899. #endif
  11900. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11901. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11902. // the payload must be passed through untouched instead of being rejected.
  11903. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11904. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11905. Server svr;
  11906. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11907. res.set_content(body, "image/jpeg");
  11908. res.set_header("Content-Encoding", "UTF-8");
  11909. });
  11910. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11911. res.set_content(body, "image/jpeg");
  11912. res.set_header("Content-Encoding", "identity");
  11913. });
  11914. svr.Post("/echo", [](const Request &req, Response &res) {
  11915. res.set_content(req.body, "image/jpeg");
  11916. });
  11917. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11918. auto se = detail::scope_exit([&] {
  11919. svr.stop();
  11920. t.join();
  11921. ASSERT_FALSE(svr.is_running());
  11922. });
  11923. svr.wait_until_ready();
  11924. Client cli(HOST, PORT);
  11925. {
  11926. auto res = cli.Get("/image");
  11927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11928. EXPECT_EQ(StatusCode::OK_200, res->status);
  11929. EXPECT_EQ(body, res->body);
  11930. }
  11931. {
  11932. auto res = cli.Get("/identity");
  11933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11934. EXPECT_EQ(StatusCode::OK_200, res->status);
  11935. EXPECT_EQ(body, res->body);
  11936. }
  11937. {
  11938. // The same applies to a request body reaching the server.
  11939. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11940. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11942. EXPECT_EQ(StatusCode::OK_200, res->status);
  11943. EXPECT_EQ(body, res->body);
  11944. }
  11945. }
  11946. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11947. // gzip-encoded response even when the build has no zlib support.
  11948. static const char GZIPPED_HELLO_WORLD[] = {
  11949. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11950. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11951. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11952. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11953. // A content coding is a whole token, not something the field value merely
  11954. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11955. // as "fibre" look like Brotli, and turned a multi-coding value like
  11956. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11957. // it was never meant to see.
  11958. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11959. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11960. Server svr;
  11961. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11962. res.set_content(body, "image/jpeg");
  11963. res.set_header("Content-Encoding", "fibre");
  11964. });
  11965. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11966. res.set_content(body, "image/jpeg");
  11967. res.set_header("Content-Encoding", "gzip, br");
  11968. });
  11969. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11970. res.set_content(body, "image/jpeg");
  11971. res.set_header("Content-Encoding", "x-zstd-ish");
  11972. });
  11973. auto port = svr.bind_to_any_port(HOST);
  11974. thread t = thread([&]() { svr.listen_after_bind(); });
  11975. auto se = detail::scope_exit([&] {
  11976. svr.stop();
  11977. t.join();
  11978. ASSERT_FALSE(svr.is_running());
  11979. });
  11980. svr.wait_until_ready();
  11981. Client cli(HOST, port);
  11982. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11983. auto res = cli.Get(path);
  11984. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11985. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11986. // Not a coding we recognize, so the payload comes back untouched
  11987. EXPECT_EQ(body, res->body) << path;
  11988. }
  11989. }
  11990. // A content coding cpp-httplib recognizes but was not built with must be
  11991. // reported as such. Handing the still-compressed payload back to the caller
  11992. // would silently corrupt it.
  11993. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11994. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11995. Server svr;
  11996. // "image/jpeg" keeps the server from applying a content coding of its own,
  11997. // so the hand-crafted Content-Encoding below survives.
  11998. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11999. res.set_content(gzipped, "image/jpeg");
  12000. res.set_header("Content-Encoding", "gzip");
  12001. });
  12002. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12003. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12004. res.set_content(gzipped, "image/jpeg");
  12005. res.set_header("Content-Encoding", "GZIP");
  12006. });
  12007. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12008. auto se = detail::scope_exit([&] {
  12009. svr.stop();
  12010. t.join();
  12011. ASSERT_FALSE(svr.is_running());
  12012. });
  12013. svr.wait_until_ready();
  12014. Client cli(HOST, PORT);
  12015. {
  12016. auto res = cli.Get("/gzipped");
  12017. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12019. EXPECT_EQ("Hello World!", res->body);
  12020. #else
  12021. ASSERT_FALSE(res);
  12022. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12023. #endif
  12024. }
  12025. {
  12026. // open_stream() must behave the same way.
  12027. auto handle = cli.open_stream("GET", "/gzipped");
  12028. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12029. ASSERT_TRUE(handle.is_valid());
  12030. std::string received;
  12031. char buf[256];
  12032. ssize_t n;
  12033. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12034. received.append(buf, static_cast<size_t>(n));
  12035. }
  12036. EXPECT_EQ("Hello World!", received);
  12037. #else
  12038. EXPECT_FALSE(handle.is_valid());
  12039. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12040. #endif
  12041. }
  12042. {
  12043. // A differently-cased coding must not be mistaken for an unknown one, or
  12044. // the body would be handed back still compressed.
  12045. auto res = cli.Get("/gzipped-uppercase");
  12046. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12048. EXPECT_EQ("Hello World!", res->body);
  12049. #else
  12050. ASSERT_FALSE(res);
  12051. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12052. #endif
  12053. }
  12054. }
  12055. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12056. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12057. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12058. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12059. // body a second time and appending a second Content-Encoding field line, so
  12060. // clients that decode one coding per listed value handed back raw gzip bytes.
  12061. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12062. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12063. Server svr;
  12064. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12065. // keeps the server from applying a coding of its own.
  12066. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12067. res.set_content(gzipped, "text/plain");
  12068. res.set_header("Content-Encoding", "gzip");
  12069. });
  12070. auto port = svr.bind_to_any_port(HOST);
  12071. thread t = thread([&]() { svr.listen_after_bind(); });
  12072. auto se = detail::scope_exit([&] {
  12073. svr.stop();
  12074. t.join();
  12075. ASSERT_FALSE(svr.is_running());
  12076. });
  12077. svr.wait_until_ready();
  12078. Client cli(HOST, port);
  12079. Headers headers = {{"Accept-Encoding", "gzip"}};
  12080. auto res = cli.Get("/pre-gzipped", headers);
  12081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12082. EXPECT_EQ(StatusCode::OK_200, res->status);
  12083. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12084. EXPECT_EQ("Hello World!", res->body);
  12085. }
  12086. // A chunked provider settles its coding where the headers are written and
  12087. // reuses it at write time. Both ends of that have to hold: a handler's own
  12088. // Content-Encoding suppresses the coding, and a response without one is still
  12089. // compressed as it always was.
  12090. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12091. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12092. const std::string plain = "Hello World! Hello World! Hello World!";
  12093. Server svr;
  12094. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12095. res.set_header("Content-Encoding", "gzip");
  12096. res.set_chunked_content_provider(
  12097. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12098. sink.write(gzipped.data(), gzipped.size());
  12099. sink.done();
  12100. return true;
  12101. });
  12102. });
  12103. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12104. res.set_chunked_content_provider(
  12105. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12106. sink.write(plain.data(), plain.size());
  12107. sink.done();
  12108. return true;
  12109. });
  12110. });
  12111. auto port = svr.bind_to_any_port(HOST);
  12112. thread t = thread([&]() { svr.listen_after_bind(); });
  12113. auto se = detail::scope_exit([&] {
  12114. svr.stop();
  12115. t.join();
  12116. ASSERT_FALSE(svr.is_running());
  12117. });
  12118. svr.wait_until_ready();
  12119. Client cli(HOST, port);
  12120. Headers headers = {{"Accept-Encoding", "gzip"}};
  12121. {
  12122. auto res = cli.Get("/pre-gzipped", headers);
  12123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12124. EXPECT_EQ(StatusCode::OK_200, res->status);
  12125. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12126. EXPECT_EQ("Hello World!", res->body);
  12127. }
  12128. {
  12129. auto res = cli.Get("/negotiated", headers);
  12130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12131. EXPECT_EQ(StatusCode::OK_200, res->status);
  12132. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12133. EXPECT_EQ(plain, res->body);
  12134. }
  12135. }
  12136. #endif
  12137. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12138. // the same message as the comma-joined one, so both have to be read the same
  12139. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12140. // single gzip coding, and a body the sender says was encoded twice was handed
  12141. // back after one pass, still compressed but presented as decoded.
  12142. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12143. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12144. Server svr;
  12145. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12146. res.set_content(body, "image/jpeg");
  12147. res.headers.emplace("Content-Encoding", "gzip");
  12148. res.headers.emplace("Content-Encoding", "gzip");
  12149. });
  12150. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12151. res.set_content(body, "image/jpeg");
  12152. res.set_header("Content-Encoding", "gzip, gzip");
  12153. });
  12154. auto port = svr.bind_to_any_port(HOST);
  12155. thread t = thread([&]() { svr.listen_after_bind(); });
  12156. auto se = detail::scope_exit([&] {
  12157. svr.stop();
  12158. t.join();
  12159. ASSERT_FALSE(svr.is_running());
  12160. });
  12161. svr.wait_until_ready();
  12162. Client cli(HOST, port);
  12163. // Two codings is not something cpp-httplib decodes, so both representations
  12164. // take the pass-through path rather than one of them being gunzipped once.
  12165. for (const char *path : {"/split", "/joined"}) {
  12166. auto res = cli.Get(path);
  12167. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12168. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12169. EXPECT_EQ(body, res->body) << path;
  12170. }
  12171. }
  12172. // Regression test for DoS vulnerability: a malicious server sending a response
  12173. // without Content-Length header must not cause unbounded memory consumption on
  12174. // the client side. The client should stop reading after a reasonable limit,
  12175. // similar to the server-side set_payload_max_length protection.
  12176. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12177. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12178. #ifndef _WIN32
  12179. signal(SIGPIPE, SIG_IGN);
  12180. #endif
  12181. auto server_thread = std::thread([] {
  12182. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12183. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12184. default_socket_options(srv);
  12185. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12186. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12187. sockaddr_in addr{};
  12188. addr.sin_family = AF_INET;
  12189. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12190. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12191. int opt = 1;
  12192. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12193. #ifdef _WIN32
  12194. reinterpret_cast<const char *>(&opt),
  12195. #else
  12196. &opt,
  12197. #endif
  12198. sizeof(opt));
  12199. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12200. ::listen(srv, 1);
  12201. sockaddr_in cli_addr{};
  12202. socklen_t cli_len = sizeof(cli_addr);
  12203. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12204. if (cli != INVALID_SOCKET) {
  12205. char buf[4096];
  12206. ::recv(cli, buf, sizeof(buf), 0);
  12207. // Malicious response: no Content-Length, no chunked encoding
  12208. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12209. "Connection: close\r\n"
  12210. "\r\n";
  12211. ::send(cli,
  12212. #ifdef _WIN32
  12213. static_cast<const char *>(response_header.c_str()),
  12214. static_cast<int>(response_header.size()),
  12215. #else
  12216. response_header.c_str(), response_header.size(),
  12217. #endif
  12218. 0);
  12219. // Send 10MB of data
  12220. std::string chunk(64 * 1024, 'A');
  12221. size_t total_sent = 0;
  12222. while (total_sent < MALICIOUS_DATA_SIZE) {
  12223. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12224. auto sent = ::send(cli,
  12225. #ifdef _WIN32
  12226. static_cast<const char *>(chunk.c_str()),
  12227. static_cast<int>(to_send),
  12228. #else
  12229. chunk.c_str(), to_send,
  12230. #endif
  12231. 0);
  12232. if (sent <= 0) break;
  12233. total_sent += static_cast<size_t>(sent);
  12234. }
  12235. detail::close_socket(cli);
  12236. }
  12237. detail::close_socket(srv);
  12238. });
  12239. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12240. size_t total_read = 0;
  12241. {
  12242. Client cli("127.0.0.1", PORT + 2);
  12243. cli.set_read_timeout(5, 0);
  12244. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12245. auto stream = cli.open_stream("GET", "/malicious");
  12246. ASSERT_TRUE(stream.is_valid());
  12247. char buffer[64 * 1024];
  12248. ssize_t n;
  12249. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12250. total_read += static_cast<size_t>(n);
  12251. }
  12252. } // StreamHandle and Client destroyed here, closing the socket
  12253. server_thread.join();
  12254. // With set_payload_max_length, the client must stop reading before consuming
  12255. // all 10MB. The read loop should be cut off at or near the configured limit.
  12256. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12257. << "Client read " << total_read << " bytes, exceeding the configured "
  12258. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12259. }
  12260. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12261. // the entire response body without truncation.
  12262. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12263. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12264. #ifndef _WIN32
  12265. signal(SIGPIPE, SIG_IGN);
  12266. #endif
  12267. auto server_thread = std::thread([] {
  12268. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12269. default_socket_options(srv);
  12270. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12271. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12272. sockaddr_in addr{};
  12273. addr.sin_family = AF_INET;
  12274. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12275. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12276. int opt = 1;
  12277. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12278. #ifdef _WIN32
  12279. reinterpret_cast<const char *>(&opt),
  12280. #else
  12281. &opt,
  12282. #endif
  12283. sizeof(opt));
  12284. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12285. ::listen(srv, 1);
  12286. sockaddr_in cli_addr{};
  12287. socklen_t cli_len = sizeof(cli_addr);
  12288. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12289. if (cli != INVALID_SOCKET) {
  12290. char buf[4096];
  12291. ::recv(cli, buf, sizeof(buf), 0);
  12292. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12293. "Connection: close\r\n"
  12294. "\r\n";
  12295. ::send(cli,
  12296. #ifdef _WIN32
  12297. static_cast<const char *>(response_header.c_str()),
  12298. static_cast<int>(response_header.size()),
  12299. #else
  12300. response_header.c_str(), response_header.size(),
  12301. #endif
  12302. 0);
  12303. std::string chunk(64 * 1024, 'A');
  12304. size_t total_sent = 0;
  12305. while (total_sent < DATA_SIZE) {
  12306. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12307. auto sent = ::send(cli,
  12308. #ifdef _WIN32
  12309. static_cast<const char *>(chunk.c_str()),
  12310. static_cast<int>(to_send),
  12311. #else
  12312. chunk.c_str(), to_send,
  12313. #endif
  12314. 0);
  12315. if (sent <= 0) break;
  12316. total_sent += static_cast<size_t>(sent);
  12317. }
  12318. #ifdef _WIN32
  12319. ::shutdown(cli, SD_SEND);
  12320. #else
  12321. ::shutdown(cli, SHUT_WR);
  12322. #endif
  12323. // Drain until the client closes its end, ensuring all data is delivered
  12324. char drain[1024];
  12325. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12326. detail::close_socket(cli);
  12327. }
  12328. detail::close_socket(srv);
  12329. });
  12330. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12331. size_t total_read = 0;
  12332. {
  12333. Client cli("127.0.0.1", PORT + 2);
  12334. cli.set_read_timeout(5, 0);
  12335. cli.set_payload_max_length(0); // 0 means no limit
  12336. auto stream = cli.open_stream("GET", "/data");
  12337. ASSERT_TRUE(stream.is_valid());
  12338. char buffer[64 * 1024];
  12339. ssize_t n;
  12340. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12341. total_read += static_cast<size_t>(n);
  12342. }
  12343. }
  12344. server_thread.join();
  12345. EXPECT_EQ(total_read, DATA_SIZE)
  12346. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12347. << " bytes without truncation, but only read " << total_read << " bytes.";
  12348. }
  12349. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12350. // enormous Content-Length must not cause the client to pre-allocate a huge
  12351. // response body buffer. The reservation is capped at payload_max_length_, and
  12352. // the read itself fails when the body exceeds the limit.
  12353. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12354. #ifndef _WIN32
  12355. signal(SIGPIPE, SIG_IGN);
  12356. #endif
  12357. auto server_thread = std::thread([] {
  12358. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12359. default_socket_options(srv);
  12360. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12361. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12362. sockaddr_in addr{};
  12363. addr.sin_family = AF_INET;
  12364. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12365. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12366. int opt = 1;
  12367. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12368. #ifdef _WIN32
  12369. reinterpret_cast<const char *>(&opt),
  12370. #else
  12371. &opt,
  12372. #endif
  12373. sizeof(opt));
  12374. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12375. ::listen(srv, 1);
  12376. sockaddr_in cli_addr{};
  12377. socklen_t cli_len = sizeof(cli_addr);
  12378. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12379. if (cli != INVALID_SOCKET) {
  12380. char buf[4096];
  12381. ::recv(cli, buf, sizeof(buf), 0);
  12382. // Malicious response: claim a 20GB body but send only a tiny payload.
  12383. std::string response = "HTTP/1.1 200 OK\r\n"
  12384. "Content-Length: 20000000000\r\n"
  12385. "\r\n"
  12386. "abc";
  12387. ::send(cli,
  12388. #ifdef _WIN32
  12389. static_cast<const char *>(response.c_str()),
  12390. static_cast<int>(response.size()),
  12391. #else
  12392. response.c_str(), response.size(),
  12393. #endif
  12394. 0);
  12395. detail::close_socket(cli);
  12396. }
  12397. detail::close_socket(srv);
  12398. });
  12399. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12400. {
  12401. Client cli("127.0.0.1", PORT + 2);
  12402. cli.set_read_timeout(5, 0);
  12403. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12404. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12405. // (server claims more bytes than payload_max_length permits), but it must
  12406. // not exhaust memory before getting there.
  12407. auto res = cli.Get("/malicious");
  12408. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12409. }
  12410. server_thread.join();
  12411. }
  12412. // Verify that content_receiver bypasses the default payload_max_length,
  12413. // allowing streaming downloads larger than 100MB without requiring an explicit
  12414. // set_payload_max_length call.
  12415. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12416. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12417. #ifndef _WIN32
  12418. signal(SIGPIPE, SIG_IGN);
  12419. #endif
  12420. auto server_thread = std::thread([] {
  12421. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12422. default_socket_options(srv);
  12423. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12424. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12425. sockaddr_in addr{};
  12426. addr.sin_family = AF_INET;
  12427. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12428. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12429. int opt = 1;
  12430. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12431. #ifdef _WIN32
  12432. reinterpret_cast<const char *>(&opt),
  12433. #else
  12434. &opt,
  12435. #endif
  12436. sizeof(opt));
  12437. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12438. ::listen(srv, 1);
  12439. sockaddr_in cli_addr{};
  12440. socklen_t cli_len = sizeof(cli_addr);
  12441. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12442. if (cli != INVALID_SOCKET) {
  12443. char buf[4096];
  12444. ::recv(cli, buf, sizeof(buf), 0);
  12445. // Response with Content-Length larger than default 100MB limit
  12446. auto content_length = std::to_string(DATA_SIZE);
  12447. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12448. "Content-Length: " +
  12449. content_length +
  12450. "\r\n"
  12451. "Connection: close\r\n"
  12452. "\r\n";
  12453. ::send(cli,
  12454. #ifdef _WIN32
  12455. static_cast<const char *>(response_header.c_str()),
  12456. static_cast<int>(response_header.size()),
  12457. #else
  12458. response_header.c_str(), response_header.size(),
  12459. #endif
  12460. 0);
  12461. std::string chunk(64 * 1024, 'A');
  12462. size_t total_sent = 0;
  12463. while (total_sent < DATA_SIZE) {
  12464. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12465. auto sent = ::send(cli,
  12466. #ifdef _WIN32
  12467. static_cast<const char *>(chunk.c_str()),
  12468. static_cast<int>(to_send),
  12469. #else
  12470. chunk.c_str(), to_send,
  12471. #endif
  12472. 0);
  12473. if (sent <= 0) break;
  12474. total_sent += static_cast<size_t>(sent);
  12475. }
  12476. detail::close_socket(cli);
  12477. }
  12478. detail::close_socket(srv);
  12479. });
  12480. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12481. size_t total_received = 0;
  12482. {
  12483. Client cli("127.0.0.1", PORT + 2);
  12484. cli.set_read_timeout(10, 0);
  12485. // Do NOT call set_payload_max_length — use the default 100MB limit
  12486. auto res =
  12487. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12488. total_received += data_length;
  12489. return true;
  12490. });
  12491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12492. EXPECT_EQ(StatusCode::OK_200, res->status);
  12493. }
  12494. server_thread.join();
  12495. EXPECT_EQ(total_received, DATA_SIZE)
  12496. << "With content_receiver, the client should read all " << DATA_SIZE
  12497. << " bytes despite the default 100MB payload_max_length, but only read "
  12498. << total_received << " bytes.";
  12499. }
  12500. // Verify that an explicit set_payload_max_length smaller than the response is
  12501. // enforced even when a content_receiver is used.
  12502. TEST(ClientVulnerabilityTest,
  12503. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12504. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12505. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12506. #ifndef _WIN32
  12507. signal(SIGPIPE, SIG_IGN);
  12508. #endif
  12509. auto server_thread = std::thread([] {
  12510. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12511. default_socket_options(srv);
  12512. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12513. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12514. sockaddr_in addr{};
  12515. addr.sin_family = AF_INET;
  12516. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12517. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12518. int opt = 1;
  12519. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12520. #ifdef _WIN32
  12521. reinterpret_cast<const char *>(&opt),
  12522. #else
  12523. &opt,
  12524. #endif
  12525. sizeof(opt));
  12526. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12527. ::listen(srv, 1);
  12528. sockaddr_in cli_addr{};
  12529. socklen_t cli_len = sizeof(cli_addr);
  12530. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12531. if (cli != INVALID_SOCKET) {
  12532. char buf[4096];
  12533. ::recv(cli, buf, sizeof(buf), 0);
  12534. auto content_length = std::to_string(DATA_SIZE);
  12535. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12536. "Content-Length: " +
  12537. content_length +
  12538. "\r\n"
  12539. "Connection: close\r\n"
  12540. "\r\n";
  12541. ::send(cli,
  12542. #ifdef _WIN32
  12543. static_cast<const char *>(response_header.c_str()),
  12544. static_cast<int>(response_header.size()),
  12545. #else
  12546. response_header.c_str(), response_header.size(),
  12547. #endif
  12548. 0);
  12549. std::string chunk(64 * 1024, 'A');
  12550. size_t total_sent = 0;
  12551. while (total_sent < DATA_SIZE) {
  12552. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12553. auto sent = ::send(cli,
  12554. #ifdef _WIN32
  12555. static_cast<const char *>(chunk.c_str()),
  12556. static_cast<int>(to_send),
  12557. #else
  12558. chunk.c_str(), to_send,
  12559. #endif
  12560. 0);
  12561. if (sent <= 0) break;
  12562. total_sent += static_cast<size_t>(sent);
  12563. }
  12564. detail::close_socket(cli);
  12565. }
  12566. detail::close_socket(srv);
  12567. });
  12568. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12569. size_t total_received = 0;
  12570. {
  12571. Client cli("127.0.0.1", PORT + 2);
  12572. cli.set_read_timeout(10, 0);
  12573. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12574. auto res =
  12575. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12576. total_received += data_length;
  12577. return true;
  12578. });
  12579. // Should fail because 200MB exceeds the explicit 150MB limit
  12580. EXPECT_FALSE(res);
  12581. }
  12582. server_thread.join();
  12583. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12584. << "Client with content_receiver should respect the explicit "
  12585. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12586. << total_received << " bytes.";
  12587. }
  12588. // Verify that an explicit set_payload_max_length larger than the response
  12589. // allows the content_receiver to read all data successfully.
  12590. TEST(ClientVulnerabilityTest,
  12591. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12592. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12593. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12594. #ifndef _WIN32
  12595. signal(SIGPIPE, SIG_IGN);
  12596. #endif
  12597. auto server_thread = std::thread([] {
  12598. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12599. default_socket_options(srv);
  12600. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12601. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12602. sockaddr_in addr{};
  12603. addr.sin_family = AF_INET;
  12604. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12605. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12606. int opt = 1;
  12607. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12608. #ifdef _WIN32
  12609. reinterpret_cast<const char *>(&opt),
  12610. #else
  12611. &opt,
  12612. #endif
  12613. sizeof(opt));
  12614. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12615. ::listen(srv, 1);
  12616. sockaddr_in cli_addr{};
  12617. socklen_t cli_len = sizeof(cli_addr);
  12618. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12619. if (cli != INVALID_SOCKET) {
  12620. char buf[4096];
  12621. ::recv(cli, buf, sizeof(buf), 0);
  12622. auto content_length = std::to_string(DATA_SIZE);
  12623. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12624. "Content-Length: " +
  12625. content_length +
  12626. "\r\n"
  12627. "Connection: close\r\n"
  12628. "\r\n";
  12629. ::send(cli,
  12630. #ifdef _WIN32
  12631. static_cast<const char *>(response_header.c_str()),
  12632. static_cast<int>(response_header.size()),
  12633. #else
  12634. response_header.c_str(), response_header.size(),
  12635. #endif
  12636. 0);
  12637. std::string chunk(64 * 1024, 'A');
  12638. size_t total_sent = 0;
  12639. while (total_sent < DATA_SIZE) {
  12640. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12641. auto sent = ::send(cli,
  12642. #ifdef _WIN32
  12643. static_cast<const char *>(chunk.c_str()),
  12644. static_cast<int>(to_send),
  12645. #else
  12646. chunk.c_str(), to_send,
  12647. #endif
  12648. 0);
  12649. if (sent <= 0) break;
  12650. total_sent += static_cast<size_t>(sent);
  12651. }
  12652. #ifdef _WIN32
  12653. ::shutdown(cli, SD_SEND);
  12654. #else
  12655. ::shutdown(cli, SHUT_WR);
  12656. #endif
  12657. char drain[1024];
  12658. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12659. detail::close_socket(cli);
  12660. }
  12661. detail::close_socket(srv);
  12662. });
  12663. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12664. size_t total_received = 0;
  12665. {
  12666. Client cli("127.0.0.1", PORT + 2);
  12667. cli.set_read_timeout(10, 0);
  12668. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12669. auto res =
  12670. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12671. total_received += data_length;
  12672. return true;
  12673. });
  12674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12675. EXPECT_EQ(StatusCode::OK_200, res->status);
  12676. }
  12677. server_thread.join();
  12678. EXPECT_EQ(total_received, DATA_SIZE)
  12679. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12680. << " bytes (larger than " << DATA_SIZE
  12681. << " bytes response), content_receiver should read all data, but only "
  12682. "read "
  12683. << total_received << " bytes.";
  12684. }
  12685. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12686. // Regression test for "zip bomb" attack on the client side: a malicious server
  12687. // sends a small gzip-compressed response that decompresses to a huge payload.
  12688. // The client must enforce payload_max_length on the decompressed size.
  12689. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12690. constexpr size_t DECOMPRESSED_SIZE =
  12691. 10 * 1024 * 1024; // 10MB after decompression
  12692. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12693. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12694. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12695. std::string compressed;
  12696. {
  12697. httplib::detail::gzip_compressor compressor;
  12698. bool ok =
  12699. compressor.compress(uncompressed.data(), uncompressed.size(),
  12700. /*last=*/true, [&](const char *buf, size_t len) {
  12701. compressed.append(buf, len);
  12702. return true;
  12703. });
  12704. ASSERT_TRUE(ok);
  12705. }
  12706. // Sanity: compressed data should be much smaller than the decompressed size
  12707. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12708. #ifndef _WIN32
  12709. signal(SIGPIPE, SIG_IGN);
  12710. #endif
  12711. // Set up the listening socket in the main thread so the server is guaranteed
  12712. // to be ready before the client connects (eliminates race condition).
  12713. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12714. default_socket_options(srv);
  12715. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12716. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12717. sockaddr_in addr{};
  12718. addr.sin_family = AF_INET;
  12719. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12720. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12721. int opt = 1;
  12722. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12723. #ifdef _WIN32
  12724. reinterpret_cast<const char *>(&opt),
  12725. #else
  12726. &opt,
  12727. #endif
  12728. sizeof(opt));
  12729. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12730. ASSERT_EQ(0, ::listen(srv, 1));
  12731. auto server_thread = std::thread([&compressed, srv] {
  12732. sockaddr_in cli_addr{};
  12733. socklen_t cli_len = sizeof(cli_addr);
  12734. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12735. if (cli != INVALID_SOCKET) {
  12736. // Read the full HTTP request (until \r\n\r\n)
  12737. char buf[4096];
  12738. size_t total = 0;
  12739. while (total < sizeof(buf)) {
  12740. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12741. if (n <= 0) break;
  12742. total += static_cast<size_t>(n);
  12743. // Check for end of headers
  12744. if (total >= 4) {
  12745. std::string req(buf, total);
  12746. if (req.find("\r\n\r\n") != std::string::npos) break;
  12747. }
  12748. }
  12749. // Malicious response: gzip-compressed body, no Content-Length
  12750. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12751. "Content-Encoding: gzip\r\n"
  12752. "Connection: close\r\n"
  12753. "\r\n";
  12754. ::send(cli,
  12755. #ifdef _WIN32
  12756. static_cast<const char *>(response_header.c_str()),
  12757. static_cast<int>(response_header.size()),
  12758. #else
  12759. response_header.c_str(), response_header.size(),
  12760. #endif
  12761. 0);
  12762. // Send the compressed payload (small on the wire, huge when decompressed)
  12763. size_t total_sent = 0;
  12764. while (total_sent < compressed.size()) {
  12765. auto to_send = std::min(compressed.size() - total_sent,
  12766. static_cast<size_t>(64 * 1024));
  12767. auto sent =
  12768. ::send(cli,
  12769. #ifdef _WIN32
  12770. static_cast<const char *>(compressed.c_str() + total_sent),
  12771. static_cast<int>(to_send),
  12772. #else
  12773. compressed.c_str() + total_sent, to_send,
  12774. #endif
  12775. 0);
  12776. if (sent <= 0) break;
  12777. total_sent += static_cast<size_t>(sent);
  12778. }
  12779. detail::close_socket(cli);
  12780. }
  12781. });
  12782. auto se = detail::scope_exit([&] {
  12783. detail::close_socket(srv);
  12784. server_thread.join();
  12785. });
  12786. size_t total_decompressed = 0;
  12787. {
  12788. Client cli("127.0.0.1", PORT + 3);
  12789. cli.set_read_timeout(5, 0);
  12790. cli.set_decompress(true);
  12791. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12792. auto stream = cli.open_stream("GET", "/zipbomb");
  12793. ASSERT_TRUE(stream.is_valid());
  12794. char buffer[64 * 1024];
  12795. ssize_t n;
  12796. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12797. total_decompressed += static_cast<size_t>(n);
  12798. }
  12799. }
  12800. // The decompressed size must be capped by payload_max_length. Without
  12801. // protection, the client would decompress the full 10MB from a tiny
  12802. // compressed payload, enabling a zip bomb DoS attack.
  12803. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12804. << "Client decompressed " << total_decompressed
  12805. << " bytes from a gzip response. The decompressed size should be "
  12806. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12807. }
  12808. #endif
  12809. TEST(HostAndPortPropertiesTest, NoSSL) {
  12810. httplib::Client cli("www.google.com", 1234);
  12811. ASSERT_EQ("www.google.com", cli.host());
  12812. ASSERT_EQ(1234, cli.port());
  12813. }
  12814. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12815. httplib::Client cli("www.google.com:1234");
  12816. ASSERT_EQ("www.google.com", cli.host());
  12817. ASSERT_EQ(1234, cli.port());
  12818. }
  12819. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12820. // Port number that overflows int — should not crash, client becomes invalid
  12821. httplib::Client cli("http://www.google.com:99999999999999999999");
  12822. ASSERT_FALSE(cli.is_valid());
  12823. }
  12824. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12825. // Port 99999 exceeds valid range (1-65535) — should not crash
  12826. httplib::Client cli("http://www.google.com:99999");
  12827. ASSERT_FALSE(cli.is_valid());
  12828. auto res = cli.Get("/");
  12829. EXPECT_FALSE(res);
  12830. EXPECT_EQ(Error::Connection, res.error());
  12831. }
  12832. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  12833. httplib::Client cli("http://user:pass@localhost:1234");
  12834. ASSERT_FALSE(cli.is_valid());
  12835. EXPECT_FALSE(cli.Get("/"));
  12836. }
  12837. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12838. httplib::Client cli("http://www.google.com:80abc");
  12839. ASSERT_FALSE(cli.is_valid());
  12840. }
  12841. #ifdef CPPHTTPLIB_SSL_ENABLED
  12842. TEST(HostAndPortPropertiesTest, SSL) {
  12843. httplib::SSLClient cli("www.google.com");
  12844. ASSERT_EQ("www.google.com", cli.host());
  12845. ASSERT_EQ(443, cli.port());
  12846. }
  12847. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12848. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12849. std::string cert;
  12850. read_file(CA_CERT_FILE, cert);
  12851. httplib::SSLClient httplib_client("www.google.com");
  12852. // Load CA store first time
  12853. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12854. // Load CA store second time (update)
  12855. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12856. // Verify client is still valid and can make connections
  12857. httplib_client.enable_server_certificate_verification(true);
  12858. auto res = httplib_client.Get("/");
  12859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12860. // Google may return 200 or 301 depending on various factors
  12861. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12862. res->status == StatusCode::MovedPermanently_301);
  12863. }
  12864. TEST(SSLClientTest, ServerNameIndication_Online) {
  12865. auto host = "httpbingo.org";
  12866. auto path = std::string{"/get"};
  12867. SSLClient cli(host, 443);
  12868. auto res = cli.Get(path);
  12869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12870. ASSERT_EQ(StatusCode::OK_200, res->status);
  12871. }
  12872. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12873. // Use a site that will cause SSL verification failure due to self-signed cert
  12874. SSLClient cli("self-signed.badssl.com", 443);
  12875. cli.enable_server_certificate_verification(true);
  12876. auto res = cli.Get("/");
  12877. ASSERT_TRUE(!res);
  12878. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12879. // Verify backend error is captured for SSLServerVerification
  12880. // This occurs when certificate verification fails
  12881. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12882. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12883. EXPECT_NE(0UL, res.ssl_backend_error());
  12884. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12885. // For OpenSSL, ssl_error is 0 for verification errors
  12886. EXPECT_EQ(0, res.ssl_error());
  12887. #if !defined(_WIN32) || \
  12888. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12889. // On non-Windows or when Windows Schannel is disabled, the error comes
  12890. // from OpenSSL's verification
  12891. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12892. res.ssl_backend_error());
  12893. #endif
  12894. #endif
  12895. }
  12896. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12897. // Use a site where hostname doesn't match the certificate
  12898. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12899. SSLClient cli("wrong.host.badssl.com", 443);
  12900. cli.enable_server_certificate_verification(true);
  12901. cli.enable_server_hostname_verification(true);
  12902. auto res = cli.Get("/");
  12903. ASSERT_TRUE(!res);
  12904. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12905. // Verify backend error is captured for hostname verification failure
  12906. EXPECT_NE(0UL, res.ssl_backend_error());
  12907. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12908. // For OpenSSL, ssl_error is 0 for verification errors
  12909. EXPECT_EQ(0, res.ssl_error());
  12910. #if !defined(_WIN32) || \
  12911. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12912. // On non-Windows or when Windows Schannel is disabled, the error comes
  12913. // from OpenSSL's hostname verification
  12914. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12915. res.ssl_backend_error());
  12916. #endif
  12917. #endif
  12918. }
  12919. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12920. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12921. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12922. SSLClient cli("www.google.com", 443);
  12923. cli.enable_server_certificate_verification(true);
  12924. auto res = cli.Get("/");
  12925. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12926. }
  12927. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12928. SSLClient cli("www.google.com", 443);
  12929. cli.enable_server_certificate_verification(true);
  12930. cli.enable_windows_certificate_verification(false);
  12931. auto res = cli.Get("/");
  12932. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12933. }
  12934. // The server sends an intermediate cross-signed by a root Windows trusts,
  12935. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12936. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12937. SSLClient cli("accounts.spotify.com", 443);
  12938. auto res = cli.Get("/");
  12939. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12940. << " ssl_backend_error=" << res.ssl_backend_error();
  12941. }
  12942. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12943. // policy status, which no backend reports for a self-signed certificate.
  12944. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12945. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12946. ASSERT_TRUE(svr.is_valid());
  12947. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12948. auto se = detail::scope_exit([&] {
  12949. svr.stop();
  12950. t.join();
  12951. ASSERT_FALSE(svr.is_running());
  12952. });
  12953. svr.wait_until_ready();
  12954. SSLClient cli("127.0.0.1", PORT);
  12955. cli.set_connection_timeout(30);
  12956. auto res = cli.Get("/");
  12957. ASSERT_FALSE(res);
  12958. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12959. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12960. }
  12961. #endif
  12962. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12963. Client cli("https://google.com");
  12964. auto res = cli.Get("/");
  12965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12966. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12967. }
  12968. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12969. SSLClient cli("google.com");
  12970. cli.set_ca_cert_path(CA_CERT_FILE);
  12971. auto res = cli.Get("/");
  12972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12973. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12974. }
  12975. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12976. SSLClient cli("google.com");
  12977. cli.enable_server_certificate_verification(true);
  12978. cli.set_ca_cert_path("hello");
  12979. auto res = cli.Get("/");
  12980. ASSERT_TRUE(!res);
  12981. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12982. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12983. // should be set
  12984. EXPECT_EQ(0, res.ssl_error());
  12985. // Verify backend error is captured for SSLLoadingCerts
  12986. // This error occurs when loading CA certificates fails
  12987. EXPECT_NE(0UL, res.ssl_backend_error());
  12988. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12989. // OpenSSL specific error codes:
  12990. // > openssl errstr 0x80000002
  12991. // error:80000002:system library::No such file or directory
  12992. // > openssl errstr 0xA000126
  12993. // error:0A000126:SSL routines::unexpected eof while reading
  12994. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12995. res.ssl_backend_error() == 0xA000126);
  12996. #endif
  12997. }
  12998. TEST(SSLClientTest, ServerCertificateVerification4) {
  12999. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13000. ASSERT_TRUE(svr.is_valid());
  13001. svr.Get("/test", [&](const Request &, Response &res) {
  13002. res.set_content("test", "text/plain");
  13003. svr.stop();
  13004. ASSERT_TRUE(true);
  13005. });
  13006. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13007. auto se = detail::scope_exit([&] {
  13008. t.join();
  13009. ASSERT_FALSE(svr.is_running());
  13010. });
  13011. svr.wait_until_ready();
  13012. SSLClient cli("127.0.0.1", PORT);
  13013. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13014. cli.enable_server_certificate_verification(true);
  13015. cli.set_connection_timeout(30);
  13016. auto res = cli.Get("/test");
  13017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13018. ASSERT_EQ(StatusCode::OK_200, res->status);
  13019. }
  13020. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13021. std::string cert;
  13022. read_file(CA_CERT_FILE, cert);
  13023. SSLClient cli("google.com");
  13024. cli.load_ca_cert_store(cert.data(), cert.size());
  13025. const auto res = cli.Get("/");
  13026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13027. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13028. }
  13029. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13030. // clang-format off
  13031. static constexpr char cert[] =
  13032. "GlobalSign Root CA\n"
  13033. "==================\n"
  13034. "-----BEGIN CERTIFICATE-----\n"
  13035. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13036. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13037. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13038. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13039. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13040. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13041. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13042. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13043. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13044. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13045. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13046. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13047. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13048. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13049. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13050. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13051. "-----END CERTIFICATE-----\n";
  13052. // clang-format on
  13053. SSLClient cli("google.com");
  13054. cli.load_ca_cert_store(cert, sizeof(cert));
  13055. const auto res = cli.Get("/");
  13056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13057. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13058. }
  13059. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13060. SSLClient cli("www.youtube.com");
  13061. cli.set_ca_cert_path(CA_CERT_FILE);
  13062. cli.enable_server_certificate_verification(true);
  13063. cli.set_follow_location(true);
  13064. auto res = cli.Get("/");
  13065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13066. ASSERT_EQ(StatusCode::OK_200, res->status);
  13067. }
  13068. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13069. SSLClient cli("wWw.YouTube.Com");
  13070. cli.set_ca_cert_path(CA_CERT_FILE);
  13071. cli.enable_server_certificate_verification(true);
  13072. cli.enable_server_hostname_verification(true);
  13073. cli.set_follow_location(true);
  13074. auto res = cli.Get("/");
  13075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13076. ASSERT_EQ(StatusCode::OK_200, res->status);
  13077. }
  13078. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13079. SSLClient cli("gOoGlE.COm");
  13080. cli.enable_server_certificate_verification(true);
  13081. cli.enable_server_hostname_verification(true);
  13082. cli.set_follow_location(true);
  13083. auto res = cli.Get("/");
  13084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13085. ASSERT_EQ(StatusCode::OK_200, res->status);
  13086. }
  13087. TEST(SSLClientTest, Issue2004_Online) {
  13088. Client client("https://google.com");
  13089. client.set_follow_location(true);
  13090. auto res = client.Get("/");
  13091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13092. ASSERT_EQ(StatusCode::OK_200, res->status);
  13093. auto body = res->body;
  13094. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13095. }
  13096. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13097. // Create SSLClient with invalid cert/key to make is_valid() return false
  13098. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13099. "nonexistent_key.pem");
  13100. // is_valid() should be false due to cert loading failure
  13101. ASSERT_FALSE(cli.is_valid());
  13102. auto res = cli.Get("/");
  13103. ASSERT_FALSE(res);
  13104. EXPECT_EQ(Error::SSLConnection, res.error());
  13105. }
  13106. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13107. // Test for Issue #2251: SSL error not properly reported when client cert
  13108. // and key paths are swapped or mismatched
  13109. // This simulates the scenario where user accidentally swaps the cert and key
  13110. // files
  13111. // Using client cert file as private key and vice versa (completely wrong)
  13112. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13113. // Should fail validation due to cert/key mismatch
  13114. ASSERT_FALSE(cli.is_valid());
  13115. // Attempt to make a request should fail with proper error
  13116. auto res = cli.Get("/");
  13117. ASSERT_FALSE(res);
  13118. EXPECT_EQ(Error::SSLConnection, res.error());
  13119. // SSL error should be recorded in the Result object (this is the key fix for
  13120. // Issue #2251)
  13121. auto backend_error = res.ssl_backend_error();
  13122. EXPECT_NE(0u, backend_error);
  13123. }
  13124. // Tests cert/key mismatch detection at the TLS context level
  13125. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13126. // Test that using mismatched cert/key causes connection failure.
  13127. // We verify this at the SSLClient level rather than through internal
  13128. // TLS API functions.
  13129. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13130. cli.enable_server_certificate_verification(false);
  13131. cli.set_connection_timeout(2);
  13132. // The mismatch should cause a connection or handshake error
  13133. auto res = cli.Get("/test");
  13134. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13135. // Either way, the request should fail
  13136. EXPECT_FALSE(res);
  13137. }
  13138. #endif
  13139. #if 0
  13140. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13141. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13142. ASSERT_TRUE(cli != nullptr);
  13143. cli->set_address_family(AF_INET6);
  13144. cli->set_interface("en0");
  13145. auto res = cli->Get("/get");
  13146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13147. ASSERT_EQ(StatusCode::OK_200, res->status);
  13148. }
  13149. #endif
  13150. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13151. #ifdef CPPHTTPLIB_SSL_ENABLED
  13152. void ClientCertPresent(
  13153. const std::string &client_cert_file,
  13154. const std::string &client_private_key_file,
  13155. const std::string &client_encrypted_private_key_pass = std::string()) {
  13156. using namespace httplib::tls;
  13157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13158. CLIENT_CA_CERT_DIR);
  13159. ASSERT_TRUE(svr.is_valid());
  13160. svr.Get("/test", [&](const Request &req, Response &res) {
  13161. res.set_content("test", "text/plain");
  13162. auto cert = req.peer_cert();
  13163. ASSERT_TRUE(static_cast<bool>(cert));
  13164. std::string common_name = cert.subject_cn();
  13165. EXPECT_EQ("Common Name", common_name);
  13166. });
  13167. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13168. auto se = detail::scope_exit([&] {
  13169. svr.stop();
  13170. t.join();
  13171. ASSERT_FALSE(svr.is_running());
  13172. });
  13173. svr.wait_until_ready();
  13174. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13175. client_encrypted_private_key_pass);
  13176. cli.enable_server_certificate_verification(false);
  13177. cli.set_connection_timeout(30);
  13178. auto res = cli.Get("/test");
  13179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13180. ASSERT_EQ(StatusCode::OK_200, res->status);
  13181. }
  13182. TEST(SSLClientServerTest, ClientCertPresent) {
  13183. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13184. }
  13185. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13186. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13187. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13188. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13189. }
  13190. // PEM memory-based constructor tests (works with all TLS backends)
  13191. void PemMemoryClientCertPresent(
  13192. const std::string &client_cert_file,
  13193. const std::string &client_private_key_file,
  13194. const std::string &client_encrypted_private_key_pass = std::string()) {
  13195. // Read PEM files into memory
  13196. std::string server_cert_pem, server_key_pem;
  13197. std::string client_ca_pem;
  13198. std::string client_cert_pem, client_key_pem;
  13199. read_file(SERVER_CERT_FILE, server_cert_pem);
  13200. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13201. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13202. read_file(client_cert_file, client_cert_pem);
  13203. read_file(client_private_key_file, client_key_pem);
  13204. // Create server with PEM memory
  13205. SSLServer::PemMemory server_pem = {
  13206. server_cert_pem.c_str(),
  13207. server_cert_pem.size(),
  13208. server_key_pem.c_str(),
  13209. server_key_pem.size(),
  13210. client_ca_pem.c_str(),
  13211. client_ca_pem.size(),
  13212. nullptr // no password for server key
  13213. };
  13214. SSLServer svr(server_pem);
  13215. ASSERT_TRUE(svr.is_valid());
  13216. svr.Get("/test", [&](const Request &, Response &res) {
  13217. res.set_content("test", "text/plain");
  13218. });
  13219. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13220. auto se = detail::scope_exit([&] {
  13221. svr.stop();
  13222. t.join();
  13223. ASSERT_FALSE(svr.is_running());
  13224. });
  13225. svr.wait_until_ready();
  13226. // Create client with PEM memory
  13227. const char *password = client_encrypted_private_key_pass.empty()
  13228. ? nullptr
  13229. : client_encrypted_private_key_pass.c_str();
  13230. SSLClient::PemMemory client_pem = {
  13231. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13232. client_key_pem.size(), password};
  13233. SSLClient cli(HOST, PORT, client_pem);
  13234. cli.enable_server_certificate_verification(false);
  13235. cli.set_connection_timeout(30);
  13236. auto res = cli.Get("/test");
  13237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13238. ASSERT_EQ(StatusCode::OK_200, res->status);
  13239. }
  13240. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13241. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13242. }
  13243. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13244. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13245. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13246. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13247. }
  13248. TEST(SSLClientServerTest, ClientCertMissing) {
  13249. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13250. CLIENT_CA_CERT_DIR);
  13251. ASSERT_TRUE(svr.is_valid());
  13252. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13253. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13254. auto se = detail::scope_exit([&] {
  13255. svr.stop();
  13256. t.join();
  13257. ASSERT_FALSE(svr.is_running());
  13258. });
  13259. svr.wait_until_ready();
  13260. SSLClient cli(HOST, PORT);
  13261. cli.set_connection_timeout(30);
  13262. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13263. // the chain check on Windows, so the result does not depend on the order.
  13264. cli.enable_server_hostname_verification(false);
  13265. auto res = cli.Get("/test");
  13266. ASSERT_TRUE(!res);
  13267. // When client cert is missing and server requires it, connection fails
  13268. // Error type depends on backend implementation
  13269. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13270. res.error() == Error::SSLConnection);
  13271. // Verify backend error is captured
  13272. // Note: This test may have different error codes depending on the exact
  13273. // verification failure
  13274. EXPECT_NE(0UL, res.ssl_backend_error());
  13275. }
  13276. TEST(SSLClientServerTest, TrustDirOptional) {
  13277. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13278. ASSERT_TRUE(svr.is_valid());
  13279. svr.Get("/test", [&](const Request &, Response &res) {
  13280. res.set_content("test", "text/plain");
  13281. });
  13282. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13283. auto se = detail::scope_exit([&] {
  13284. svr.stop();
  13285. t.join();
  13286. ASSERT_FALSE(svr.is_running());
  13287. });
  13288. svr.wait_until_ready();
  13289. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13290. cli.enable_server_certificate_verification(false);
  13291. cli.set_connection_timeout(30);
  13292. auto res = cli.Get("/test");
  13293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13294. ASSERT_EQ(StatusCode::OK_200, res->status);
  13295. }
  13296. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13297. class NoListenSSLServer : public SSLServer {
  13298. public:
  13299. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13300. const char *client_ca_cert_file_path,
  13301. const char *client_ca_cert_dir_path = nullptr)
  13302. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13303. client_ca_cert_dir_path),
  13304. stop_(false) {}
  13305. std::atomic_bool stop_;
  13306. private:
  13307. bool process_and_close_socket(socket_t /*sock*/) override {
  13308. // Don't create SSL context
  13309. while (!stop_.load()) {
  13310. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13311. }
  13312. return true;
  13313. }
  13314. };
  13315. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13316. CLIENT_CA_CERT_FILE);
  13317. ASSERT_TRUE(svr.is_valid());
  13318. svr.Get("/test", [&](const Request &, Response &res) {
  13319. res.set_content("test", "text/plain");
  13320. });
  13321. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13322. auto se = detail::scope_exit([&] {
  13323. svr.stop_ = true;
  13324. svr.stop();
  13325. t.join();
  13326. ASSERT_FALSE(svr.is_running());
  13327. });
  13328. svr.wait_until_ready();
  13329. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13330. cli.enable_server_certificate_verification(false);
  13331. cli.set_connection_timeout(1);
  13332. auto res = cli.Get("/test");
  13333. ASSERT_TRUE(!res);
  13334. EXPECT_EQ(Error::SSLConnection, res.error());
  13335. // Timeout results in WantRead error code (maps to backend-specific value)
  13336. EXPECT_NE(0, res.ssl_error());
  13337. }
  13338. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13339. // Test SSLServer with client certificate verification using the standard
  13340. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13342. CLIENT_CA_CERT_DIR);
  13343. ASSERT_TRUE(svr.is_valid());
  13344. svr.Get("/test", [&](const Request &req, Response &res) {
  13345. res.set_content("test", "text/plain");
  13346. auto cert = req.peer_cert();
  13347. ASSERT_TRUE(static_cast<bool>(cert));
  13348. auto common_name = cert.subject_cn();
  13349. EXPECT_EQ("Common Name", common_name);
  13350. });
  13351. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13352. auto se = detail::scope_exit([&] {
  13353. svr.stop();
  13354. t.join();
  13355. ASSERT_FALSE(svr.is_running());
  13356. });
  13357. svr.wait_until_ready();
  13358. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13359. cli.enable_server_certificate_verification(false);
  13360. cli.set_connection_timeout(30);
  13361. auto res = cli.Get("/test");
  13362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13363. ASSERT_EQ(StatusCode::OK_200, res->status);
  13364. }
  13365. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13366. // Verifies that wildcard matching and exact matching work consistently
  13367. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13368. using namespace httplib::tls;
  13369. // We need a running server to test against
  13370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13371. ASSERT_TRUE(svr.is_valid());
  13372. svr.Get("/test", [](const Request &, Response &res) {
  13373. res.set_content("ok", "text/plain");
  13374. });
  13375. thread t([&]() { svr.listen(HOST, PORT); });
  13376. auto se = detail::scope_exit([&] {
  13377. svr.stop();
  13378. t.join();
  13379. });
  13380. svr.wait_until_ready();
  13381. bool verify_callback_called = false;
  13382. bool verify_result_wrong = false;
  13383. SSLClient cli(HOST, PORT);
  13384. cli.enable_server_certificate_verification(true);
  13385. cli.set_ca_cert_path(CA_CERT_FILE);
  13386. cli.set_connection_timeout(5);
  13387. // Note: Test certificate has CN="Common Name", not "localhost"
  13388. bool verify_result_cn = false;
  13389. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13390. verify_callback_called = true;
  13391. if (!ctx.cert) return false;
  13392. // Test 1: "Common Name" should match (our test server cert CN)
  13393. verify_result_cn = ctx.check_hostname("Common Name");
  13394. // Test 2: wrong hostname should not match
  13395. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13396. return true; // Accept for the purpose of this test
  13397. });
  13398. auto res = cli.Get("/test");
  13399. // The request may succeed or fail depending on cert configuration
  13400. // but the callback should have been called
  13401. ASSERT_TRUE(verify_callback_called)
  13402. << "Verify callback should have been called";
  13403. // CN="Common Name" should match our test certificate
  13404. //
  13405. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13406. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13407. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13408. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13409. // <openssl/base.h>, which is included transitively when
  13410. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13411. #if defined(OPENSSL_IS_BORINGSSL)
  13412. EXPECT_FALSE(verify_result_cn)
  13413. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13414. #else
  13415. EXPECT_TRUE(verify_result_cn)
  13416. << "verify_hostname should match 'Common Name' (certificate CN)";
  13417. #endif
  13418. // Wrong hostname should not match
  13419. EXPECT_FALSE(verify_result_wrong)
  13420. << "verify_hostname should not match 'wronghost.example.com'";
  13421. }
  13422. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13423. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13424. // X509_check_ip behavior and must hold for every backend.
  13425. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13426. using namespace httplib::tls;
  13427. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13428. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13429. ASSERT_TRUE(svr.is_valid());
  13430. svr.Get("/test", [](const Request &, Response &res) {
  13431. res.set_content("ok", "text/plain");
  13432. });
  13433. thread t([&]() { svr.listen(HOST, PORT); });
  13434. auto se = detail::scope_exit([&] {
  13435. svr.stop();
  13436. t.join();
  13437. });
  13438. svr.wait_until_ready();
  13439. bool verify_callback_called = false;
  13440. bool ip_matched_via_cn = true;
  13441. SSLClient cli(HOST, PORT);
  13442. cli.enable_server_certificate_verification(true);
  13443. cli.set_ca_cert_path(CA_CERT_FILE);
  13444. cli.set_connection_timeout(5);
  13445. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13446. verify_callback_called = true;
  13447. if (!ctx.cert) return false;
  13448. // The IP appears only in the CN, so it must NOT be accepted.
  13449. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13450. return true; // Accept for the purpose of this test
  13451. });
  13452. cli.Get("/test");
  13453. ASSERT_TRUE(verify_callback_called)
  13454. << "Verify callback should have been called";
  13455. EXPECT_FALSE(ip_matched_via_cn)
  13456. << "An IP host must not be authenticated via the certificate CN";
  13457. }
  13458. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13459. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13460. using namespace httplib::tls;
  13461. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13462. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13463. ASSERT_TRUE(svr.is_valid());
  13464. svr.Get("/test", [](const Request &, Response &res) {
  13465. res.set_content("ok", "text/plain");
  13466. });
  13467. thread t([&]() { svr.listen(HOST, PORT); });
  13468. auto se = detail::scope_exit([&] {
  13469. svr.stop();
  13470. t.join();
  13471. });
  13472. svr.wait_until_ready();
  13473. bool verify_callback_called = false;
  13474. bool san_matched = false;
  13475. bool wrong_ipv6_matched = true;
  13476. bool cn_ipv6_matched = true;
  13477. SSLClient cli(HOST, PORT);
  13478. cli.enable_server_certificate_verification(true);
  13479. cli.set_ca_cert_path(CA_CERT_FILE);
  13480. cli.set_connection_timeout(5);
  13481. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13482. verify_callback_called = true;
  13483. if (!ctx.cert) return false;
  13484. // Matches the IPv6 iPAddress SAN.
  13485. san_matched = ctx.check_hostname("2001:db8::1");
  13486. // A different IPv6 address must not match.
  13487. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13488. // "::1" lives only in the CN, so it must not be accepted.
  13489. cn_ipv6_matched = ctx.check_hostname("::1");
  13490. return true; // Accept for the purpose of this test
  13491. });
  13492. cli.Get("/test");
  13493. ASSERT_TRUE(verify_callback_called)
  13494. << "Verify callback should have been called";
  13495. EXPECT_TRUE(san_matched)
  13496. << "verify_hostname should match an IPv6 iPAddress SAN";
  13497. EXPECT_FALSE(wrong_ipv6_matched)
  13498. << "verify_hostname should not match a non-matching IPv6 address";
  13499. EXPECT_FALSE(cn_ipv6_matched)
  13500. << "An IPv6 host must not be authenticated via the certificate CN";
  13501. }
  13502. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13503. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13504. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13505. using namespace httplib::tls;
  13506. // SANs: DNS:a.zz, IP:42.46.122.122
  13507. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13508. ASSERT_TRUE(svr.is_valid());
  13509. svr.Get("/test", [](const Request &, Response &res) {
  13510. res.set_content("ok", "text/plain");
  13511. });
  13512. auto port = svr.bind_to_any_port(HOST);
  13513. thread t([&]() { svr.listen_after_bind(); });
  13514. auto se = detail::scope_exit([&] {
  13515. svr.stop();
  13516. t.join();
  13517. });
  13518. svr.wait_until_ready();
  13519. bool verify_callback_called = false;
  13520. bool dns_san_matched = false;
  13521. bool ip_san_matched = false;
  13522. bool ip_matched_via_dns_san = true;
  13523. bool dns_matched_via_ip_san = true;
  13524. SSLClient cli(HOST, port);
  13525. cli.enable_server_certificate_verification(true);
  13526. cli.set_ca_cert_path(CA_CERT_FILE);
  13527. cli.set_connection_timeout(5);
  13528. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13529. verify_callback_called = true;
  13530. if (!ctx.cert) return false;
  13531. dns_san_matched = ctx.check_hostname("a.zz");
  13532. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13533. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13534. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13535. return true; // Accept for the purpose of this test
  13536. });
  13537. cli.Get("/test");
  13538. ASSERT_TRUE(verify_callback_called)
  13539. << "Verify callback should have been called";
  13540. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13541. EXPECT_TRUE(ip_san_matched)
  13542. << "verify_hostname should match an iPAddress SAN";
  13543. EXPECT_FALSE(ip_matched_via_dns_san)
  13544. << "An IP host must not be authenticated via a dNSName SAN";
  13545. EXPECT_FALSE(dns_matched_via_ip_san)
  13546. << "A DNS host must not be authenticated via an iPAddress SAN";
  13547. }
  13548. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13549. // "www.*.example.test" names one host and not every host under example.test.
  13550. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13551. using namespace httplib::tls;
  13552. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13553. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13554. ASSERT_TRUE(svr.is_valid());
  13555. svr.Get("/test", [](const Request &, Response &res) {
  13556. res.set_content("ok", "text/plain");
  13557. });
  13558. auto port = svr.bind_to_any_port(HOST);
  13559. thread t([&]() { svr.listen_after_bind(); });
  13560. auto se = detail::scope_exit([&] {
  13561. svr.stop();
  13562. t.join();
  13563. });
  13564. svr.wait_until_ready();
  13565. bool verify_callback_called = false;
  13566. bool leftmost_wildcard_matched = false;
  13567. bool wildcard_spanned_labels = true;
  13568. bool inner_wildcard_matched = true;
  13569. SSLClient cli(HOST, port);
  13570. cli.enable_server_certificate_verification(true);
  13571. cli.set_ca_cert_path(CA_CERT_FILE);
  13572. cli.set_connection_timeout(5);
  13573. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13574. verify_callback_called = true;
  13575. if (!ctx.cert) return false;
  13576. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13577. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13578. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13579. return true; // Accept for the purpose of this test
  13580. });
  13581. cli.Get("/test");
  13582. ASSERT_TRUE(verify_callback_called)
  13583. << "Verify callback should have been called";
  13584. EXPECT_TRUE(leftmost_wildcard_matched)
  13585. << "A leftmost wildcard should match a single label";
  13586. EXPECT_FALSE(wildcard_spanned_labels)
  13587. << "A wildcard label must not match more than one label";
  13588. EXPECT_FALSE(inner_wildcard_matched)
  13589. << "A wildcard outside the leftmost label must not be honoured";
  13590. }
  13591. // sans() must report each SAN entry under its own type.
  13592. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13593. using namespace httplib::tls;
  13594. // SANs: DNS:a.zz, IP:42.46.122.122
  13595. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13596. ASSERT_TRUE(svr.is_valid());
  13597. svr.Get("/test", [](const Request &, Response &res) {
  13598. res.set_content("ok", "text/plain");
  13599. });
  13600. auto port = svr.bind_to_any_port(HOST);
  13601. thread t([&]() { svr.listen_after_bind(); });
  13602. auto se = detail::scope_exit([&] {
  13603. svr.stop();
  13604. t.join();
  13605. });
  13606. svr.wait_until_ready();
  13607. bool verify_callback_called = false;
  13608. std::vector<SanEntry> sans;
  13609. SSLClient cli(HOST, port);
  13610. cli.enable_server_certificate_verification(true);
  13611. cli.set_ca_cert_path(CA_CERT_FILE);
  13612. cli.set_connection_timeout(5);
  13613. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13614. verify_callback_called = true;
  13615. if (!ctx.cert) return false;
  13616. sans = ctx.sans();
  13617. return true; // Accept for the purpose of this test
  13618. });
  13619. cli.Get("/test");
  13620. ASSERT_TRUE(verify_callback_called)
  13621. << "Verify callback should have been called";
  13622. auto has_san = [&](SanType type, const std::string &value) {
  13623. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13624. return san.type == type && san.value == value;
  13625. });
  13626. };
  13627. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13628. << "sans() should report the dNSName SAN";
  13629. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13630. << "sans() should report the iPAddress SAN";
  13631. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13632. << "sans() must not report the dNSName SAN as an address";
  13633. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13634. << "sans() must not report the iPAddress SAN as a DNS name";
  13635. }
  13636. #endif
  13637. // mbedTLS-specific callback constructor test
  13638. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13639. #ifdef CPPHTTPLIB_SSL_ENABLED
  13640. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13642. ASSERT_TRUE(svr.is_valid());
  13643. // Set up a handler to verify client certificate is present
  13644. bool client_cert_verified = false;
  13645. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13646. // Verify that client certificate was provided
  13647. client_cert_verified = true;
  13648. res.set_content("success", "text/plain");
  13649. });
  13650. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13651. auto se = detail::scope_exit([&] {
  13652. svr.stop();
  13653. t.join();
  13654. ASSERT_FALSE(svr.is_running());
  13655. });
  13656. svr.wait_until_ready();
  13657. // Client with certificate
  13658. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13659. cli.enable_server_certificate_verification(false);
  13660. cli.set_connection_timeout(30);
  13661. auto res = cli.Get("/test");
  13662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13663. ASSERT_EQ(StatusCode::OK_200, res->status);
  13664. ASSERT_TRUE(client_cert_verified);
  13665. EXPECT_EQ("success", res->body);
  13666. }
  13667. #endif
  13668. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13669. // backends
  13670. #ifdef CPPHTTPLIB_SSL_ENABLED
  13671. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13672. using namespace httplib::tls;
  13673. // Test that when client CA cert file is provided,
  13674. // the server properly requests and validates client certificates
  13675. // Create a server with client authentication
  13676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13677. ASSERT_TRUE(svr.is_valid());
  13678. bool handler_called = false;
  13679. svr.Get("/test", [&](const Request &req, Response &res) {
  13680. handler_called = true;
  13681. // Verify that a client certificate was provided
  13682. auto cert = req.peer_cert();
  13683. ASSERT_TRUE(static_cast<bool>(cert));
  13684. // Get the issuer name
  13685. std::string issuer_str = cert.issuer_name();
  13686. ASSERT_FALSE(issuer_str.empty());
  13687. // The client certificate should be issued by our test CA
  13688. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13689. res.set_content("authenticated", "text/plain");
  13690. });
  13691. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13692. auto se = detail::scope_exit([&] {
  13693. svr.stop();
  13694. t.join();
  13695. ASSERT_FALSE(svr.is_running());
  13696. });
  13697. svr.wait_until_ready();
  13698. // Connect with a client certificate issued by the CA
  13699. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13700. cli.enable_server_certificate_verification(false);
  13701. cli.set_connection_timeout(30);
  13702. auto res = cli.Get("/test");
  13703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13704. ASSERT_EQ(StatusCode::OK_200, res->status);
  13705. ASSERT_TRUE(handler_called);
  13706. EXPECT_EQ("authenticated", res->body);
  13707. }
  13708. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13709. using namespace httplib::tls;
  13710. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13711. ASSERT_TRUE(svr.is_valid());
  13712. svr.Get("/test", [](const Request &, Response &res) {
  13713. res.set_content("ok", "text/plain");
  13714. });
  13715. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13716. auto se = detail::scope_exit([&] {
  13717. svr.stop();
  13718. t.join();
  13719. });
  13720. svr.wait_until_ready();
  13721. SSLClient cli(HOST, PORT);
  13722. cli.enable_server_certificate_verification(false);
  13723. cli.set_connection_timeout(30);
  13724. bool cert_checked = false;
  13725. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13726. if (ctx.cert) {
  13727. auto sans = ctx.sans();
  13728. // Test certificate may or may not have SANs - just verify the API
  13729. // works If SANs exist, verify the types are valid
  13730. for (const auto &san : sans) {
  13731. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13732. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13733. san.type == SanType::OTHER);
  13734. EXPECT_FALSE(san.value.empty());
  13735. }
  13736. cert_checked = true;
  13737. }
  13738. return true;
  13739. });
  13740. auto res = cli.Get("/test");
  13741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13742. EXPECT_TRUE(cert_checked);
  13743. }
  13744. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13745. using namespace httplib::tls;
  13746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13747. ASSERT_TRUE(svr.is_valid());
  13748. svr.Get("/test", [](const Request &, Response &res) {
  13749. res.set_content("ok", "text/plain");
  13750. });
  13751. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13752. auto se = detail::scope_exit([&] {
  13753. svr.stop();
  13754. t.join();
  13755. });
  13756. svr.wait_until_ready();
  13757. SSLClient cli(HOST, PORT);
  13758. cli.enable_server_certificate_verification(false);
  13759. cli.set_connection_timeout(30);
  13760. bool validity_checked = false;
  13761. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13762. if (ctx.cert) {
  13763. time_t not_before = 0, not_after = 0;
  13764. bool result = ctx.validity(not_before, not_after);
  13765. EXPECT_TRUE(result);
  13766. // Verify that not_before < now < not_after for a valid cert
  13767. time_t now = time(nullptr);
  13768. EXPECT_LT(not_before, now);
  13769. EXPECT_GT(not_after, now);
  13770. validity_checked = true;
  13771. }
  13772. return true;
  13773. });
  13774. auto res = cli.Get("/test");
  13775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13776. EXPECT_TRUE(validity_checked);
  13777. }
  13778. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13779. using namespace httplib::tls;
  13780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13781. ASSERT_TRUE(svr.is_valid());
  13782. svr.Get("/test", [](const Request &, Response &res) {
  13783. res.set_content("ok", "text/plain");
  13784. });
  13785. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13786. auto se = detail::scope_exit([&] {
  13787. svr.stop();
  13788. t.join();
  13789. });
  13790. svr.wait_until_ready();
  13791. SSLClient cli(HOST, PORT);
  13792. cli.enable_server_certificate_verification(false);
  13793. cli.set_connection_timeout(30);
  13794. bool serial_checked = false;
  13795. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13796. if (ctx.cert) {
  13797. std::string serial = ctx.serial();
  13798. EXPECT_FALSE(serial.empty());
  13799. // Serial should be a hex string
  13800. for (char c : serial) {
  13801. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13802. (c >= 'a' && c <= 'f'));
  13803. }
  13804. serial_checked = true;
  13805. }
  13806. return true;
  13807. });
  13808. auto res = cli.Get("/test");
  13809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13810. EXPECT_TRUE(serial_checked);
  13811. }
  13812. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13813. // Test 1: Valid CA file - no error should be recorded
  13814. {
  13815. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13816. CLIENT_CA_CERT_FILE);
  13817. ASSERT_TRUE(svr.is_valid());
  13818. // With valid setup, last_ssl_error should be 0
  13819. EXPECT_EQ(0, svr.ssl_last_error());
  13820. }
  13821. // Test 2: Invalid CA file content
  13822. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13823. {
  13824. // Create a temporary file with completely invalid content
  13825. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13826. {
  13827. std::ofstream ofs(temp_invalid_ca);
  13828. ofs << "This is not a certificate file at all\n";
  13829. ofs << "Just plain text content\n";
  13830. }
  13831. // Create server with invalid CA file
  13832. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13833. // Clean up temporary file
  13834. std::remove(temp_invalid_ca);
  13835. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13836. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13837. // Note: SSL_CTX_load_verify_locations typically fails first,
  13838. // but our error handling code path is still exercised
  13839. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13840. }
  13841. }
  13842. TEST(VerifyCallbackTest, VerifyContextFields) {
  13843. using namespace httplib::tls;
  13844. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13845. ASSERT_TRUE(svr.is_valid());
  13846. svr.Get("/test", [](const Request &, Response &res) {
  13847. res.set_content("ok", "text/plain");
  13848. });
  13849. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13850. auto se = detail::scope_exit([&] {
  13851. svr.stop();
  13852. t.join();
  13853. });
  13854. svr.wait_until_ready();
  13855. SSLClient cli(HOST, PORT);
  13856. cli.enable_server_certificate_verification(false);
  13857. cli.set_connection_timeout(30);
  13858. int callback_count = 0;
  13859. bool saw_leaf_cert = false;
  13860. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13861. if (ctx.cert) {
  13862. callback_count++;
  13863. // We should see at least one certificate (the leaf)
  13864. std::string cn = ctx.subject_cn();
  13865. if (!cn.empty()) { saw_leaf_cert = true; }
  13866. // Verify context fields are populated
  13867. EXPECT_NE(ctx.session, nullptr);
  13868. EXPECT_GE(ctx.depth, 0);
  13869. }
  13870. return true;
  13871. });
  13872. auto res = cli.Get("/test");
  13873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13874. EXPECT_GT(callback_count, 0);
  13875. EXPECT_TRUE(saw_leaf_cert);
  13876. }
  13877. // A verifier belongs to the client that set it, not to the thread that set it.
  13878. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13879. using namespace httplib::tls;
  13880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13881. ASSERT_TRUE(svr.is_valid());
  13882. svr.Get("/test", [](const Request &, Response &res) {
  13883. res.set_content("ok", "text/plain");
  13884. });
  13885. auto port = svr.bind_to_any_port(HOST);
  13886. thread t([&]() { svr.listen_after_bind(); });
  13887. auto se = detail::scope_exit([&] {
  13888. svr.stop();
  13889. t.join();
  13890. });
  13891. svr.wait_until_ready();
  13892. auto rejecting_calls = 0;
  13893. SSLClient rejecting(HOST, port);
  13894. rejecting.enable_server_certificate_verification(false);
  13895. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13896. rejecting_calls++;
  13897. return false;
  13898. });
  13899. auto accepting_calls = 0;
  13900. SSLClient accepting(HOST, port);
  13901. accepting.enable_server_certificate_verification(false);
  13902. // Set on another thread than the requests below.
  13903. thread([&]() {
  13904. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13905. accepting_calls++;
  13906. return true;
  13907. });
  13908. }).join();
  13909. // Requested on another thread than the verifier was set on.
  13910. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13911. EXPECT_GT(rejecting_calls, 0);
  13912. auto res = accepting.Get("/test");
  13913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13914. EXPECT_GT(accepting_calls, 0);
  13915. }
  13916. // VerifyContext::session is the same handle the other tls:: functions take.
  13917. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13918. using namespace httplib::tls;
  13919. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13920. ASSERT_TRUE(svr.is_valid());
  13921. svr.Get("/test", [](const Request &, Response &res) {
  13922. res.set_content("ok", "text/plain");
  13923. });
  13924. auto port = svr.bind_to_any_port(HOST);
  13925. thread t([&]() { svr.listen_after_bind(); });
  13926. auto se = detail::scope_exit([&] {
  13927. svr.stop();
  13928. t.join();
  13929. });
  13930. svr.wait_until_ready();
  13931. SSLClient cli(HOST, port);
  13932. cli.enable_server_certificate_verification(false);
  13933. session_t verifier_session = nullptr;
  13934. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13935. verifier_session = ctx.session;
  13936. return true;
  13937. });
  13938. session_t session_verifier_session = nullptr;
  13939. cli.set_session_verifier([&](session_t session) {
  13940. session_verifier_session = session;
  13941. return SSLVerifierResponse::NoDecisionMade;
  13942. });
  13943. auto res = cli.Get("/test");
  13944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13945. EXPECT_NE(nullptr, verifier_session);
  13946. EXPECT_EQ(session_verifier_session, verifier_session);
  13947. }
  13948. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13949. using httplib::tls::TlsError;
  13950. // Test that verify_error_to_string returns empty for success
  13951. std::string success_str = TlsError::verify_error_to_string(0);
  13952. EXPECT_TRUE(success_str.empty());
  13953. // Test that verify_error_to_string returns non-empty for error codes
  13954. // Using a common error code (certificate expired)
  13955. std::string error_str =
  13956. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13957. EXPECT_FALSE(error_str.empty());
  13958. }
  13959. TEST(SessionVerifierTest, CertificateAccepted) {
  13960. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13961. ASSERT_TRUE(svr.is_valid());
  13962. svr.Get("/test", [](const Request &, Response &res) {
  13963. res.set_content("ok", "text/plain");
  13964. });
  13965. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13966. auto se = detail::scope_exit([&] {
  13967. svr.stop();
  13968. t.join();
  13969. });
  13970. svr.wait_until_ready();
  13971. SSLClient cli(HOST, PORT);
  13972. cli.enable_server_certificate_verification(false);
  13973. cli.set_connection_timeout(30);
  13974. bool callback_called = false;
  13975. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13976. EXPECT_NE(session, nullptr);
  13977. callback_called = true;
  13978. return SSLVerifierResponse::CertificateAccepted;
  13979. });
  13980. auto res = cli.Get("/test");
  13981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13982. EXPECT_EQ(200, res->status);
  13983. EXPECT_TRUE(callback_called);
  13984. }
  13985. TEST(SessionVerifierTest, CertificateRejected) {
  13986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13987. ASSERT_TRUE(svr.is_valid());
  13988. svr.Get("/test", [](const Request &, Response &res) {
  13989. res.set_content("ok", "text/plain");
  13990. });
  13991. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13992. auto se = detail::scope_exit([&] {
  13993. svr.stop();
  13994. t.join();
  13995. });
  13996. svr.wait_until_ready();
  13997. SSLClient cli(HOST, PORT);
  13998. cli.enable_server_certificate_verification(false);
  13999. cli.set_connection_timeout(30);
  14000. bool callback_called = false;
  14001. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14002. EXPECT_NE(session, nullptr);
  14003. callback_called = true;
  14004. return SSLVerifierResponse::CertificateRejected;
  14005. });
  14006. auto res = cli.Get("/test");
  14007. EXPECT_FALSE(res);
  14008. EXPECT_TRUE(callback_called);
  14009. }
  14010. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14012. ASSERT_TRUE(svr.is_valid());
  14013. svr.Get("/test", [](const Request &, Response &res) {
  14014. res.set_content("ok", "text/plain");
  14015. });
  14016. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14017. auto se = detail::scope_exit([&] {
  14018. svr.stop();
  14019. t.join();
  14020. });
  14021. svr.wait_until_ready();
  14022. // NoDecisionMade with verification disabled should succeed (no default check)
  14023. SSLClient cli(HOST, PORT);
  14024. cli.enable_server_certificate_verification(false);
  14025. cli.set_connection_timeout(30);
  14026. bool callback_called = false;
  14027. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14028. EXPECT_NE(session, nullptr);
  14029. callback_called = true;
  14030. return SSLVerifierResponse::NoDecisionMade;
  14031. });
  14032. auto res = cli.Get("/test");
  14033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14034. EXPECT_EQ(200, res->status);
  14035. EXPECT_TRUE(callback_called);
  14036. }
  14037. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14038. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14039. ASSERT_TRUE(svr.is_valid());
  14040. svr.Get("/test", [](const Request &, Response &res) {
  14041. res.set_content("ok", "text/plain");
  14042. });
  14043. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14044. auto se = detail::scope_exit([&] {
  14045. svr.stop();
  14046. t.join();
  14047. });
  14048. svr.wait_until_ready();
  14049. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14050. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14051. // so we only check that the request fails, not whether the callback was
  14052. // called.
  14053. SSLClient cli(HOST, PORT);
  14054. cli.enable_server_certificate_verification(true);
  14055. cli.set_connection_timeout(30);
  14056. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14057. EXPECT_NE(session, nullptr);
  14058. return SSLVerifierResponse::NoDecisionMade;
  14059. });
  14060. auto res = cli.Get("/test");
  14061. EXPECT_FALSE(res);
  14062. }
  14063. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14064. // Test SSL server using PemMemory constructor with client CA certificates
  14065. // Read PEM files
  14066. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14067. read_file(SERVER_CERT_FILE, server_cert_pem);
  14068. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14069. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14070. // Create SSLServer with PemMemory constructor including client CA
  14071. SSLServer::PemMemory server_pem = {
  14072. server_cert_pem.c_str(),
  14073. server_cert_pem.size(),
  14074. server_key_pem.c_str(),
  14075. server_key_pem.size(),
  14076. client_ca_pem.c_str(),
  14077. client_ca_pem.size(),
  14078. nullptr // no password for server key
  14079. };
  14080. SSLServer svr(server_pem);
  14081. ASSERT_TRUE(svr.is_valid());
  14082. // No SSL error should be recorded for valid setup
  14083. EXPECT_EQ(0, svr.ssl_last_error());
  14084. // Set up server endpoints
  14085. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14086. res.set_content("ok", "text/plain");
  14087. });
  14088. // Start server in a thread
  14089. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14090. svr.wait_until_ready();
  14091. // Connect with client certificate (using constructor with paths)
  14092. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14093. cli.enable_server_certificate_verification(false);
  14094. auto res = cli.Get("/test-pem-ca");
  14095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14096. EXPECT_EQ(200, res->status);
  14097. EXPECT_EQ("ok", res->body);
  14098. svr.stop();
  14099. server_thread.join();
  14100. }
  14101. #endif
  14102. #ifdef _WIN32
  14103. TEST(CleanupTest, WSACleanup) {
  14104. int ret = WSACleanup();
  14105. ASSERT_EQ(0, ret);
  14106. }
  14107. #endif
  14108. #ifndef CPPHTTPLIB_SSL_ENABLED
  14109. TEST(NoSSLSupport, SimpleInterface) {
  14110. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14111. }
  14112. #endif
  14113. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14114. TEST(InvalidScheme, SimpleInterface) {
  14115. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14116. }
  14117. #endif
  14118. TEST(NoScheme, SimpleInterface) {
  14119. Client cli("yahoo.com:80");
  14120. ASSERT_TRUE(cli.is_valid());
  14121. }
  14122. TEST(SendAPI, SimpleInterface_Online) {
  14123. Client cli("http://yahoo.com");
  14124. Request req;
  14125. req.method = "GET";
  14126. req.path = "/";
  14127. auto res = cli.send(req);
  14128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14129. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14130. }
  14131. TEST(SendAPI, WithParamsInRequest) {
  14132. Server svr;
  14133. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14134. EXPECT_TRUE(req.has_param("test"));
  14135. EXPECT_EQ("test_value", req.get_param_value("test"));
  14136. });
  14137. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14138. auto se = detail::scope_exit([&] {
  14139. svr.stop();
  14140. t.join();
  14141. ASSERT_FALSE(svr.is_running());
  14142. });
  14143. svr.wait_until_ready();
  14144. Client cli(HOST, PORT);
  14145. {
  14146. Request req;
  14147. req.method = "GET";
  14148. req.path = "/";
  14149. req.params.emplace("test", "test_value");
  14150. auto res = cli.send(req);
  14151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14152. }
  14153. {
  14154. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14156. }
  14157. }
  14158. TEST(ClientImplMethods, GetSocketTest) {
  14159. httplib::Server svr;
  14160. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14161. res.status = StatusCode::OK_200;
  14162. });
  14163. auto port = svr.bind_to_any_port("127.0.0.1");
  14164. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14165. auto se = detail::scope_exit([&] {
  14166. svr.stop();
  14167. thread.join();
  14168. ASSERT_FALSE(svr.is_running());
  14169. });
  14170. svr.wait_until_ready();
  14171. {
  14172. httplib::Client cli("127.0.0.1", port);
  14173. cli.set_keep_alive(true);
  14174. // Use the behavior of cpp-httplib of opening the connection
  14175. // only when the first request happens. If that changes,
  14176. // this test would be obsolete.
  14177. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14178. // This also implicitly tests the server. But other tests would fail much
  14179. // earlier than this one to be considered.
  14180. auto res = cli.Get("/");
  14181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14182. EXPECT_EQ(StatusCode::OK_200, res->status);
  14183. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14184. }
  14185. }
  14186. #ifdef CPPHTTPLIB_SSL_ENABLED
  14187. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14188. Client cli("http://yahoo.com");
  14189. auto res = cli.Get("/");
  14190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14191. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14192. cli.set_follow_location(true);
  14193. res = cli.Get("/");
  14194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14195. EXPECT_EQ(StatusCode::OK_200, res->status);
  14196. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14197. }
  14198. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14199. Client cli("https://yahoo.com");
  14200. auto res = cli.Get("/");
  14201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14202. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14203. cli.set_follow_location(true);
  14204. res = cli.Get("/");
  14205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14206. EXPECT_EQ(StatusCode::OK_200, res->status);
  14207. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14208. }
  14209. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14210. Client cli("https://yahoo.com");
  14211. auto res = cli.Get("/");
  14212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14213. ASSERT_FALSE(!res);
  14214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14215. ASSERT_FALSE(res == nullptr);
  14216. ASSERT_TRUE(res != nullptr);
  14217. EXPECT_EQ(Error::Success, res.error());
  14218. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14219. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14220. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14221. cli.set_follow_location(true);
  14222. res = cli.Get("/");
  14223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14224. EXPECT_EQ(Error::Success, res.error());
  14225. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14226. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14227. EXPECT_EQ(StatusCode::OK_200, res->status);
  14228. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14229. }
  14230. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14231. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14232. Client cli("https://cdnjs.cloudflare.com");
  14233. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14234. Headers{{"Accept-Encoding", "br"}});
  14235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14236. EXPECT_EQ(StatusCode::OK_200, res->status);
  14237. EXPECT_EQ(287630U, res->body.size());
  14238. EXPECT_EQ("application/javascript; charset=utf-8",
  14239. res->get_header_value("Content-Type"));
  14240. }
  14241. #endif
  14242. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14243. #undef REDIR_HOST // Silence compiler warning
  14244. #define REDIR_HOST "https://httpbingo.org"
  14245. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14246. Client cli(REDIR_HOST);
  14247. cli.set_follow_location(true);
  14248. auto res =
  14249. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14251. EXPECT_EQ(StatusCode::OK_200, res->status);
  14252. }
  14253. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14254. Client cli(REDIR_HOST);
  14255. cli.set_follow_location(true);
  14256. Params params;
  14257. params.emplace("url", "http://example.com");
  14258. params.emplace("status_code", "302");
  14259. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14261. EXPECT_EQ(StatusCode::OK_200, res->status);
  14262. }
  14263. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14264. Client cli(REDIR_HOST);
  14265. cli.set_follow_location(true);
  14266. Params params;
  14267. params.emplace("url", "http://example.com");
  14268. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14270. EXPECT_EQ(StatusCode::OK_200, res->status);
  14271. }
  14272. TEST(HttpToHttpsRedirectTest, CertFile) {
  14273. auto ssl_port = PORT + 1;
  14274. Server svr;
  14275. ASSERT_TRUE(svr.is_valid());
  14276. svr.Get("/index", [&](const Request &, Response &res) {
  14277. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14278. "/index");
  14279. svr.stop();
  14280. });
  14281. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14282. ASSERT_TRUE(ssl_svr.is_valid());
  14283. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14284. res.set_content("test", "text/plain");
  14285. ssl_svr.stop();
  14286. });
  14287. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14288. thread t2 =
  14289. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14290. auto se = detail::scope_exit([&] {
  14291. t2.join();
  14292. t.join();
  14293. ASSERT_FALSE(svr.is_running());
  14294. });
  14295. svr.wait_until_ready();
  14296. ssl_svr.wait_until_ready();
  14297. Client cli("127.0.0.1", PORT);
  14298. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14299. cli.enable_server_certificate_verification(true);
  14300. cli.set_follow_location(true);
  14301. cli.set_connection_timeout(30);
  14302. auto res = cli.Get("/index");
  14303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14304. ASSERT_EQ(StatusCode::OK_200, res->status);
  14305. }
  14306. TEST(SSLClientRedirectTest, CertFile) {
  14307. auto ssl_port = PORT + 1;
  14308. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14309. ASSERT_TRUE(ssl_svr1.is_valid());
  14310. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14311. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14312. "/index");
  14313. ssl_svr1.stop();
  14314. });
  14315. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14316. ASSERT_TRUE(ssl_svr2.is_valid());
  14317. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14318. res.set_content("test", "text/plain");
  14319. ssl_svr2.stop();
  14320. });
  14321. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14322. thread t2 =
  14323. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14324. auto se = detail::scope_exit([&] {
  14325. t2.join();
  14326. t.join();
  14327. ASSERT_FALSE(ssl_svr1.is_running());
  14328. });
  14329. ssl_svr1.wait_until_ready();
  14330. ssl_svr2.wait_until_ready();
  14331. SSLClient cli("127.0.0.1", PORT);
  14332. std::string cert;
  14333. read_file(SERVER_CERT2_FILE, cert);
  14334. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14335. cli.enable_server_certificate_verification(true);
  14336. cli.set_follow_location(true);
  14337. cli.set_connection_timeout(30);
  14338. auto res = cli.Get("/index");
  14339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14340. ASSERT_EQ(StatusCode::OK_200, res->status);
  14341. }
  14342. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14343. // another port, so the client follows it with a new client.
  14344. static Result GetThroughTlsRedirectToDifferentPort(
  14345. const std::function<void(SSLClient &)> &setup,
  14346. const char *target_cert = SERVER_CERT2_FILE) {
  14347. auto ssl_port = PORT + 1;
  14348. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14349. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14350. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14351. "/index");
  14352. });
  14353. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14354. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14355. res.set_content("test", "text/plain");
  14356. });
  14357. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14358. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14359. auto se = detail::scope_exit([&] {
  14360. ssl_svr2.stop();
  14361. ssl_svr1.stop();
  14362. t2.join();
  14363. t.join();
  14364. });
  14365. ssl_svr1.wait_until_ready();
  14366. ssl_svr2.wait_until_ready();
  14367. SSLClient cli("127.0.0.1", PORT);
  14368. cli.set_follow_location(true);
  14369. cli.set_connection_timeout(30);
  14370. setup(cli);
  14371. return cli.Get("/index");
  14372. }
  14373. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14374. auto calls = 0;
  14375. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14376. cli.enable_server_certificate_verification(false);
  14377. // Accept the first server only.
  14378. cli.set_session_verifier([&](tls::session_t) {
  14379. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14380. : SSLVerifierResponse::CertificateRejected;
  14381. });
  14382. });
  14383. EXPECT_FALSE(res);
  14384. EXPECT_EQ(2, calls);
  14385. }
  14386. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14387. std::string pinned;
  14388. auto res = GetThroughTlsRedirectToDifferentPort(
  14389. [&](SSLClient &cli) {
  14390. cli.enable_server_certificate_verification(false);
  14391. // Pin the first certificate seen.
  14392. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14393. if (pinned.empty()) { pinned = ctx.serial(); }
  14394. return ctx.serial() == pinned;
  14395. });
  14396. },
  14397. // A certificate other than the first server's.
  14398. SERVER_CERT_FILE);
  14399. EXPECT_FALSE(res);
  14400. EXPECT_FALSE(pinned.empty());
  14401. }
  14402. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14403. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14404. std::string cert;
  14405. read_file(SERVER_CERT2_FILE, cert);
  14406. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14407. });
  14408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14409. EXPECT_EQ(StatusCode::OK_200, res->status);
  14410. }
  14411. #endif
  14412. #ifdef CPPHTTPLIB_SSL_ENABLED
  14413. // Test that set_ca_cert_store() skips system certs (consistent with
  14414. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14415. // should be trusted - system certs should NOT be loaded.
  14416. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14417. // Load a specific cert that is NOT a system CA cert
  14418. std::string cert;
  14419. read_file(SERVER_CERT2_FILE, cert);
  14420. SSLClient cli("google.com");
  14421. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14422. cli.enable_server_certificate_verification(true);
  14423. // This should FAIL because:
  14424. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14425. // 2. System certs should NOT be loaded when custom store is set
  14426. // If system certs WERE loaded, this would succeed
  14427. auto res = cli.Get("/");
  14428. ASSERT_FALSE(res);
  14429. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14430. }
  14431. // Same as above, but through the native store handle path. Regression test:
  14432. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14433. // merged system certs into the user-provided store.
  14434. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14435. std::string cert;
  14436. read_file(SERVER_CERT2_FILE, cert);
  14437. SSLClient cli("google.com");
  14438. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14439. cli.enable_server_certificate_verification(true);
  14440. auto res = cli.Get("/");
  14441. ASSERT_FALSE(res);
  14442. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14443. }
  14444. // A custom store set via the native handle must still verify a server whose
  14445. // cert it does contain.
  14446. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14447. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14448. ASSERT_TRUE(svr.is_valid());
  14449. svr.Get("/test", [&](const Request &, Response &res) {
  14450. res.set_content("test", "text/plain");
  14451. });
  14452. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14453. auto se = detail::scope_exit([&] {
  14454. svr.stop();
  14455. t.join();
  14456. ASSERT_FALSE(svr.is_running());
  14457. });
  14458. svr.wait_until_ready();
  14459. SSLClient cli("127.0.0.1", PORT);
  14460. std::string cert;
  14461. read_file(SERVER_CERT2_FILE, cert);
  14462. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14463. cli.enable_server_certificate_verification(true);
  14464. cli.set_connection_timeout(30);
  14465. auto res = cli.Get("/test");
  14466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14467. ASSERT_EQ(StatusCode::OK_200, res->status);
  14468. }
  14469. // CA certs loaded through the universal Client must be transferred to the
  14470. // client created internally for following an HTTPS redirect. Regression test:
  14471. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14472. // the CA data for redirect transfer.
  14473. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14474. auto ssl_port = PORT + 1;
  14475. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14476. ASSERT_TRUE(ssl_svr1.is_valid());
  14477. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14478. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14479. "/index");
  14480. });
  14481. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14482. ASSERT_TRUE(ssl_svr2.is_valid());
  14483. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14484. res.set_content("test", "text/plain");
  14485. });
  14486. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14487. thread t2 =
  14488. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14489. auto se = detail::scope_exit([&] {
  14490. ssl_svr2.stop();
  14491. ssl_svr1.stop();
  14492. t2.join();
  14493. t.join();
  14494. ASSERT_FALSE(ssl_svr1.is_running());
  14495. });
  14496. ssl_svr1.wait_until_ready();
  14497. ssl_svr2.wait_until_ready();
  14498. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14499. std::string cert;
  14500. read_file(SERVER_CERT2_FILE, cert);
  14501. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14502. cli.enable_server_certificate_verification(true);
  14503. cli.set_follow_location(true);
  14504. cli.set_connection_timeout(30);
  14505. auto res = cli.Get("/index");
  14506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14507. ASSERT_EQ(StatusCode::OK_200, res->status);
  14508. }
  14509. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14510. // so a host signed by a system CA verifies even though a custom CA is set
  14511. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14512. std::string cert;
  14513. read_file(SERVER_CERT2_FILE, cert);
  14514. SSLClient cli("google.com");
  14515. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14516. cli.enable_system_ca(true);
  14517. cli.enable_server_certificate_verification(true);
  14518. auto res = cli.Get("/");
  14519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14520. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14521. }
  14522. // The custom CA remains effective when combined with the system CA
  14523. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14524. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14525. ASSERT_TRUE(svr.is_valid());
  14526. svr.Get("/test", [&](const Request &, Response &res) {
  14527. res.set_content("test", "text/plain");
  14528. });
  14529. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14530. auto se = detail::scope_exit([&] {
  14531. svr.stop();
  14532. t.join();
  14533. ASSERT_FALSE(svr.is_running());
  14534. });
  14535. svr.wait_until_ready();
  14536. SSLClient cli("127.0.0.1", PORT);
  14537. std::string cert;
  14538. read_file(SERVER_CERT2_FILE, cert);
  14539. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14540. cli.enable_system_ca(true);
  14541. cli.enable_server_certificate_verification(true);
  14542. cli.set_connection_timeout(30);
  14543. auto res = cli.Get("/test");
  14544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14545. ASSERT_EQ(StatusCode::OK_200, res->status);
  14546. }
  14547. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14548. // skip chain verification entirely (only the certificate identity was
  14549. // checked), so a server presenting an untrusted certificate with a matching
  14550. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14551. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14552. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14553. ASSERT_TRUE(svr.is_valid());
  14554. svr.Get("/test", [&](const Request &, Response &res) {
  14555. res.set_content("test", "text/plain");
  14556. });
  14557. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14558. auto se = detail::scope_exit([&] {
  14559. svr.stop();
  14560. t.join();
  14561. ASSERT_FALSE(svr.is_running());
  14562. });
  14563. svr.wait_until_ready();
  14564. SSLClient cli("127.0.0.1", PORT);
  14565. std::string cert;
  14566. // A trusted CA that did not sign the server certificate. The server cert
  14567. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14568. // this connection.
  14569. read_file(CLIENT_CA_CERT_FILE, cert);
  14570. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14571. cli.enable_server_certificate_verification(true);
  14572. cli.set_connection_timeout(30);
  14573. auto res = cli.Get("/test");
  14574. ASSERT_FALSE(res);
  14575. }
  14576. // enable_system_ca(false) prevents system CA loading entirely
  14577. TEST(SSLClientTest, DisableSystemCa_Online) {
  14578. SSLClient cli("google.com");
  14579. cli.enable_system_ca(false);
  14580. cli.enable_server_certificate_verification(true);
  14581. auto res = cli.Get("/");
  14582. ASSERT_FALSE(res);
  14583. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14584. // itself when the CA chain is empty
  14585. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14586. res.error() == Error::SSLConnection);
  14587. }
  14588. // The universal Client forwards enable_system_ca()
  14589. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14590. std::string cert;
  14591. read_file(SERVER_CERT2_FILE, cert);
  14592. Client cli("https://google.com");
  14593. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14594. cli.enable_system_ca(true);
  14595. cli.enable_server_certificate_verification(true);
  14596. auto res = cli.Get("/");
  14597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14598. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14599. }
  14600. // The system CA policy must carry over to the client created internally for
  14601. // following a cross-host HTTPS redirect
  14602. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14603. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14604. ASSERT_TRUE(svr.is_valid());
  14605. svr.Get("/index", [&](const Request &, Response &res) {
  14606. res.set_redirect("https://www.google.com/");
  14607. });
  14608. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14609. auto se = detail::scope_exit([&] {
  14610. svr.stop();
  14611. t.join();
  14612. ASSERT_FALSE(svr.is_running());
  14613. });
  14614. svr.wait_until_ready();
  14615. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14616. std::string cert;
  14617. read_file(SERVER_CERT2_FILE, cert);
  14618. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14619. cli.enable_system_ca(true);
  14620. cli.enable_server_certificate_verification(true);
  14621. cli.set_follow_location(true);
  14622. cli.set_connection_timeout(30);
  14623. // Receiving any response proves the redirect client completed the TLS
  14624. // handshake with a system-CA-signed host
  14625. auto res = cli.Get("/index");
  14626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14627. }
  14628. TEST(MultipartFormDataTest, LargeData) {
  14629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14630. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14631. const ContentReader &content_reader) {
  14632. if (req.is_multipart_form_data()) {
  14633. std::vector<FormData> items;
  14634. content_reader(
  14635. [&](const FormData &file) {
  14636. items.push_back(file);
  14637. return true;
  14638. },
  14639. [&](const char *data, size_t data_length) {
  14640. items.back().content.append(data, data_length);
  14641. return true;
  14642. });
  14643. EXPECT_TRUE(std::string(items[0].name) == "document");
  14644. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14645. EXPECT_TRUE(items[0].filename == "2MB_data");
  14646. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14647. EXPECT_TRUE(items[1].name == "hello");
  14648. EXPECT_TRUE(items[1].content == "world");
  14649. EXPECT_TRUE(items[1].filename == "");
  14650. EXPECT_TRUE(items[1].content_type == "");
  14651. } else {
  14652. std::string body;
  14653. content_reader([&](const char *data, size_t data_length) {
  14654. body.append(data, data_length);
  14655. return true;
  14656. });
  14657. }
  14658. });
  14659. auto port = svr.bind_to_any_port(HOST);
  14660. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14661. auto se = detail::scope_exit([&] {
  14662. svr.stop();
  14663. t.join();
  14664. ASSERT_FALSE(svr.is_running());
  14665. });
  14666. svr.wait_until_ready();
  14667. {
  14668. std::string data(1024 * 1024 * 2, '.');
  14669. std::stringstream buffer;
  14670. buffer << data;
  14671. SSLClient cli(HOST, port);
  14672. cli.enable_server_certificate_verification(false);
  14673. UploadFormDataItems items{
  14674. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14675. {"hello", "world", "", ""},
  14676. };
  14677. auto res = cli.Post("/post", items);
  14678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14679. ASSERT_EQ(StatusCode::OK_200, res->status);
  14680. }
  14681. }
  14682. TEST(MultipartFormDataTest, DataProviderItems) {
  14683. std::random_device seed_gen;
  14684. std::mt19937 random(seed_gen());
  14685. std::string rand1;
  14686. rand1.resize(1000);
  14687. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14688. std::string rand2;
  14689. rand2.resize(3000);
  14690. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14692. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14693. const ContentReader &content_reader) {
  14694. ASSERT_FALSE(req.is_multipart_form_data());
  14695. std::string body;
  14696. content_reader([&](const char *data, size_t data_length) {
  14697. body.append(data, data_length);
  14698. return true;
  14699. });
  14700. EXPECT_EQ(body, "");
  14701. });
  14702. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14703. const ContentReader &content_reader) {
  14704. ASSERT_TRUE(req.is_multipart_form_data());
  14705. std::vector<FormData> items;
  14706. content_reader(
  14707. [&](const FormData &file) {
  14708. items.push_back(file);
  14709. return true;
  14710. },
  14711. [&](const char *data, size_t data_length) {
  14712. items.back().content.append(data, data_length);
  14713. return true;
  14714. });
  14715. ASSERT_TRUE(items.size() == 2);
  14716. EXPECT_EQ(std::string(items[0].name), "name1");
  14717. EXPECT_EQ(items[0].content, "Testing123");
  14718. EXPECT_EQ(items[0].filename, "filename1");
  14719. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14720. EXPECT_EQ(items[1].name, "name2");
  14721. EXPECT_EQ(items[1].content, "Testing456");
  14722. EXPECT_EQ(items[1].filename, "");
  14723. EXPECT_EQ(items[1].content_type, "");
  14724. });
  14725. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14726. const ContentReader &content_reader) {
  14727. ASSERT_TRUE(req.is_multipart_form_data());
  14728. std::vector<FormData> items;
  14729. content_reader(
  14730. [&](const FormData &file) {
  14731. items.push_back(file);
  14732. return true;
  14733. },
  14734. [&](const char *data, size_t data_length) {
  14735. items.back().content.append(data, data_length);
  14736. return true;
  14737. });
  14738. ASSERT_TRUE(items.size() == 2);
  14739. EXPECT_EQ(items[0].name, "name3");
  14740. EXPECT_EQ(items[0].content, rand1);
  14741. EXPECT_EQ(items[0].filename, "filename3");
  14742. EXPECT_EQ(items[0].content_type, "");
  14743. EXPECT_EQ(items[1].name, "name4");
  14744. EXPECT_EQ(items[1].content, rand2);
  14745. EXPECT_EQ(items[1].filename, "filename4");
  14746. EXPECT_EQ(items[1].content_type, "");
  14747. });
  14748. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14749. const ContentReader &content_reader) {
  14750. ASSERT_TRUE(req.is_multipart_form_data());
  14751. std::vector<FormData> items;
  14752. content_reader(
  14753. [&](const FormData &file) {
  14754. items.push_back(file);
  14755. return true;
  14756. },
  14757. [&](const char *data, size_t data_length) {
  14758. items.back().content.append(data, data_length);
  14759. return true;
  14760. });
  14761. ASSERT_TRUE(items.size() == 4);
  14762. EXPECT_EQ(std::string(items[0].name), "name1");
  14763. EXPECT_EQ(items[0].content, "Testing123");
  14764. EXPECT_EQ(items[0].filename, "filename1");
  14765. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14766. EXPECT_EQ(items[1].name, "name2");
  14767. EXPECT_EQ(items[1].content, "Testing456");
  14768. EXPECT_EQ(items[1].filename, "");
  14769. EXPECT_EQ(items[1].content_type, "");
  14770. EXPECT_EQ(items[2].name, "name3");
  14771. EXPECT_EQ(items[2].content, rand1);
  14772. EXPECT_EQ(items[2].filename, "filename3");
  14773. EXPECT_EQ(items[2].content_type, "");
  14774. EXPECT_EQ(items[3].name, "name4");
  14775. EXPECT_EQ(items[3].content, rand2);
  14776. EXPECT_EQ(items[3].filename, "filename4");
  14777. EXPECT_EQ(items[3].content_type, "");
  14778. });
  14779. auto port = svr.bind_to_any_port("localhost");
  14780. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14781. auto se = detail::scope_exit([&] {
  14782. svr.stop();
  14783. t.join();
  14784. ASSERT_FALSE(svr.is_running());
  14785. });
  14786. svr.wait_until_ready();
  14787. {
  14788. SSLClient cli("localhost", port);
  14789. cli.enable_server_certificate_verification(false);
  14790. UploadFormDataItems items{
  14791. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14792. {"name2", "Testing456", "", ""}, // not a file
  14793. };
  14794. {
  14795. auto res = cli.Post("/post-none", {}, {}, {});
  14796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14797. ASSERT_EQ(StatusCode::OK_200, res->status);
  14798. }
  14799. FormDataProviderItems providers;
  14800. {
  14801. auto res =
  14802. cli.Post("/post-items", {}, items, providers); // empty providers
  14803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14804. ASSERT_EQ(StatusCode::OK_200, res->status);
  14805. }
  14806. providers.push_back({"name3",
  14807. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14808. // test the offset is given correctly at each step
  14809. if (!offset)
  14810. sink.os.write(rand1.data(), 30);
  14811. else if (offset == 30)
  14812. sink.os.write(rand1.data() + 30, 300);
  14813. else if (offset == 330)
  14814. sink.os.write(rand1.data() + 330, 670);
  14815. else if (offset == rand1.size())
  14816. sink.done();
  14817. return true;
  14818. },
  14819. "filename3",
  14820. {}});
  14821. providers.push_back({"name4",
  14822. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14823. // test the offset is given correctly at each step
  14824. if (!offset)
  14825. sink.os.write(rand2.data(), 2000);
  14826. else if (offset == 2000)
  14827. sink.os.write(rand2.data() + 2000, 1);
  14828. else if (offset == 2001)
  14829. sink.os.write(rand2.data() + 2001, 999);
  14830. else if (offset == rand2.size())
  14831. sink.done();
  14832. return true;
  14833. },
  14834. "filename4",
  14835. {}});
  14836. {
  14837. auto res = cli.Post("/post-providers", {}, {}, providers);
  14838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14839. ASSERT_EQ(StatusCode::OK_200, res->status);
  14840. }
  14841. {
  14842. auto res = cli.Post("/post-both", {}, items, providers);
  14843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14844. ASSERT_EQ(StatusCode::OK_200, res->status);
  14845. }
  14846. }
  14847. }
  14848. TEST(MultipartFormDataTest, BadHeader) {
  14849. Server svr;
  14850. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14851. res.set_content("ok", "text/plain");
  14852. });
  14853. thread t = thread([&] { svr.listen(HOST, PORT); });
  14854. auto se = detail::scope_exit([&] {
  14855. svr.stop();
  14856. t.join();
  14857. ASSERT_FALSE(svr.is_running());
  14858. });
  14859. svr.wait_until_ready();
  14860. const std::string body =
  14861. "This is the preamble. It is to be ignored, though it\r\n"
  14862. "is a handy place for composition agents to include an\r\n"
  14863. "explanatory note to non-MIME conformant readers.\r\n"
  14864. "\r\n"
  14865. "\r\n"
  14866. "--simple boundary\r\n"
  14867. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14868. ": BAD...\r\n"
  14869. "\r\n"
  14870. "value1\r\n"
  14871. "--simple boundary\r\n"
  14872. "Content-Disposition: form-data; name=\"field2\"; "
  14873. "filename=\"example.txt\"\r\n"
  14874. "\r\n"
  14875. "value2\r\n"
  14876. "--simple boundary--\r\n"
  14877. "This is the epilogue. It is also to be ignored.\r\n";
  14878. std::string content_type =
  14879. R"(multipart/form-data; boundary="simple boundary")";
  14880. Client cli(HOST, PORT);
  14881. auto res = cli.Post("/post", body, content_type.c_str());
  14882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14883. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14884. }
  14885. TEST(MultipartFormDataTest, WithPreamble) {
  14886. Server svr;
  14887. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14888. res.set_content("ok", "text/plain");
  14889. });
  14890. thread t = thread([&] { svr.listen(HOST, PORT); });
  14891. auto se = detail::scope_exit([&] {
  14892. svr.stop();
  14893. t.join();
  14894. ASSERT_FALSE(svr.is_running());
  14895. });
  14896. svr.wait_until_ready();
  14897. const std::string body =
  14898. "This is the preamble. It is to be ignored, though it\r\n"
  14899. "is a handy place for composition agents to include an\r\n"
  14900. "explanatory note to non-MIME conformant readers.\r\n"
  14901. "\r\n"
  14902. "\r\n"
  14903. "--simple boundary\r\n"
  14904. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14905. "\r\n"
  14906. "value1\r\n"
  14907. "--simple boundary\r\n"
  14908. "Content-Disposition: form-data; name=\"field2\"; "
  14909. "filename=\"example.txt\"\r\n"
  14910. "\r\n"
  14911. "value2\r\n"
  14912. "--simple boundary--\r\n"
  14913. "This is the epilogue. It is also to be ignored.\r\n";
  14914. std::string content_type =
  14915. R"(multipart/form-data; boundary="simple boundary")";
  14916. Client cli(HOST, PORT);
  14917. auto res = cli.Post("/post", body, content_type.c_str());
  14918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14919. EXPECT_EQ(StatusCode::OK_200, res->status);
  14920. }
  14921. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14923. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14924. const ContentReader &content_reader) {
  14925. if (req.is_multipart_form_data()) {
  14926. std::vector<FormData> items;
  14927. content_reader(
  14928. [&](const FormData &file) {
  14929. items.push_back(file);
  14930. return true;
  14931. },
  14932. [&](const char *data, size_t data_length) {
  14933. items.back().content.append(data, data_length);
  14934. return true;
  14935. });
  14936. EXPECT_TRUE(std::string(items[0].name) == "document");
  14937. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14938. EXPECT_TRUE(items[0].filename == "2MB_data");
  14939. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14940. EXPECT_TRUE(items[1].name == "hello");
  14941. EXPECT_TRUE(items[1].content == "world");
  14942. EXPECT_TRUE(items[1].filename == "");
  14943. EXPECT_TRUE(items[1].content_type == "");
  14944. } else {
  14945. std::string body;
  14946. content_reader([&](const char *data, size_t data_length) {
  14947. body.append(data, data_length);
  14948. return true;
  14949. });
  14950. }
  14951. });
  14952. auto port = svr.bind_to_any_port("localhost");
  14953. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14954. auto se = detail::scope_exit([&] {
  14955. svr.stop();
  14956. t.join();
  14957. ASSERT_FALSE(svr.is_running());
  14958. });
  14959. svr.wait_until_ready();
  14960. {
  14961. std::string data(1024 * 1024 * 2, '.');
  14962. std::stringstream buffer;
  14963. buffer << data;
  14964. SSLClient cli("localhost", port);
  14965. cli.enable_server_certificate_verification(false);
  14966. UploadFormDataItems items{
  14967. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14968. {"hello", "world", "", ""},
  14969. };
  14970. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14972. ASSERT_EQ(StatusCode::OK_200, res->status);
  14973. }
  14974. }
  14975. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14976. std::string data(1024 * 1024 * 2, '&');
  14977. std::stringstream buffer;
  14978. buffer << data;
  14979. Client cli("https://localhost:8080");
  14980. UploadFormDataItems items{
  14981. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14982. {"hello", "world", "", ""},
  14983. };
  14984. for (const char &c : " \t\r\n") {
  14985. auto res =
  14986. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14987. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14988. ASSERT_FALSE(res);
  14989. }
  14990. }
  14991. TEST(MultipartFormDataTest, PutFormData) {
  14992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14993. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14994. const ContentReader &content_reader) {
  14995. if (req.is_multipart_form_data()) {
  14996. std::vector<FormData> items;
  14997. content_reader(
  14998. [&](const FormData &file) {
  14999. items.push_back(file);
  15000. return true;
  15001. },
  15002. [&](const char *data, size_t data_length) {
  15003. items.back().content.append(data, data_length);
  15004. return true;
  15005. });
  15006. EXPECT_TRUE(std::string(items[0].name) == "document");
  15007. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15008. EXPECT_TRUE(items[0].filename == "2MB_data");
  15009. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15010. EXPECT_TRUE(items[1].name == "hello");
  15011. EXPECT_TRUE(items[1].content == "world");
  15012. EXPECT_TRUE(items[1].filename == "");
  15013. EXPECT_TRUE(items[1].content_type == "");
  15014. } else {
  15015. std::string body;
  15016. content_reader([&](const char *data, size_t data_length) {
  15017. body.append(data, data_length);
  15018. return true;
  15019. });
  15020. }
  15021. });
  15022. auto port = svr.bind_to_any_port("localhost");
  15023. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15024. auto se = detail::scope_exit([&] {
  15025. svr.stop();
  15026. t.join();
  15027. ASSERT_FALSE(svr.is_running());
  15028. });
  15029. svr.wait_until_ready();
  15030. {
  15031. std::string data(1024 * 1024 * 2, '&');
  15032. std::stringstream buffer;
  15033. buffer << data;
  15034. SSLClient cli("localhost", port);
  15035. cli.enable_server_certificate_verification(false);
  15036. UploadFormDataItems items{
  15037. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15038. {"hello", "world", "", ""},
  15039. };
  15040. auto res = cli.Put("/put", items);
  15041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15042. ASSERT_EQ(StatusCode::OK_200, res->status);
  15043. }
  15044. }
  15045. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15047. svr.Put("/put_customboundary",
  15048. [&](const Request &req, const Response & /*res*/,
  15049. const ContentReader &content_reader) {
  15050. if (req.is_multipart_form_data()) {
  15051. std::vector<FormData> items;
  15052. content_reader(
  15053. [&](const FormData &file) {
  15054. items.push_back(file);
  15055. return true;
  15056. },
  15057. [&](const char *data, size_t data_length) {
  15058. items.back().content.append(data, data_length);
  15059. return true;
  15060. });
  15061. EXPECT_TRUE(std::string(items[0].name) == "document");
  15062. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15063. EXPECT_TRUE(items[0].filename == "2MB_data");
  15064. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15065. EXPECT_TRUE(items[1].name == "hello");
  15066. EXPECT_TRUE(items[1].content == "world");
  15067. EXPECT_TRUE(items[1].filename == "");
  15068. EXPECT_TRUE(items[1].content_type == "");
  15069. } else {
  15070. std::string body;
  15071. content_reader([&](const char *data, size_t data_length) {
  15072. body.append(data, data_length);
  15073. return true;
  15074. });
  15075. }
  15076. });
  15077. auto port = svr.bind_to_any_port("localhost");
  15078. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15079. auto se = detail::scope_exit([&] {
  15080. svr.stop();
  15081. t.join();
  15082. ASSERT_FALSE(svr.is_running());
  15083. });
  15084. svr.wait_until_ready();
  15085. {
  15086. std::string data(1024 * 1024 * 2, '&');
  15087. std::stringstream buffer;
  15088. buffer << data;
  15089. SSLClient cli("localhost", port);
  15090. cli.enable_server_certificate_verification(false);
  15091. UploadFormDataItems items{
  15092. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15093. {"hello", "world", "", ""},
  15094. };
  15095. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15097. ASSERT_EQ(StatusCode::OK_200, res->status);
  15098. }
  15099. }
  15100. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15101. std::string data(1024 * 1024 * 2, '&');
  15102. std::stringstream buffer;
  15103. buffer << data;
  15104. Client cli("https://localhost:8080");
  15105. cli.enable_server_certificate_verification(false);
  15106. UploadFormDataItems items{
  15107. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15108. {"hello", "world", "", ""},
  15109. };
  15110. for (const char &c : " \t\r\n") {
  15111. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15112. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15113. ASSERT_FALSE(res);
  15114. }
  15115. }
  15116. TEST(MultipartFormDataTest, AlternateFilename) {
  15117. auto handled = false;
  15118. Server svr;
  15119. svr.Post("/test", [&](const Request &req, Response &res) {
  15120. ASSERT_EQ(2u, req.form.files.size());
  15121. ASSERT_EQ(1u, req.form.fields.size());
  15122. // Test files
  15123. const auto &file1 = req.form.get_file("file1");
  15124. ASSERT_EQ("file1", file1.name);
  15125. ASSERT_EQ("A.txt", file1.filename);
  15126. ASSERT_EQ("text/plain", file1.content_type);
  15127. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15128. const auto &file2 = req.form.get_file("file2");
  15129. ASSERT_EQ("file2", file2.name);
  15130. ASSERT_EQ("a.html", file2.filename);
  15131. ASSERT_EQ("text/html", file2.content_type);
  15132. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15133. file2.content);
  15134. // Test text field
  15135. const auto &text = req.form.get_field("text");
  15136. ASSERT_EQ("text default", text);
  15137. res.set_content("ok", "text/plain");
  15138. handled = true;
  15139. });
  15140. thread t = thread([&] { svr.listen(HOST, PORT); });
  15141. auto se = detail::scope_exit([&] {
  15142. svr.stop();
  15143. t.join();
  15144. ASSERT_FALSE(svr.is_running());
  15145. ASSERT_TRUE(handled);
  15146. });
  15147. svr.wait_until_ready();
  15148. auto req = "POST /test HTTP/1.1\r\n"
  15149. "Host: localhost\r\n"
  15150. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15151. "Content-Length: 399\r\n"
  15152. "\r\n"
  15153. "----------\r\n"
  15154. "Content-Disposition: form-data; name=\"text\"\r\n"
  15155. "\r\n"
  15156. "text default\r\n"
  15157. "----------\r\n"
  15158. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15159. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15160. "Content-Type: text/plain\r\n"
  15161. "\r\n"
  15162. "Content of a.txt.\r\n"
  15163. "\r\n"
  15164. "----------\r\n"
  15165. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15166. "\"a.html\"\r\n"
  15167. "Content-Type: text/html\r\n"
  15168. "\r\n"
  15169. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15170. "\r\n"
  15171. "------------\r\n";
  15172. ASSERT_TRUE(send_request(1, req));
  15173. }
  15174. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15175. auto handled = false;
  15176. Server svr;
  15177. svr.Post("/test", [&](const Request &req, Response &res) {
  15178. // Case-insensitive "utf-8''" prefix with a long value
  15179. const auto &file = req.form.get_file("file1");
  15180. ASSERT_EQ("file1", file.name);
  15181. // 8000 chars exercises both the Content-Disposition parser and the
  15182. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15183. // Prior to the fix, std::regex_match on this header would cause O(N)
  15184. // stack recursion in libstdc++, leading to SIGSEGV.
  15185. std::string expected_filename(8000, 'A');
  15186. ASSERT_EQ(expected_filename, file.filename);
  15187. res.set_content("ok", "text/plain");
  15188. handled = true;
  15189. });
  15190. thread t = thread([&] { svr.listen(HOST, PORT); });
  15191. auto se = detail::scope_exit([&] {
  15192. svr.stop();
  15193. t.join();
  15194. ASSERT_FALSE(svr.is_running());
  15195. ASSERT_TRUE(handled);
  15196. });
  15197. svr.wait_until_ready();
  15198. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15199. // Regression test for GHSA-qq6v-r583-3h69
  15200. std::string long_filename(8000, 'A');
  15201. std::string body = "----------\r\n"
  15202. "Content-Disposition: form-data; name=\"file1\"; "
  15203. "filename*=\"Utf-8''" +
  15204. long_filename +
  15205. "\"\r\n"
  15206. "\r\n"
  15207. "hello\r\n"
  15208. "------------\r\n";
  15209. auto req = "POST /test HTTP/1.1\r\n"
  15210. "Host: localhost\r\n"
  15211. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15212. "Content-Length: " +
  15213. std::to_string(body.size()) + "\r\n\r\n" + body;
  15214. ASSERT_TRUE(send_request(1, req));
  15215. }
  15216. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15217. auto handled = false;
  15218. Server svr;
  15219. svr.Post("/test", [&](const Request &req, Response &) {
  15220. ASSERT_EQ(2u, req.form.fields.size());
  15221. const auto &text1 = req.form.get_field("text1");
  15222. ASSERT_EQ("text1", text1);
  15223. const auto &text2 = req.form.get_field("text2");
  15224. ASSERT_EQ("text2", text2);
  15225. handled = true;
  15226. });
  15227. thread t = thread([&] { svr.listen(HOST, PORT); });
  15228. auto se = detail::scope_exit([&] {
  15229. svr.stop();
  15230. t.join();
  15231. ASSERT_FALSE(svr.is_running());
  15232. ASSERT_TRUE(handled);
  15233. });
  15234. svr.wait_until_ready();
  15235. auto req = "POST /test HTTP/1.1\r\n"
  15236. "Host: localhost\r\n"
  15237. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15238. "Content-Length: 146\r\n"
  15239. "\r\n----------\r\n"
  15240. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15241. "\r\n"
  15242. "text1"
  15243. "\r\n----------\r\n"
  15244. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15245. "\r\n"
  15246. "text2"
  15247. "\r\n------------";
  15248. std::string response;
  15249. ASSERT_TRUE(send_request(1, req, &response));
  15250. ASSERT_EQ("200", response.substr(9, 3));
  15251. }
  15252. TEST(MultipartFormDataTest, ContentLength) {
  15253. auto handled = false;
  15254. Server svr;
  15255. svr.Post("/test", [&](const Request &req, Response &) {
  15256. ASSERT_EQ(2u, req.form.fields.size());
  15257. const auto &text1 = req.form.get_field("text1");
  15258. ASSERT_EQ("text1", text1);
  15259. const auto &text2 = req.form.get_field("text2");
  15260. ASSERT_EQ("text2", text2);
  15261. handled = true;
  15262. });
  15263. thread t = thread([&] { svr.listen(HOST, PORT); });
  15264. auto se = detail::scope_exit([&] {
  15265. svr.stop();
  15266. t.join();
  15267. ASSERT_FALSE(svr.is_running());
  15268. ASSERT_TRUE(handled);
  15269. });
  15270. svr.wait_until_ready();
  15271. auto req = "POST /test HTTP/1.1\r\n"
  15272. "Host: localhost\r\n"
  15273. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15274. "Content-Length: 167\r\n"
  15275. "\r\n----------\r\n"
  15276. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15277. "Content-Length: 5\r\n"
  15278. "\r\n"
  15279. "text1"
  15280. "\r\n----------\r\n"
  15281. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15282. "\r\n"
  15283. "text2"
  15284. "\r\n------------\r\n";
  15285. std::string response;
  15286. ASSERT_TRUE(send_request(1, req, &response));
  15287. ASSERT_EQ("200", response.substr(9, 3));
  15288. }
  15289. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15290. auto handled = false;
  15291. Server svr;
  15292. svr.Post("/test", [&](const Request &req, Response &) {
  15293. ASSERT_EQ(2u, req.form.fields.size());
  15294. const auto &text1 = req.form.get_field("text1");
  15295. ASSERT_EQ("text1", text1);
  15296. // TODO: Add header access for text fields if needed
  15297. const auto &text2 = req.form.get_field("text2");
  15298. ASSERT_EQ("text2", text2);
  15299. // TODO: Header access for text fields needs to be implemented
  15300. // auto &headers = it->second.headers;
  15301. // ASSERT_EQ(3U, headers.size());
  15302. // auto custom_header = headers.find("x-whatever");
  15303. // ASSERT_TRUE(custom_header != headers.end());
  15304. // ASSERT_NE("customvalue", custom_header->second);
  15305. // ASSERT_EQ("CustomValue", custom_header->second);
  15306. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15307. handled = true;
  15308. });
  15309. thread t = thread([&] { svr.listen(HOST, PORT); });
  15310. auto se = detail::scope_exit([&] {
  15311. svr.stop();
  15312. t.join();
  15313. ASSERT_FALSE(svr.is_running());
  15314. ASSERT_TRUE(handled);
  15315. });
  15316. svr.wait_until_ready();
  15317. auto req = "POST /test HTTP/1.1\r\n"
  15318. "Host: localhost\r\n"
  15319. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15320. "Content-Length: 232\r\n"
  15321. "\r\n----------\r\n"
  15322. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15323. "Content-Length: 5\r\n"
  15324. "X-Test: 1\r\n"
  15325. "\r\n"
  15326. "text1"
  15327. "\r\n----------\r\n"
  15328. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15329. "Content-Type: text/plain\r\n"
  15330. "X-Whatever: CustomValue\r\n"
  15331. "\r\n"
  15332. "text2"
  15333. "\r\n------------\r\n"
  15334. "That should be disregarded. Not even read";
  15335. std::string response;
  15336. ASSERT_TRUE(send_request(1, req, &response));
  15337. ASSERT_EQ("200", response.substr(9, 3));
  15338. }
  15339. TEST(MultipartFormDataTest, LargeHeader) {
  15340. auto handled = false;
  15341. Server svr;
  15342. svr.Post("/test", [&](const Request &req, Response &) {
  15343. ASSERT_EQ(1u, req.form.fields.size());
  15344. const auto &text = req.form.get_field("name1");
  15345. ASSERT_EQ("text1", text);
  15346. handled = true;
  15347. });
  15348. thread t = thread([&] { svr.listen(HOST, PORT); });
  15349. auto se = detail::scope_exit([&] {
  15350. svr.stop();
  15351. t.join();
  15352. ASSERT_FALSE(svr.is_running());
  15353. ASSERT_TRUE(handled);
  15354. });
  15355. svr.wait_until_ready();
  15356. auto boundary = std::string("cpp-httplib-multipart-data");
  15357. std::string content = "--" + boundary +
  15358. "\r\n"
  15359. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15360. "\r\n"
  15361. "text1\r\n"
  15362. "--" +
  15363. boundary + "--\r\n";
  15364. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15365. "Host: localhost\r\n"
  15366. "Content-Type: multipart/form-data;boundary=" +
  15367. boundary +
  15368. "\r\n"
  15369. "Content-Length: " +
  15370. std::to_string(content.size()) +
  15371. "\r\n"
  15372. "Dummy-Header: ";
  15373. std::string header_suffix = "\r\n"
  15374. "\r\n";
  15375. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15376. size_t header_dummy_size =
  15377. read_buff_size -
  15378. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15379. auto header_dummy = std::string(header_dummy_size, '@');
  15380. auto req = header_prefix + header_dummy + header_suffix + content;
  15381. std::string response;
  15382. ASSERT_TRUE(send_request(1, req, &response));
  15383. ASSERT_EQ("200", response.substr(9, 3));
  15384. }
  15385. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15386. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15387. // (not chunked Transfer-Encoding) after the streaming refactor.
  15388. auto handled = false;
  15389. Server svr;
  15390. svr.Post("/upload", [&](const Request &req, Response &res) {
  15391. auto cl_it = req.headers.find("Content-Length");
  15392. EXPECT_TRUE(cl_it != req.headers.end());
  15393. auto te_it = req.headers.find("Transfer-Encoding");
  15394. EXPECT_TRUE(te_it == req.headers.end());
  15395. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15396. res.set_content("ok", "text/plain");
  15397. handled = true;
  15398. });
  15399. auto port = svr.bind_to_any_port(HOST);
  15400. auto t = thread([&] { svr.listen_after_bind(); });
  15401. auto se = detail::scope_exit([&] {
  15402. svr.stop();
  15403. t.join();
  15404. ASSERT_FALSE(svr.is_running());
  15405. ASSERT_TRUE(handled);
  15406. });
  15407. svr.wait_until_ready();
  15408. UploadFormDataItems items = {
  15409. {"field1", "hello", "", "text/plain"},
  15410. {"file1", "world", "test.txt", "application/octet-stream"},
  15411. };
  15412. Client cli(HOST, port);
  15413. auto res = cli.Post("/upload", {}, items);
  15414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15415. EXPECT_EQ(StatusCode::OK_200, res->status);
  15416. }
  15417. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15418. // Verify that make_multipart_content_provider coalesces many small segments
  15419. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15420. constexpr size_t kItemCount = 1000;
  15421. UploadFormDataItems items;
  15422. items.reserve(kItemCount);
  15423. for (size_t i = 0; i < kItemCount; i++) {
  15424. items.push_back(
  15425. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15426. }
  15427. const std::string boundary = "----test-boundary";
  15428. auto content_length = detail::get_multipart_content_length(items, boundary);
  15429. auto provider = detail::make_multipart_content_provider(items, boundary);
  15430. // Drive the provider the same way write_content_with_progress does
  15431. size_t write_count = 0;
  15432. size_t total_bytes = 0;
  15433. DataSink sink;
  15434. size_t offset = 0;
  15435. sink.write = [&](const char *d, size_t l) -> bool {
  15436. (void)d;
  15437. write_count++;
  15438. total_bytes += l;
  15439. offset += l;
  15440. return true;
  15441. };
  15442. sink.is_writable = []() -> bool { return true; };
  15443. while (offset < content_length) {
  15444. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15445. }
  15446. EXPECT_EQ(content_length, total_bytes);
  15447. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15448. // With buffering into 64KB blocks, write_count should be much smaller.
  15449. auto segment_count = 3 * kItemCount + 1;
  15450. EXPECT_LT(write_count, segment_count / 10);
  15451. }
  15452. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15453. // Integration test: send many UploadFormDataItems and verify the server
  15454. // receives all of them correctly (#2410).
  15455. constexpr size_t kItemCount = 500;
  15456. auto handled = false;
  15457. Server svr;
  15458. svr.Post("/upload", [&](const Request &req, Response &res) {
  15459. EXPECT_EQ(kItemCount, req.form.fields.size());
  15460. for (size_t i = 0; i < kItemCount; i++) {
  15461. auto key = "field" + std::to_string(i);
  15462. auto val = "value" + std::to_string(i);
  15463. auto it = req.form.fields.find(key);
  15464. if (it != req.form.fields.end()) {
  15465. EXPECT_EQ(val, it->second.content);
  15466. } else {
  15467. ADD_FAILURE() << "Missing field: " << key;
  15468. }
  15469. }
  15470. res.set_content("ok", "text/plain");
  15471. handled = true;
  15472. });
  15473. auto port = svr.bind_to_any_port(HOST);
  15474. auto t = thread([&] { svr.listen_after_bind(); });
  15475. auto se = detail::scope_exit([&] {
  15476. svr.stop();
  15477. t.join();
  15478. ASSERT_FALSE(svr.is_running());
  15479. ASSERT_TRUE(handled);
  15480. });
  15481. svr.wait_until_ready();
  15482. UploadFormDataItems items;
  15483. items.reserve(kItemCount);
  15484. for (size_t i = 0; i < kItemCount; i++) {
  15485. items.push_back(
  15486. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15487. }
  15488. Client cli(HOST, port);
  15489. auto res = cli.Post("/upload", items);
  15490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15491. EXPECT_EQ(StatusCode::OK_200, res->status);
  15492. }
  15493. TEST(MultipartFormDataTest, MakeFileProvider) {
  15494. // Verify make_file_provider sends a file's contents correctly.
  15495. const std::string file_content(4096, 'Z');
  15496. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15497. {
  15498. std::ofstream ofs(tmp_path, std::ios::binary);
  15499. ofs.write(file_content.data(),
  15500. static_cast<std::streamsize>(file_content.size()));
  15501. }
  15502. auto handled = false;
  15503. Server svr;
  15504. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15505. const ContentReader &content_reader) {
  15506. ASSERT_TRUE(req.is_multipart_form_data());
  15507. std::vector<FormData> items;
  15508. content_reader(
  15509. [&](const FormData &file) {
  15510. items.push_back(file);
  15511. return true;
  15512. },
  15513. [&](const char *data, size_t data_length) {
  15514. items.back().content.append(data, data_length);
  15515. return true;
  15516. });
  15517. ASSERT_EQ(1u, items.size());
  15518. EXPECT_EQ("myfile", items[0].name);
  15519. EXPECT_EQ("data.bin", items[0].filename);
  15520. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15521. EXPECT_EQ(file_content, items[0].content);
  15522. handled = true;
  15523. });
  15524. auto port = svr.bind_to_any_port(HOST);
  15525. auto t = thread([&] { svr.listen_after_bind(); });
  15526. auto se = detail::scope_exit([&] {
  15527. svr.stop();
  15528. t.join();
  15529. ASSERT_FALSE(svr.is_running());
  15530. ASSERT_TRUE(handled);
  15531. std::remove(tmp_path.c_str());
  15532. });
  15533. svr.wait_until_ready();
  15534. FormDataProviderItems providers;
  15535. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15536. "application/octet-stream"));
  15537. Client cli(HOST, port);
  15538. auto res = cli.Post("/upload", {}, {}, providers);
  15539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15540. EXPECT_EQ(StatusCode::OK_200, res->status);
  15541. }
  15542. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15543. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15544. // (100) headers is rejected with a 400 Bad Request response.
  15545. Server svr;
  15546. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15547. res.set_content("ok", "text/plain");
  15548. });
  15549. thread t = thread([&] { svr.listen(HOST, PORT); });
  15550. auto se = detail::scope_exit([&] {
  15551. svr.stop();
  15552. t.join();
  15553. ASSERT_FALSE(svr.is_running());
  15554. });
  15555. svr.wait_until_ready();
  15556. // Build a multipart part with 101 custom headers (exceeding
  15557. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15558. std::stringstream body;
  15559. body << "--simpleboundary\r\n"
  15560. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15561. for (int i = 0; i < 101; i++) {
  15562. body << "X-Custom-Header-" << i << ": value\r\n";
  15563. }
  15564. body << "\r\n"
  15565. << "value1\r\n"
  15566. << "--simpleboundary--\r\n";
  15567. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15568. Client cli(HOST, PORT);
  15569. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15571. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15572. }
  15573. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15574. // A body that never contains the declared boundary must not be accumulated
  15575. // while the parser waits for it. Buffering it would also make every read
  15576. // rescan everything seen so far, which is quadratic in the body size.
  15577. Server svr;
  15578. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15579. res.set_content("ok", "text/plain");
  15580. });
  15581. auto port = svr.bind_to_any_port(HOST);
  15582. thread t = thread([&] { svr.listen_after_bind(); });
  15583. auto se = detail::scope_exit([&] {
  15584. svr.stop();
  15585. t.join();
  15586. ASSERT_FALSE(svr.is_running());
  15587. });
  15588. svr.wait_until_ready();
  15589. Client cli(HOST, port);
  15590. cli.set_read_timeout(60, 0);
  15591. cli.set_write_timeout(60, 0);
  15592. // '-' is the worst case: it matches the first character of the boundary, so
  15593. // every position has to be checked against it.
  15594. auto post_dashes = [&](size_t size) {
  15595. const std::string body(size, '-');
  15596. auto start = std::chrono::steady_clock::now();
  15597. auto res =
  15598. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15599. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15600. std::chrono::steady_clock::now() - start)
  15601. .count();
  15602. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15603. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15604. return ms;
  15605. };
  15606. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15607. // Windows.
  15608. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15609. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15610. // Comparing the two sizes rather than checking an absolute duration keeps
  15611. // this meaningful across build types and CI load, both of which move the
  15612. // absolute numbers by more than an order of magnitude. Four times the bytes
  15613. // costs about four times the time when parsing is linear, and about sixteen
  15614. // times when the body is buffered and rescanned.
  15615. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15616. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15617. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15618. << "ms, which suggests the body is being buffered and rescanned";
  15619. }
  15620. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15621. // A boundary can only be followed by CRLF or by "--", so anything else is
  15622. // malformed no matter what comes next. The parser must say so right away
  15623. // instead of buffering the rest of the declared body.
  15624. Server svr;
  15625. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15626. res.set_content("ok", "text/plain");
  15627. });
  15628. auto port = svr.bind_to_any_port(HOST);
  15629. thread t = thread([&] { svr.listen_after_bind(); });
  15630. auto se = detail::scope_exit([&] {
  15631. svr.stop();
  15632. t.join();
  15633. ASSERT_FALSE(svr.is_running());
  15634. });
  15635. svr.wait_until_ready();
  15636. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15637. // buffers instead of failing would still be waiting for the remaining bytes.
  15638. const std::string body = "--zzzz\r\n"
  15639. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15640. "\r\n"
  15641. "text1"
  15642. "\r\n--zzzzXX";
  15643. const std::string req = "POST /post HTTP/1.1\r\n"
  15644. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15645. "Content-Length: 1048576\r\n"
  15646. "\r\n" +
  15647. body;
  15648. std::string response;
  15649. ASSERT_TRUE(send_request(3, req, &response, port));
  15650. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15651. EXPECT_EQ("400", response.substr(9, 3));
  15652. }
  15653. // Posts a multipart body split into two writes, so that the server sees the
  15654. // split at whatever offset the caller chose, and expects the single "text1"
  15655. // field to come through.
  15656. static void expect_split_multipart_ok(const std::string &body1,
  15657. const std::string &body2) {
  15658. auto handled = false;
  15659. Server svr;
  15660. svr.Post("/post", [&](const Request &req, Response &) {
  15661. EXPECT_EQ(1u, req.form.fields.size());
  15662. EXPECT_EQ("text1", req.form.get_field("text1"));
  15663. handled = true;
  15664. });
  15665. auto port = svr.bind_to_any_port(HOST);
  15666. thread t = thread([&] { svr.listen_after_bind(); });
  15667. auto se = detail::scope_exit([&] {
  15668. svr.stop();
  15669. t.join();
  15670. ASSERT_FALSE(svr.is_running());
  15671. ASSERT_TRUE(handled);
  15672. });
  15673. svr.wait_until_ready();
  15674. // "Connection: close" makes the server close once it has answered, so the
  15675. // response drain ends immediately instead of idling until the read timeout.
  15676. const std::string head =
  15677. "POST /post HTTP/1.1\r\n"
  15678. "Host: localhost\r\n"
  15679. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15680. "Connection: close\r\n"
  15681. "Content-Length: " +
  15682. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15683. std::string response;
  15684. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15685. ASSERT_GE(response.size(), 12u) << "no response";
  15686. EXPECT_EQ("200", response.substr(9, 3));
  15687. }
  15688. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15689. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15690. // ignored, including when it does not arrive in the same read as the
  15691. // close-delimiter itself.
  15692. expect_split_multipart_ok("--zzzz\r\n"
  15693. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15694. "\r\n"
  15695. "text1"
  15696. "\r\n--zzzz--",
  15697. "\r\nthis epilogue must be ignored\r\n");
  15698. }
  15699. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15700. // The initial boundary may be preceded by a preamble of any length and may
  15701. // straddle a read boundary. Discarding data while waiting for it must not
  15702. // throw away a partial boundary sitting at the end of the buffer.
  15703. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15704. "zz\r\n"
  15705. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15706. "\r\n"
  15707. "text1"
  15708. "\r\n--zzzz--\r\n");
  15709. }
  15710. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15711. // The received boundary was only checked for being non-empty, so it could be
  15712. // as long as a header is allowed to be. The parser scans the body for
  15713. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15714. // costs a nearly full comparison at nearly every position, making the
  15715. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15716. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15717. Server svr;
  15718. svr.Post("/post", [](const Request &req, Response &res) {
  15719. EXPECT_EQ(1u, req.form.fields.size());
  15720. EXPECT_EQ("text1", req.form.get_field("text1"));
  15721. res.set_content("ok", "text/plain");
  15722. });
  15723. auto port = svr.bind_to_any_port(HOST);
  15724. thread t = thread([&] { svr.listen_after_bind(); });
  15725. auto se = detail::scope_exit([&] {
  15726. svr.stop();
  15727. t.join();
  15728. ASSERT_FALSE(svr.is_running());
  15729. });
  15730. svr.wait_until_ready();
  15731. Client cli(HOST, port);
  15732. auto post_with_boundary_of_length = [&](size_t len) {
  15733. const std::string boundary(len, 'a');
  15734. const std::string body =
  15735. "--" + boundary +
  15736. "\r\n"
  15737. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15738. "\r\n"
  15739. "text1"
  15740. "\r\n--" +
  15741. boundary + "--\r\n";
  15742. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15743. };
  15744. auto res = post_with_boundary_of_length(70);
  15745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15746. EXPECT_EQ(StatusCode::OK_200, res->status);
  15747. res = post_with_boundary_of_length(71);
  15748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15749. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15750. }
  15751. TEST(MakeFileBodyTest, Basic) {
  15752. const std::string file_content(4096, 'Z');
  15753. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15754. {
  15755. std::ofstream ofs(tmp_path, std::ios::binary);
  15756. ofs.write(file_content.data(),
  15757. static_cast<std::streamsize>(file_content.size()));
  15758. }
  15759. auto handled = false;
  15760. Server svr;
  15761. svr.Post("/upload", [&](const Request &req, Response &res) {
  15762. EXPECT_EQ(file_content, req.body);
  15763. handled = true;
  15764. res.status = StatusCode::OK_200;
  15765. });
  15766. auto port = svr.bind_to_any_port(HOST);
  15767. auto t = thread([&] { svr.listen_after_bind(); });
  15768. auto se = detail::scope_exit([&] {
  15769. svr.stop();
  15770. t.join();
  15771. ASSERT_FALSE(svr.is_running());
  15772. ASSERT_TRUE(handled);
  15773. std::remove(tmp_path.c_str());
  15774. });
  15775. svr.wait_until_ready();
  15776. auto fb = make_file_body(tmp_path);
  15777. ASSERT_GT(fb.first, 0u);
  15778. Client cli(HOST, port);
  15779. auto res =
  15780. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15782. EXPECT_EQ(StatusCode::OK_200, res->status);
  15783. }
  15784. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15785. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15786. {
  15787. std::ofstream ofs(path, std::ios::binary);
  15788. const std::string content(100, 'A');
  15789. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15790. }
  15791. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15792. auto body = make_file_body(path);
  15793. ASSERT_EQ(100u, body.first);
  15794. ASSERT_TRUE(static_cast<bool>(body.second));
  15795. // Rewritten shorter after its length was measured - and, on a server, after
  15796. // that length has already gone out as Content-Length.
  15797. {
  15798. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15799. const std::string content(10, 'A');
  15800. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15801. }
  15802. std::string written;
  15803. DataSink sink;
  15804. sink.write = [&](const char *d, size_t l) {
  15805. written.append(d, l);
  15806. return true;
  15807. };
  15808. // The provider has to report failure. write_content_with_progress() advances
  15809. // its offset only by what was written, so a provider that returns true
  15810. // without completing the length it promised is called again straight away,
  15811. // and again.
  15812. EXPECT_FALSE(body.second(0, body.first, sink));
  15813. EXPECT_EQ(std::string(10, 'A'), written);
  15814. }
  15815. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15816. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15817. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15818. {
  15819. std::ofstream ofs(path, std::ios::binary);
  15820. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15821. }
  15822. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15823. auto body = make_file_body(path);
  15824. ASSERT_EQ(content.size(), body.first);
  15825. ASSERT_TRUE(static_cast<bool>(body.second));
  15826. std::string written;
  15827. DataSink sink;
  15828. sink.write = [&](const char *d, size_t l) {
  15829. written.append(d, l);
  15830. return true;
  15831. };
  15832. EXPECT_TRUE(body.second(0, body.first, sink));
  15833. EXPECT_EQ(content, written);
  15834. }
  15835. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15836. static constexpr unsigned int number_of_tasks{1000000};
  15837. std::atomic_uint count{0};
  15838. std::unique_ptr<TaskQueue> task_queue{
  15839. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15840. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15841. auto queued = task_queue->enqueue(
  15842. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15843. EXPECT_TRUE(queued);
  15844. }
  15845. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15846. task_queue->shutdown();
  15847. #else
  15848. EXPECT_NO_THROW(task_queue->shutdown());
  15849. #endif
  15850. EXPECT_EQ(number_of_tasks, count.load());
  15851. }
  15852. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15853. static constexpr unsigned int number_of_tasks{1000000};
  15854. static constexpr unsigned int qlimit{2};
  15855. unsigned int queued_count{0};
  15856. std::atomic_uint count{0};
  15857. std::unique_ptr<TaskQueue> task_queue{
  15858. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15859. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15860. if (task_queue->enqueue(
  15861. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15862. queued_count++;
  15863. }
  15864. }
  15865. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15866. task_queue->shutdown();
  15867. #else
  15868. EXPECT_NO_THROW(task_queue->shutdown());
  15869. #endif
  15870. EXPECT_EQ(queued_count, count.load());
  15871. EXPECT_TRUE(queued_count <= number_of_tasks);
  15872. EXPECT_TRUE(queued_count >= qlimit);
  15873. }
  15874. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15875. // Use a short idle timeout so a dynamic thread spawns, times out and
  15876. // exits during the test, and the pool keeps working afterwards.
  15877. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15878. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15879. /*idle_timeout_sec=*/1}};
  15880. std::atomic_uint count{0};
  15881. std::condition_variable cv;
  15882. std::mutex mtx;
  15883. bool release = false;
  15884. // Block the base thread so the second task spawns a dynamic thread.
  15885. EXPECT_TRUE(task_queue->enqueue([&] {
  15886. std::unique_lock<std::mutex> lock(mtx);
  15887. while (!release) {
  15888. cv.wait(lock);
  15889. }
  15890. count++;
  15891. }));
  15892. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15893. // Let the dynamic thread finish its task and exceed the idle timeout.
  15894. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15895. {
  15896. std::unique_lock<std::mutex> lock(mtx);
  15897. release = true;
  15898. }
  15899. cv.notify_all();
  15900. // The pool must still accept and run tasks after the dynamic thread exited.
  15901. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15902. task_queue->shutdown();
  15903. EXPECT_EQ(3u, count.load());
  15904. }
  15905. TEST(TaskQueueTest, MaxQueuedRequests) {
  15906. static constexpr unsigned int qlimit{3};
  15907. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15908. std::condition_variable sem_cv;
  15909. std::mutex sem_mtx;
  15910. int credits = 0;
  15911. bool queued;
  15912. /* Fill up the queue with tasks that will block until we give them credits to
  15913. * complete. */
  15914. for (unsigned int n = 0; n <= qlimit;) {
  15915. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15916. std::unique_lock<std::mutex> lock(sem_mtx);
  15917. while (credits <= 0) {
  15918. sem_cv.wait(lock);
  15919. }
  15920. /* Consume the credit and signal the test code if they are all gone. */
  15921. if (--credits == 0) { sem_cv.notify_one(); }
  15922. });
  15923. if (n < qlimit) {
  15924. /* The first qlimit enqueues must succeed. */
  15925. EXPECT_TRUE(queued);
  15926. } else {
  15927. /* The last one will succeed only when the worker thread
  15928. * starts and dequeues the first blocking task. Although
  15929. * not necessary for the correctness of this test, we sleep for
  15930. * a short while to avoid busy waiting. */
  15931. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15932. }
  15933. if (queued) { n++; }
  15934. }
  15935. /* Further enqueues must fail since the queue is full. */
  15936. for (auto i = 0; i < 4; i++) {
  15937. queued = task_queue->enqueue([] {});
  15938. EXPECT_FALSE(queued);
  15939. }
  15940. /* Give the credits to allow the previous tasks to complete. */
  15941. {
  15942. std::unique_lock<std::mutex> lock(sem_mtx);
  15943. credits += qlimit + 1;
  15944. }
  15945. sem_cv.notify_all();
  15946. /* Wait for all the credits to be consumed. */
  15947. {
  15948. std::unique_lock<std::mutex> lock(sem_mtx);
  15949. while (credits > 0) {
  15950. sem_cv.wait(lock);
  15951. }
  15952. }
  15953. /* Check that we are able again to enqueue at least qlimit tasks. */
  15954. for (unsigned int i = 0; i < qlimit; i++) {
  15955. queued = task_queue->enqueue([] {});
  15956. EXPECT_TRUE(queued);
  15957. }
  15958. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15959. task_queue->shutdown();
  15960. #else
  15961. EXPECT_NO_THROW(task_queue->shutdown());
  15962. #endif
  15963. }
  15964. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15965. Server svr;
  15966. std::string method;
  15967. std::string body;
  15968. auto has_content_length = false;
  15969. auto has_transfer_encoding = false;
  15970. std::atomic<int> bad_requests{0};
  15971. // Leftover body bytes get parsed as a malformed request and answered with
  15972. // 400
  15973. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15974. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15975. });
  15976. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15977. res.set_redirect("/down", StatusCode::SeeOther_303);
  15978. });
  15979. svr.Get("/down", [&](const Request &req, Response &res) {
  15980. method = req.method;
  15981. body = req.body;
  15982. has_content_length = req.has_header("Content-Length");
  15983. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15984. res.set_content("ok", "text/plain");
  15985. });
  15986. auto port = svr.bind_to_any_port(HOST);
  15987. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15988. auto se = detail::scope_exit([&] {
  15989. svr.stop();
  15990. thread.join();
  15991. ASSERT_FALSE(svr.is_running());
  15992. });
  15993. svr.wait_until_ready();
  15994. const std::string payload = "SECRET-BODY";
  15995. auto check = [&](Client &cli, const Result &res) {
  15996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15997. EXPECT_EQ(StatusCode::OK_200, res->status);
  15998. EXPECT_EQ("ok", res->body);
  15999. EXPECT_EQ("GET", method);
  16000. EXPECT_TRUE(body.empty());
  16001. EXPECT_FALSE(has_content_length);
  16002. EXPECT_FALSE(has_transfer_encoding);
  16003. // Nothing of the original body may be left on the connection
  16004. auto res2 = cli.Get("/down");
  16005. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16006. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16007. EXPECT_EQ("ok", res2->body);
  16008. EXPECT_EQ(0, bad_requests);
  16009. };
  16010. // With content length
  16011. {
  16012. Client cli(HOST, port);
  16013. cli.set_keep_alive(true);
  16014. cli.set_follow_location(true);
  16015. auto res = cli.Post(
  16016. "/up", payload.size(),
  16017. [&](size_t offset, size_t length, DataSink &sink) {
  16018. return sink.write(payload.data() + offset, length);
  16019. },
  16020. "text/plain");
  16021. check(cli, res);
  16022. }
  16023. // Without content length (chunked)
  16024. {
  16025. Client cli(HOST, port);
  16026. cli.set_keep_alive(true);
  16027. cli.set_follow_location(true);
  16028. auto res = cli.Post(
  16029. "/up",
  16030. [&](size_t /*offset*/, DataSink &sink) {
  16031. sink.write(payload.data(), payload.size());
  16032. sink.done();
  16033. return true;
  16034. },
  16035. "text/plain");
  16036. check(cli, res);
  16037. }
  16038. }
  16039. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16040. Server svr;
  16041. std::string target;
  16042. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16043. // Echo the still-encoded name back in the Location
  16044. const std::string prefix = "/start/";
  16045. res.status = StatusCode::Found_302;
  16046. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16047. });
  16048. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16049. target = req.target;
  16050. res.set_content("ok", "text/plain");
  16051. });
  16052. auto port = svr.bind_to_any_port(HOST);
  16053. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16054. auto se = detail::scope_exit([&] {
  16055. svr.stop();
  16056. thread.join();
  16057. ASSERT_FALSE(svr.is_running());
  16058. });
  16059. svr.wait_until_ready();
  16060. // Decoding the Location path would turn the first four into a path
  16061. // separator, a query delimiter, a fragment delimiter and a different
  16062. // percent-encoded octet. The rest must keep reaching the server as they are.
  16063. const std::vector<std::string> names = {
  16064. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16065. };
  16066. for (auto path_encode : {true, false}) {
  16067. Client cli(HOST, port);
  16068. cli.set_follow_location(true);
  16069. cli.set_path_encode(path_encode);
  16070. for (const auto &name : names) {
  16071. target.clear();
  16072. auto res = cli.Get("/start/" + name);
  16073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16074. EXPECT_EQ(StatusCode::OK_200, res->status);
  16075. EXPECT_EQ("/dest/" + name, target);
  16076. }
  16077. }
  16078. }
  16079. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16080. Server svr;
  16081. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16082. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16083. });
  16084. svr.Get("/hello", [](const Request &req, Response &res) {
  16085. res.set_content(req.get_param_value("key"), "text/plain");
  16086. });
  16087. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16088. auto se = detail::scope_exit([&] {
  16089. svr.stop();
  16090. thread.join();
  16091. ASSERT_FALSE(svr.is_running());
  16092. });
  16093. svr.wait_until_ready();
  16094. {
  16095. Client cli(HOST, PORT);
  16096. cli.set_follow_location(true);
  16097. auto res = cli.Get("/");
  16098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16099. EXPECT_EQ(StatusCode::OK_200, res->status);
  16100. EXPECT_EQ("val&key2=val2", res->body);
  16101. }
  16102. }
  16103. #endif
  16104. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16105. Server svr;
  16106. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16107. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16108. });
  16109. svr.Get("/hello", [](const Request &req, Response &res) {
  16110. res.set_content(req.get_param_value("key"), "text/plain");
  16111. });
  16112. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16113. auto se = detail::scope_exit([&] {
  16114. svr.stop();
  16115. thread.join();
  16116. ASSERT_FALSE(svr.is_running());
  16117. });
  16118. svr.wait_until_ready();
  16119. {
  16120. Client cli(HOST, PORT);
  16121. cli.set_follow_location(true);
  16122. auto res = cli.Get("/");
  16123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16124. EXPECT_EQ(StatusCode::OK_200, res->status);
  16125. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16126. }
  16127. }
  16128. TEST(RedirectTest, RedirectWithPlusInPath) {
  16129. Server svr;
  16130. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16131. res.set_redirect("/a+b");
  16132. });
  16133. // Route pattern uses regex; escape + as \\+
  16134. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16135. res.set_content(req.path, "text/plain");
  16136. });
  16137. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16138. auto se = detail::scope_exit([&] {
  16139. svr.stop();
  16140. thread.join();
  16141. ASSERT_FALSE(svr.is_running());
  16142. });
  16143. svr.wait_until_ready();
  16144. {
  16145. Client cli(HOST, PORT);
  16146. cli.set_follow_location(true);
  16147. auto res = cli.Get("/");
  16148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16149. EXPECT_EQ(StatusCode::OK_200, res->status);
  16150. EXPECT_EQ("/a+b", res->body);
  16151. }
  16152. }
  16153. TEST(RedirectTest, ResolveRelativeLocation) {
  16154. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16155. const std::vector<std::pair<std::string, std::string>> cases = {
  16156. {"g", "/b/c/g"},
  16157. {"./g", "/b/c/g"},
  16158. {"g/", "/b/c/g/"},
  16159. {"?y", "/b/c/d;p?y"},
  16160. {"g?y", "/b/c/g?y"},
  16161. {"#s", "/b/c/d;p?q#s"},
  16162. {"g#s", "/b/c/g#s"},
  16163. {"g?y#s", "/b/c/g?y#s"},
  16164. {";x", "/b/c/;x"},
  16165. {"g;x", "/b/c/g;x"},
  16166. {".", "/b/c/"},
  16167. {"./", "/b/c/"},
  16168. {"..", "/b/"},
  16169. {"../", "/b/"},
  16170. {"../g", "/b/g"},
  16171. {"../..", "/"},
  16172. {"../../", "/"},
  16173. {"../../g", "/g"},
  16174. {"../../../g", "/g"},
  16175. {"g.", "/b/c/g."},
  16176. {".g", "/b/c/.g"},
  16177. {"g..", "/b/c/g.."},
  16178. {"..g", "/b/c/..g"},
  16179. {"./../g", "/b/g"},
  16180. {"./g/.", "/b/c/g/"},
  16181. {"g/./h", "/b/c/g/h"},
  16182. {"g/../h", "/b/c/h"},
  16183. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16184. {"g;x=1/../y", "/b/c/y"},
  16185. {"g?y/./x", "/b/c/g?y/./x"},
  16186. {"g#s/../x", "/b/c/g#s/../x"},
  16187. // Not relative-path references, so left for parse_url.
  16188. {"/g", "/g"},
  16189. {"//g", "//g"},
  16190. {"http://g/x", "http://g/x"},
  16191. {"g:h", "g:h"},
  16192. };
  16193. for (const auto &c : cases) {
  16194. EXPECT_EQ(c.second,
  16195. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16196. << c.first;
  16197. }
  16198. }
  16199. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16200. Server svr;
  16201. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16202. res.set_redirect(req.get_param_value("to"));
  16203. });
  16204. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16205. res.set_content(req.target, "text/plain");
  16206. });
  16207. svr.Get("/other", [](const Request &req, Response &res) {
  16208. res.set_content(req.target, "text/plain");
  16209. });
  16210. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16211. auto se = detail::scope_exit([&] {
  16212. svr.stop();
  16213. thread.join();
  16214. ASSERT_FALSE(svr.is_running());
  16215. });
  16216. svr.wait_until_ready();
  16217. const std::vector<std::pair<std::string, std::string>> cases = {
  16218. {"next", "/dir/next"},
  16219. {"./next?x=1", "/dir/next?x=1"},
  16220. {"../other", "/other"},
  16221. };
  16222. for (const auto &c : cases) {
  16223. Client cli(HOST, PORT);
  16224. cli.set_follow_location(true);
  16225. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16226. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16227. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16228. EXPECT_EQ(c.second, res->body) << c.first;
  16229. }
  16230. }
  16231. #ifdef CPPHTTPLIB_SSL_ENABLED
  16232. TEST(RedirectTest, Issue2185_Online) {
  16233. SSLClient client("github.com");
  16234. client.set_follow_location(true);
  16235. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16236. "Coollab-Windows.zip");
  16237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16238. EXPECT_EQ(StatusCode::OK_200, res->status);
  16239. EXPECT_EQ(9920427U, res->body.size());
  16240. }
  16241. #endif
  16242. TEST(VulnerabilityTest, CRLFInjection) {
  16243. Server svr;
  16244. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16245. res.set_content("Hello 1", "text/plain");
  16246. });
  16247. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16248. res.set_content("Hello 2", "text/plain");
  16249. });
  16250. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16251. res.set_content("Hello 3", "text/plain");
  16252. });
  16253. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16254. res.set_content("Hello 4", "text/plain");
  16255. });
  16256. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16257. for (const auto &x : req.headers) {
  16258. auto key = x.first;
  16259. EXPECT_STRNE("evil", key.c_str());
  16260. }
  16261. });
  16262. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16263. auto se = detail::scope_exit([&] {
  16264. svr.stop();
  16265. thread.join();
  16266. ASSERT_FALSE(svr.is_running());
  16267. });
  16268. svr.wait_until_ready();
  16269. {
  16270. Client cli(HOST, PORT);
  16271. cli.Post("/test1", "A=B",
  16272. "application/x-www-form-urlencoded\r\nevil: hello1");
  16273. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16274. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16275. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16276. }
  16277. }
  16278. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16279. auto server_thread = std::thread([] {
  16280. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16281. default_socket_options(srv);
  16282. sockaddr_in addr{};
  16283. addr.sin_family = AF_INET;
  16284. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16285. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16286. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16287. ::listen(srv, 1);
  16288. sockaddr_in cli_addr{};
  16289. socklen_t cli_len = sizeof(cli_addr);
  16290. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16291. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16292. std::string buf_all;
  16293. char buf[2048];
  16294. ssize_t n;
  16295. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16296. buf_all.append(buf, static_cast<size_t>(n));
  16297. size_t pos;
  16298. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16299. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16300. auto e = request_block.find("\r\n");
  16301. if (e != std::string::npos) {
  16302. auto request_line = request_block.substr(0, e);
  16303. std::string msg =
  16304. "CRLF injection detected in request line: '" + request_line + "'";
  16305. EXPECT_FALSE(true) << msg;
  16306. }
  16307. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16308. ::send(cli,
  16309. #ifdef _WIN32
  16310. static_cast<const char *>(resp.c_str()),
  16311. static_cast<int>(resp.size()),
  16312. #else
  16313. resp.c_str(), resp.size(),
  16314. #endif
  16315. 0);
  16316. buf_all.erase(0, pos + 4);
  16317. }
  16318. }
  16319. detail::close_socket(cli);
  16320. detail::close_socket(srv);
  16321. });
  16322. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16323. auto cli = Client("127.0.0.1", PORT + 1);
  16324. auto headers = Headers{
  16325. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16326. {"Connection", "keep-alive"}};
  16327. auto res = cli.Get("/hi", headers);
  16328. EXPECT_FALSE(res);
  16329. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16330. server_thread.join();
  16331. }
  16332. // A request rejected before any byte reaches the socket must fail right away
  16333. // instead of waiting for a response the server will never send.
  16334. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16335. // The kernel completes the TCP handshake from the listen backlog, so the
  16336. // client connects, but nothing ever reads, responds or closes.
  16337. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16338. default_socket_options(srv);
  16339. sockaddr_in addr{};
  16340. addr.sin_family = AF_INET;
  16341. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16342. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16343. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16344. ASSERT_EQ(0, ::listen(srv, 8));
  16345. auto cli = Client("127.0.0.1", PORT + 1);
  16346. cli.set_read_timeout(10, 0);
  16347. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16348. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16349. std::chrono::steady_clock::now() - start)
  16350. .count();
  16351. };
  16352. {
  16353. Request req;
  16354. req.method = "GE T";
  16355. req.path = "/";
  16356. auto start = std::chrono::steady_clock::now();
  16357. auto res = cli.send(req);
  16358. EXPECT_FALSE(res);
  16359. EXPECT_EQ(Error::Write, res.error());
  16360. EXPECT_LT(elapsed_ms(start), 1000);
  16361. }
  16362. {
  16363. auto start = std::chrono::steady_clock::now();
  16364. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16365. EXPECT_FALSE(res);
  16366. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16367. EXPECT_LT(elapsed_ms(start), 1000);
  16368. }
  16369. EXPECT_FALSE(cli.is_socket_open());
  16370. detail::close_socket(srv);
  16371. }
  16372. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16373. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16374. default_socket_options(srv);
  16375. sockaddr_in addr{};
  16376. addr.sin_family = AF_INET;
  16377. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16378. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16379. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16380. ASSERT_EQ(0, ::listen(srv, 1));
  16381. std::string received;
  16382. auto server_thread = std::thread([&] {
  16383. auto sock = ::accept(srv, nullptr, nullptr);
  16384. if (sock == INVALID_SOCKET) { return; }
  16385. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16386. char buf[2048];
  16387. ssize_t n;
  16388. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16389. received.append(buf, static_cast<size_t>(n));
  16390. }
  16391. detail::close_socket(sock);
  16392. });
  16393. {
  16394. auto cli = Client("127.0.0.1", PORT + 1);
  16395. // "Z" sorts after the default headers, so writing straight to the socket
  16396. // would have sent the request line and those headers before the rejection.
  16397. auto handle =
  16398. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16399. EXPECT_FALSE(handle.is_valid());
  16400. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16401. }
  16402. server_thread.join();
  16403. detail::close_socket(srv);
  16404. EXPECT_TRUE(received.empty()) << received;
  16405. }
  16406. TEST(PathParamsTest, StaticMatch) {
  16407. const auto pattern = "/users/all";
  16408. detail::PathParamsMatcher matcher(pattern);
  16409. Request request;
  16410. request.path = "/users/all";
  16411. ASSERT_TRUE(matcher.match(request));
  16412. std::unordered_map<std::string, std::string> expected_params = {};
  16413. EXPECT_EQ(request.path_params, expected_params);
  16414. }
  16415. TEST(PathParamsTest, StaticMismatch) {
  16416. const auto pattern = "/users/all";
  16417. detail::PathParamsMatcher matcher(pattern);
  16418. Request request;
  16419. request.path = "/users/1";
  16420. ASSERT_FALSE(matcher.match(request));
  16421. }
  16422. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16423. const auto pattern = "/users/:id/subscriptions";
  16424. detail::PathParamsMatcher matcher(pattern);
  16425. Request request;
  16426. request.path = "/users/42/subscriptions";
  16427. ASSERT_TRUE(matcher.match(request));
  16428. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16429. EXPECT_EQ(request.path_params, expected_params);
  16430. }
  16431. TEST(PathParamsTest, SingleParamInTheEnd) {
  16432. const auto pattern = "/users/:id";
  16433. detail::PathParamsMatcher matcher(pattern);
  16434. Request request;
  16435. request.path = "/users/24";
  16436. ASSERT_TRUE(matcher.match(request));
  16437. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16438. EXPECT_EQ(request.path_params, expected_params);
  16439. }
  16440. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16441. const auto pattern = "/users/:id/";
  16442. detail::PathParamsMatcher matcher(pattern);
  16443. Request request;
  16444. request.path = "/users/42/";
  16445. ASSERT_TRUE(matcher.match(request));
  16446. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16447. EXPECT_EQ(request.path_params, expected_params);
  16448. }
  16449. TEST(PathParamsTest, EmptyParam) {
  16450. const auto pattern = "/users/:id/";
  16451. detail::PathParamsMatcher matcher(pattern);
  16452. Request request;
  16453. request.path = "/users//";
  16454. ASSERT_TRUE(matcher.match(request));
  16455. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16456. EXPECT_EQ(request.path_params, expected_params);
  16457. }
  16458. TEST(PathParamsTest, FragmentMismatch) {
  16459. const auto pattern = "/users/:id/";
  16460. detail::PathParamsMatcher matcher(pattern);
  16461. Request request;
  16462. request.path = "/admins/24/";
  16463. ASSERT_FALSE(matcher.match(request));
  16464. }
  16465. TEST(PathParamsTest, ExtraFragments) {
  16466. const auto pattern = "/users/:id";
  16467. detail::PathParamsMatcher matcher(pattern);
  16468. Request request;
  16469. request.path = "/users/42/subscriptions";
  16470. ASSERT_FALSE(matcher.match(request));
  16471. }
  16472. TEST(PathParamsTest, MissingTrailingParam) {
  16473. const auto pattern = "/users/:id";
  16474. detail::PathParamsMatcher matcher(pattern);
  16475. Request request;
  16476. request.path = "/users";
  16477. ASSERT_FALSE(matcher.match(request));
  16478. }
  16479. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16480. const auto pattern = "/users/:id/subscriptions";
  16481. detail::PathParamsMatcher matcher(pattern);
  16482. Request request;
  16483. request.path = "/users/subscriptions";
  16484. ASSERT_FALSE(matcher.match(request));
  16485. }
  16486. TEST(PathParamsTest, MultipleParams) {
  16487. const auto pattern = "/users/:userid/subscriptions/:subid";
  16488. detail::PathParamsMatcher matcher(pattern);
  16489. Request request;
  16490. request.path = "/users/42/subscriptions/2";
  16491. ASSERT_TRUE(matcher.match(request));
  16492. std::unordered_map<std::string, std::string> expected_params = {
  16493. {"userid", "42"}, {"subid", "2"}};
  16494. EXPECT_EQ(request.path_params, expected_params);
  16495. }
  16496. TEST(PathParamsTest, SequenceOfParams) {
  16497. const auto pattern = "/values/:x/:y/:z";
  16498. detail::PathParamsMatcher matcher(pattern);
  16499. Request request;
  16500. request.path = "/values/1/2/3";
  16501. ASSERT_TRUE(matcher.match(request));
  16502. std::unordered_map<std::string, std::string> expected_params = {
  16503. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16504. EXPECT_EQ(request.path_params, expected_params);
  16505. }
  16506. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16507. const auto pattern = "/prefix:suffix";
  16508. detail::PathParamsMatcher matcher(pattern);
  16509. Request request;
  16510. request.path = "/prefix:suffix";
  16511. ASSERT_TRUE(matcher.match(request));
  16512. const std::unordered_map<std::string, std::string> expected_params = {};
  16513. EXPECT_EQ(request.path_params, expected_params);
  16514. }
  16515. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16516. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16517. // calling thread's stack on a long enough path for a quantified pattern;
  16518. // RegexMatcher must refuse to run regex matching on paths beyond
  16519. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16520. detail::RegexMatcher matcher("/files/(.*)");
  16521. Request within_limit;
  16522. within_limit.path = "/files/" + std::string(10, 'A');
  16523. EXPECT_TRUE(matcher.match(within_limit));
  16524. Request over_limit;
  16525. over_limit.path =
  16526. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16527. EXPECT_FALSE(matcher.match(over_limit));
  16528. }
  16529. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16530. Server svr;
  16531. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16532. res.set_content("ok", "text/plain");
  16533. });
  16534. auto port = svr.bind_to_any_port(HOST);
  16535. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16536. auto se = detail::scope_exit([&] {
  16537. svr.stop();
  16538. thread.join();
  16539. ASSERT_FALSE(svr.is_running());
  16540. });
  16541. svr.wait_until_ready();
  16542. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16543. // request URI limit; this used to be able to crash the process.
  16544. std::string path =
  16545. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16546. std::string req = "GET " + path +
  16547. " HTTP/1.1\r\n"
  16548. "Host: " +
  16549. std::string(HOST) + ":" + std::to_string(port) +
  16550. "\r\n"
  16551. "Connection: close\r\n"
  16552. "\r\n";
  16553. std::string response;
  16554. ASSERT_TRUE(send_request(5, req, &response, port));
  16555. EXPECT_NE(std::string::npos, response.find("404"));
  16556. }
  16557. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16558. Server svr;
  16559. auto handler = [](const Request & /*req*/, Response &res) {
  16560. res.set_content("hit", "text/plain");
  16561. };
  16562. // No regex metacharacter, so this one is compared literally
  16563. svr.Get("/literal/route", handler);
  16564. // '.' is a regex metacharacter, so this one must keep regex semantics
  16565. svr.Get("/a.c", handler);
  16566. auto port = svr.bind_to_any_port(HOST);
  16567. std::thread t([&]() { svr.listen_after_bind(); });
  16568. auto se = detail::scope_exit([&] {
  16569. svr.stop();
  16570. t.join();
  16571. ASSERT_FALSE(svr.is_running());
  16572. });
  16573. svr.wait_until_ready();
  16574. Client cli(HOST, port);
  16575. struct {
  16576. const char *path;
  16577. int status;
  16578. } cases[] = {
  16579. {"/literal/route", StatusCode::OK_200},
  16580. {"/literal/routes", StatusCode::NotFound_404},
  16581. {"/literal/rout", StatusCode::NotFound_404},
  16582. {"/abc", StatusCode::OK_200},
  16583. {"/a.c", StatusCode::OK_200},
  16584. };
  16585. for (const auto &x : cases) {
  16586. auto res = cli.Get(x.path);
  16587. ASSERT_TRUE(res) << x.path;
  16588. EXPECT_EQ(x.status, res->status) << x.path;
  16589. }
  16590. }
  16591. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16592. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16593. // from exhausting the stack, so it must only constrain routes that actually
  16594. // run a regular expression. A literal route is matched by comparison and
  16595. // stays usable at any length.
  16596. Server svr;
  16597. const std::string pattern =
  16598. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16599. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16600. res.set_content("hit", "text/plain");
  16601. });
  16602. auto port = svr.bind_to_any_port(HOST);
  16603. std::thread t([&]() { svr.listen_after_bind(); });
  16604. auto se = detail::scope_exit([&] {
  16605. svr.stop();
  16606. t.join();
  16607. ASSERT_FALSE(svr.is_running());
  16608. });
  16609. svr.wait_until_ready();
  16610. Client cli(HOST, port);
  16611. auto res = cli.Get(pattern);
  16612. ASSERT_TRUE(res);
  16613. EXPECT_EQ(StatusCode::OK_200, res->status);
  16614. }
  16615. TEST(ParseUrlTest, VariousPatterns) {
  16616. {
  16617. detail::UrlComponents uc;
  16618. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16619. EXPECT_EQ("http", uc.scheme);
  16620. EXPECT_EQ("example.com", uc.host);
  16621. EXPECT_EQ("8080", uc.port);
  16622. EXPECT_EQ("/path", uc.path);
  16623. EXPECT_EQ("?q=1", uc.query);
  16624. }
  16625. {
  16626. detail::UrlComponents uc;
  16627. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16628. EXPECT_EQ("https", uc.scheme);
  16629. EXPECT_EQ("example.com", uc.host);
  16630. EXPECT_TRUE(uc.port.empty());
  16631. EXPECT_EQ("/path", uc.path);
  16632. }
  16633. {
  16634. detail::UrlComponents uc;
  16635. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16636. EXPECT_EQ("::1", uc.host);
  16637. EXPECT_EQ("8080", uc.port);
  16638. EXPECT_EQ("/path", uc.path);
  16639. }
  16640. {
  16641. detail::UrlComponents uc;
  16642. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16643. }
  16644. {
  16645. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16646. // the path while the connection still targets the bracketed host.
  16647. detail::UrlComponents uc;
  16648. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16649. }
  16650. {
  16651. detail::UrlComponents uc;
  16652. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16653. }
  16654. {
  16655. detail::UrlComponents uc;
  16656. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16657. EXPECT_EQ("::1", uc.host);
  16658. EXPECT_TRUE(uc.port.empty());
  16659. EXPECT_EQ("/path", uc.path);
  16660. }
  16661. {
  16662. detail::UrlComponents uc;
  16663. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16664. EXPECT_TRUE(uc.scheme.empty());
  16665. EXPECT_EQ("example.com", uc.host);
  16666. EXPECT_EQ("/path", uc.path);
  16667. EXPECT_EQ("?q=1", uc.query);
  16668. }
  16669. {
  16670. detail::UrlComponents uc;
  16671. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16672. EXPECT_TRUE(uc.host.empty());
  16673. EXPECT_EQ("/path", uc.path);
  16674. EXPECT_EQ("?q=1", uc.query);
  16675. }
  16676. {
  16677. detail::UrlComponents uc;
  16678. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16679. EXPECT_EQ("example.com", uc.host);
  16680. EXPECT_EQ("8080", uc.port);
  16681. }
  16682. {
  16683. // Unix socket path — must not be parsed as host
  16684. detail::UrlComponents uc;
  16685. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16686. EXPECT_TRUE(uc.host.empty());
  16687. }
  16688. {
  16689. detail::UrlComponents uc;
  16690. ASSERT_TRUE(detail::parse_url("", uc));
  16691. EXPECT_TRUE(uc.host.empty());
  16692. EXPECT_TRUE(uc.path.empty());
  16693. }
  16694. {
  16695. detail::UrlComponents uc;
  16696. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16697. }
  16698. {
  16699. detail::UrlComponents uc;
  16700. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16701. }
  16702. {
  16703. // Accepted by parse_url; callers restrict to http/https
  16704. detail::UrlComponents uc;
  16705. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16706. EXPECT_EQ("ftp", uc.scheme);
  16707. }
  16708. {
  16709. detail::UrlComponents uc;
  16710. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16711. }
  16712. {
  16713. detail::UrlComponents uc;
  16714. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16715. }
  16716. }
  16717. TEST(ParseUrlTest, FragmentHandling) {
  16718. {
  16719. detail::UrlComponents uc;
  16720. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16721. EXPECT_EQ("/path", uc.path);
  16722. EXPECT_TRUE(uc.query.empty());
  16723. }
  16724. {
  16725. detail::UrlComponents uc;
  16726. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16727. EXPECT_TRUE(uc.path.empty());
  16728. EXPECT_TRUE(uc.query.empty());
  16729. }
  16730. }
  16731. TEST(ParseUrlTest, UserinfoHandling) {
  16732. // userinfo, and a backslash some parsers take for '/', are rejected: such
  16733. // parsers would see evil.com as the host.
  16734. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16735. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16736. for (auto url : urls) {
  16737. detail::UrlComponents uc;
  16738. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16739. }
  16740. }
  16741. TEST(ParseUrlTest, IPv6EdgeCases) {
  16742. {
  16743. detail::UrlComponents uc;
  16744. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16745. EXPECT_TRUE(uc.scheme.empty());
  16746. EXPECT_EQ("::1", uc.host);
  16747. EXPECT_EQ("8080", uc.port);
  16748. }
  16749. {
  16750. // Zone ID '%25' is not in [a-fA-F0-9:]
  16751. detail::UrlComponents uc;
  16752. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16753. }
  16754. }
  16755. TEST(ParseUrlTest, SchemeEdgeCases) {
  16756. {
  16757. detail::UrlComponents uc;
  16758. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16759. }
  16760. {
  16761. detail::UrlComponents uc;
  16762. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16763. }
  16764. {
  16765. detail::UrlComponents uc;
  16766. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16767. }
  16768. }
  16769. TEST(ParseUrlTest, PortEdgeCases) {
  16770. {
  16771. detail::UrlComponents uc;
  16772. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16773. EXPECT_TRUE(uc.port.empty());
  16774. EXPECT_EQ("/path", uc.path);
  16775. }
  16776. {
  16777. // parse_url accepts any port string; validation is done by parse_port
  16778. detail::UrlComponents uc;
  16779. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16780. EXPECT_EQ("abc", uc.port);
  16781. }
  16782. }
  16783. TEST(ParseUrlTest, WebSocketPatterns) {
  16784. {
  16785. detail::UrlComponents uc;
  16786. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16787. EXPECT_EQ("ws", uc.scheme);
  16788. EXPECT_EQ("echo.example.com", uc.host);
  16789. EXPECT_EQ("8080", uc.port);
  16790. EXPECT_EQ("/ws", uc.path);
  16791. }
  16792. {
  16793. detail::UrlComponents uc;
  16794. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16795. EXPECT_EQ("wss", uc.scheme);
  16796. EXPECT_EQ("echo.example.com", uc.host);
  16797. EXPECT_TRUE(uc.port.empty());
  16798. EXPECT_EQ("/ws", uc.path);
  16799. }
  16800. }
  16801. TEST(ParseUrlTest, QueryOnly) {
  16802. detail::UrlComponents uc;
  16803. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16804. EXPECT_TRUE(uc.host.empty());
  16805. EXPECT_TRUE(uc.path.empty());
  16806. EXPECT_EQ("?q=1&r=2", uc.query);
  16807. }
  16808. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16809. detail::UrlComponents uc;
  16810. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16811. EXPECT_TRUE(uc.scheme.empty());
  16812. EXPECT_EQ("example.com", uc.host);
  16813. EXPECT_EQ("443", uc.port);
  16814. EXPECT_EQ("/path", uc.path);
  16815. }
  16816. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16817. // If ipv6 regex working, regex match codepath is taken.
  16818. // else port will default to 80 in Client impl
  16819. int clientImplMagicPort = 80;
  16820. int port = 4321;
  16821. // above ports must be different to avoid false negative
  16822. EXPECT_NE(clientImplMagicPort, port);
  16823. std::string ipV6TestURL = "http://[ff06::c3]";
  16824. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16825. CLIENT_PRIVATE_KEY_FILE);
  16826. EXPECT_EQ(cli.port(), port);
  16827. }
  16828. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16829. auto file_path = "./www/dir/index.html";
  16830. auto dir_path = "./www/dir";
  16831. detail::FileStat stat_file(file_path);
  16832. EXPECT_TRUE(stat_file.is_file());
  16833. EXPECT_FALSE(stat_file.is_dir());
  16834. detail::FileStat stat_dir(dir_path);
  16835. EXPECT_FALSE(stat_dir.is_file());
  16836. EXPECT_TRUE(stat_dir.is_dir());
  16837. }
  16838. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16839. // IPv4 with default HTTP port (80)
  16840. EXPECT_EQ("example.com",
  16841. detail::make_host_and_port_string("example.com", 80, false));
  16842. // IPv4 with default HTTPS port (443)
  16843. EXPECT_EQ("example.com",
  16844. detail::make_host_and_port_string("example.com", 443, true));
  16845. // IPv4 with non-default HTTP port
  16846. EXPECT_EQ("example.com:8080",
  16847. detail::make_host_and_port_string("example.com", 8080, false));
  16848. // IPv4 with non-default HTTPS port
  16849. EXPECT_EQ("example.com:8443",
  16850. detail::make_host_and_port_string("example.com", 8443, true));
  16851. // IPv6 with default HTTP port (80)
  16852. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16853. // IPv6 with default HTTPS port (443)
  16854. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16855. // IPv6 with non-default HTTP port
  16856. EXPECT_EQ("[::1]:8080",
  16857. detail::make_host_and_port_string("::1", 8080, false));
  16858. // IPv6 with non-default HTTPS port
  16859. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16860. // IPv6 full address with default port
  16861. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16862. detail::make_host_and_port_string(
  16863. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16864. // IPv6 full address with non-default port
  16865. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16866. detail::make_host_and_port_string(
  16867. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16868. // IPv6 localhost with non-default port
  16869. EXPECT_EQ("[::1]:3000",
  16870. detail::make_host_and_port_string("::1", 3000, false));
  16871. // IPv6 with zone ID (link-local address) with default port
  16872. EXPECT_EQ("[fe80::1%eth0]",
  16873. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16874. // IPv6 with zone ID (link-local address) with non-default port
  16875. EXPECT_EQ("[fe80::1%eth0]:8080",
  16876. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16877. // Edge case: Port 443 with is_ssl=false (should add port)
  16878. EXPECT_EQ("example.com:443",
  16879. detail::make_host_and_port_string("example.com", 443, false));
  16880. // Edge case: Port 80 with is_ssl=true (should add port)
  16881. EXPECT_EQ("example.com:80",
  16882. detail::make_host_and_port_string("example.com", 80, true));
  16883. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16884. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16885. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16886. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16887. // Security fix: Already bracketed IPv6 should not get double brackets
  16888. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16889. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16890. EXPECT_EQ("[::1]:8080",
  16891. detail::make_host_and_port_string("[::1]", 8080, false));
  16892. EXPECT_EQ("[2001:db8::1]:8080",
  16893. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16894. EXPECT_EQ("[fe80::1%eth0]",
  16895. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16896. EXPECT_EQ("[fe80::1%eth0]:8080",
  16897. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16898. // Edge case: Empty host (should return as-is)
  16899. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16900. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16901. // This is a known limitation but shouldn't crash
  16902. EXPECT_EQ("[host:name]",
  16903. detail::make_host_and_port_string("host:name", 80, false));
  16904. // Port number edge cases (no validation, but should not crash)
  16905. EXPECT_EQ("example.com:0",
  16906. detail::make_host_and_port_string("example.com", 0, false));
  16907. EXPECT_EQ("example.com:-1",
  16908. detail::make_host_and_port_string("example.com", -1, false));
  16909. EXPECT_EQ("example.com:65535",
  16910. detail::make_host_and_port_string("example.com", 65535, false));
  16911. EXPECT_EQ("example.com:65536",
  16912. detail::make_host_and_port_string("example.com", 65536, false));
  16913. }
  16914. #ifdef CPPHTTPLIB_SSL_ENABLED
  16915. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16916. httplib::SSLClient cli("roblox.com", 443);
  16917. cli.set_follow_location(true);
  16918. auto res = cli.Get("/");
  16919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16920. EXPECT_EQ(StatusCode::OK_200, res->status);
  16921. }
  16922. #endif
  16923. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16924. Server svr;
  16925. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16926. EXPECT_EQ(res.status, 400);
  16927. });
  16928. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16929. auto se = detail::scope_exit([&] {
  16930. svr.stop();
  16931. thread.join();
  16932. ASSERT_FALSE(svr.is_running());
  16933. });
  16934. svr.wait_until_ready();
  16935. Client cli(HOST, PORT);
  16936. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16937. }
  16938. TEST(InvalidHeaderCharsTest, is_field_name) {
  16939. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16940. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16941. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16942. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16943. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16944. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16945. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16946. EXPECT_FALSE(detail::fields::is_field_name(""));
  16947. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16948. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16949. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16950. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16951. }
  16952. TEST(InvalidHeaderCharsTest, is_field_value) {
  16953. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16954. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16955. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16956. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16957. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16958. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16959. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16960. EXPECT_TRUE(detail::fields::is_field_value(""));
  16961. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16962. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16963. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16964. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16965. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16966. }
  16967. TEST(InvalidHeaderCharsTest, OnServer) {
  16968. Server svr;
  16969. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16970. std::string header = "Not Set";
  16971. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16972. res.set_header(header, "value");
  16973. res.set_content("Page Content Page Content", "text/plain");
  16974. });
  16975. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16976. std::string header = "Not Set";
  16977. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16978. res.set_header("X-Test", header);
  16979. res.set_content("Page Content Page Content", "text/plain");
  16980. });
  16981. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16982. auto se = detail::scope_exit([&] {
  16983. svr.stop();
  16984. thread.join();
  16985. ASSERT_FALSE(svr.is_running());
  16986. });
  16987. svr.wait_until_ready();
  16988. Client cli(HOST, PORT);
  16989. {
  16990. auto res = cli.Get(
  16991. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16993. EXPECT_EQ("Page Content Page Content", res->body);
  16994. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16995. }
  16996. {
  16997. auto res = cli.Get(
  16998. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17000. EXPECT_EQ("Page Content Page Content", res->body);
  17001. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17002. }
  17003. }
  17004. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17005. auto handled = false;
  17006. Server svr;
  17007. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17008. thread t = thread([&] { svr.listen(HOST, PORT); });
  17009. auto se = detail::scope_exit([&] {
  17010. svr.stop();
  17011. t.join();
  17012. ASSERT_FALSE(svr.is_running());
  17013. ASSERT_FALSE(handled);
  17014. });
  17015. svr.wait_until_ready();
  17016. auto req = "POST /test HTTP/1.1\r\n"
  17017. "Content-Length: x\r\n"
  17018. "\r\n";
  17019. std::string response;
  17020. ASSERT_TRUE(send_request(1, req, &response));
  17021. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17022. response.substr(0, response.find("\r\n")));
  17023. }
  17024. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17025. // case-insensitive, and a server that receives a 100-continue expectation in
  17026. // an HTTP/1.0 request MUST ignore it.
  17027. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17028. std::string response;
  17029. ASSERT_TRUE(send_request(1, req, &response, port));
  17030. *got_100 = response.find("100 Continue") != std::string::npos;
  17031. }
  17032. class ExpectTokenTest : public ::testing::Test {
  17033. protected:
  17034. void SetUp() override {
  17035. svr_.Post("/p", [](const Request &, Response &res) {
  17036. res.set_content("ok", "text/plain");
  17037. });
  17038. port_ = svr_.bind_to_any_port(HOST);
  17039. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17040. svr_.wait_until_ready();
  17041. }
  17042. void TearDown() override {
  17043. svr_.stop();
  17044. if (thread_.joinable()) { thread_.join(); }
  17045. }
  17046. std::string request(const char *version, const char *expect_value) const {
  17047. return std::string("POST /p ") + version +
  17048. "\r\n"
  17049. "Host: localhost\r\n"
  17050. "Content-Length: 2\r\n"
  17051. "Connection: close\r\n"
  17052. "Expect: " +
  17053. expect_value +
  17054. "\r\n"
  17055. "\r\n"
  17056. "hi";
  17057. }
  17058. Server svr_;
  17059. int port_ = 0;
  17060. thread thread_;
  17061. };
  17062. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17063. bool got_100 = false;
  17064. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17065. EXPECT_TRUE(got_100);
  17066. }
  17067. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17068. bool got_100 = true;
  17069. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17070. EXPECT_FALSE(got_100);
  17071. }
  17072. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17073. bool got_100 = false;
  17074. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17075. EXPECT_TRUE(got_100);
  17076. }
  17077. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17078. bool got_100 = false;
  17079. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17080. EXPECT_TRUE(got_100);
  17081. }
  17082. // `100 Continue` is sent only when the server starts reading the body, so a
  17083. // request rejected before that never invites the client to send it. The
  17084. // requests below carry the expectation but withhold the body, as a client
  17085. // waiting for `100 Continue` would.
  17086. // A POST that expects `100 Continue` and withholds its two-byte body.
  17087. static std::string expect_headers_only(const std::string &path) {
  17088. return "POST " + path +
  17089. " HTTP/1.1\r\n"
  17090. "Host: localhost\r\n"
  17091. "Content-Length: 2\r\n"
  17092. "Expect: 100-continue\r\n"
  17093. "\r\n";
  17094. }
  17095. class ExpectLazyContinueTest : public ::testing::Test {
  17096. protected:
  17097. void SetUp() override {
  17098. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17099. if (req.path == "/pre-routing") {
  17100. res.status = StatusCode::Unauthorized_401;
  17101. return Server::HandlerResponse::Handled;
  17102. }
  17103. return Server::HandlerResponse::Unhandled;
  17104. });
  17105. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17106. if (req.matched_route == "/pre-request") {
  17107. res.status = StatusCode::Forbidden_403;
  17108. return Server::HandlerResponse::Handled;
  17109. }
  17110. return Server::HandlerResponse::Unhandled;
  17111. });
  17112. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17113. res.set_content("ok", "text/plain");
  17114. });
  17115. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17116. res.set_content("ok", "text/plain");
  17117. });
  17118. svr_.Post("/reader-used", [](const Request &, Response &res,
  17119. const ContentReader &content_reader) {
  17120. std::string body;
  17121. content_reader([&](const char *data, size_t len) {
  17122. body.append(data, len);
  17123. return true;
  17124. });
  17125. res.set_content(body, "text/plain");
  17126. });
  17127. svr_.Post("/reader-unused",
  17128. [](const Request &, Response &res, const ContentReader &) {
  17129. res.set_content("ignored", "text/plain");
  17130. });
  17131. port_ = svr_.bind_to_any_port(HOST);
  17132. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17133. svr_.wait_until_ready();
  17134. }
  17135. void TearDown() override {
  17136. svr_.stop();
  17137. if (thread_.joinable()) { thread_.join(); }
  17138. }
  17139. // Sends `req` and reads until the server closes the connection. Returns
  17140. // false if the read had to wait for the client-side timeout instead.
  17141. bool send_until_closed(const std::string &req, std::string *resp) const {
  17142. auto start = std::chrono::steady_clock::now();
  17143. if (!send_request(3, req, resp, port_)) { return false; }
  17144. auto elapsed = std::chrono::steady_clock::now() - start;
  17145. return elapsed < std::chrono::seconds(2);
  17146. }
  17147. // The final response comes without `100 Continue`, and the server closes
  17148. // the connection since the body may or may not follow.
  17149. void expect_final_without_interim(const std::string &path,
  17150. const char *status_line) const {
  17151. std::string resp;
  17152. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17153. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17154. EXPECT_EQ(0u, resp.find(status_line));
  17155. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17156. }
  17157. Server svr_;
  17158. int port_ = 0;
  17159. thread thread_;
  17160. };
  17161. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17162. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17163. }
  17164. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17165. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17166. }
  17167. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17168. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17169. }
  17170. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17171. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17172. }
  17173. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17174. // The body follows once `100 Continue` has had time to arrive.
  17175. auto req = expect_headers_only("/reader-used");
  17176. req.insert(req.size() - 2, "Connection: close\r\n");
  17177. std::string resp;
  17178. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17179. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17180. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17181. EXPECT_NE(std::string::npos, resp.find("hi"));
  17182. }
  17183. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17184. // Large enough for the client to add `Expect: 100-continue` itself.
  17185. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17186. std::atomic<bool> body_sent{false};
  17187. Client cli(HOST, port_);
  17188. auto res = cli.Post(
  17189. "/pre-request", length,
  17190. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17191. body_sent = true;
  17192. std::string chunk(len, 'x');
  17193. sink.write(chunk.data(), chunk.size());
  17194. return true;
  17195. },
  17196. "application/octet-stream");
  17197. ASSERT_TRUE(res);
  17198. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17199. EXPECT_FALSE(body_sent);
  17200. }
  17201. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17202. Server svr;
  17203. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17204. return StatusCode::ExpectationFailed_417;
  17205. });
  17206. svr.Post("/p", [](const Request &, Response &res) {
  17207. res.set_content("ok", "text/plain");
  17208. });
  17209. auto port = svr.bind_to_any_port(HOST);
  17210. thread t = thread([&] { svr.listen_after_bind(); });
  17211. auto se = detail::scope_exit([&] {
  17212. svr.stop();
  17213. t.join();
  17214. });
  17215. svr.wait_until_ready();
  17216. std::string resp;
  17217. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17218. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17219. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17220. // Exactly one response: the route handler must not run after the 417.
  17221. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17222. }
  17223. #ifndef _WIN32
  17224. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17225. static constexpr char reject[] = "Unauthorized";
  17226. static constexpr char accept[] = "Upload accepted";
  17227. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17228. Server svr;
  17229. svr.set_expect_100_continue_handler(
  17230. [](const Request & /*req*/, Response &res) {
  17231. res.status = StatusCode::Unauthorized_401;
  17232. res.set_content(reject, "text/plain");
  17233. return res.status;
  17234. });
  17235. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17236. res.set_content(accept, "text/plain");
  17237. });
  17238. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17239. auto se = detail::scope_exit([&] {
  17240. svr.stop();
  17241. thread.join();
  17242. ASSERT_FALSE(svr.is_running());
  17243. });
  17244. svr.wait_until_ready();
  17245. {
  17246. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17247. curl_easy_init(), &curl_easy_cleanup};
  17248. ASSERT_NE(curl, nullptr);
  17249. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17250. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17251. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17252. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17253. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17254. &curl_slist_free_all};
  17255. ASSERT_NE(list, nullptr);
  17256. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17257. struct read_data {
  17258. size_t read_size;
  17259. size_t total_size;
  17260. } data = {0, total_size};
  17261. using read_callback_t =
  17262. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17263. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17264. void *userdata) -> size_t {
  17265. read_data *d = (read_data *)userdata;
  17266. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17267. std::fill_n(ptr, size * nmemb, 'A');
  17268. d->read_size += size * nmemb;
  17269. return size * nmemb;
  17270. };
  17271. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17272. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17273. std::vector<char> buffer;
  17274. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17275. using write_callback_t =
  17276. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17277. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17278. void *userdata) -> size_t {
  17279. std::vector<char> *buf = (std::vector<char> *)userdata;
  17280. buf->reserve(buf->size() + size * nmemb + 1);
  17281. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17282. return size * nmemb;
  17283. };
  17284. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17285. {
  17286. const auto res = curl_easy_perform(curl.get());
  17287. ASSERT_EQ(res, CURLE_OK);
  17288. }
  17289. {
  17290. auto response_code = long{};
  17291. const auto res =
  17292. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17293. ASSERT_EQ(res, CURLE_OK);
  17294. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17295. }
  17296. {
  17297. auto dl = curl_off_t{};
  17298. const auto res =
  17299. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17300. ASSERT_EQ(res, CURLE_OK);
  17301. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17302. }
  17303. {
  17304. buffer.push_back('\0');
  17305. ASSERT_STRCASEEQ(buffer.data(), reject);
  17306. }
  17307. }
  17308. }
  17309. #endif
  17310. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17311. // Regression test for #2458.
  17312. //
  17313. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17314. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17315. // ticket can make the client socket spuriously readable during the
  17316. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17317. // the client withholds the body and then blocks reading a response that never
  17318. // comes, failing with `Failed to read connection`.
  17319. //
  17320. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17321. // within the timeout. This raw OpenSSL server deliberately never sends
  17322. // `100 Continue`; the client must still deliver the body and receive 200.
  17323. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17324. signal(SIGPIPE, SIG_IGN);
  17325. const auto port = PORT + 4;
  17326. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17327. ASSERT_NE(srv, INVALID_SOCKET);
  17328. int opt = 1;
  17329. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17330. sockaddr_in addr{};
  17331. addr.sin_family = AF_INET;
  17332. addr.sin_port = htons(static_cast<uint16_t>(port));
  17333. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17334. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17335. ASSERT_EQ(0, ::listen(srv, 1));
  17336. std::atomic<size_t> server_body_bytes{0};
  17337. auto server_thread = std::thread([&] {
  17338. sockaddr_in cli_addr{};
  17339. socklen_t cli_len = sizeof(cli_addr);
  17340. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17341. if (cli == INVALID_SOCKET) { return; }
  17342. // Bound the lifetime of the server side so a buggy client (which never
  17343. // sends the body) cannot make this thread block forever on join.
  17344. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17345. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17346. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17347. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17348. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17349. SSL *ssl = SSL_new(ctx);
  17350. SSL_set_fd(ssl, static_cast<int>(cli));
  17351. if (SSL_accept(ssl) > 0) {
  17352. // Read the request headers. Reading here also flushes the TLS 1.3
  17353. // session tickets to the client. Deliberately do NOT send
  17354. // `100 Continue`.
  17355. std::string buf;
  17356. char tmp[1024];
  17357. while (buf.find("\r\n\r\n") == std::string::npos) {
  17358. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17359. if (n <= 0) { break; }
  17360. buf.append(tmp, static_cast<size_t>(n));
  17361. }
  17362. // A correct client sends the body now; count what arrives.
  17363. auto pos = buf.find("\r\n\r\n");
  17364. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17365. while (body < 4096) {
  17366. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17367. if (n <= 0) { break; }
  17368. body += static_cast<size_t>(n);
  17369. }
  17370. server_body_bytes = body;
  17371. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17372. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17373. SSL_shutdown(ssl);
  17374. }
  17375. SSL_free(ssl);
  17376. detail::close_socket(cli);
  17377. SSL_CTX_free(ctx);
  17378. });
  17379. auto se = detail::scope_exit([&] {
  17380. server_thread.join();
  17381. detail::close_socket(srv);
  17382. });
  17383. SSLClient cli("127.0.0.1", port);
  17384. cli.enable_server_certificate_verification(false);
  17385. cli.set_connection_timeout(5, 0);
  17386. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17387. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17388. std::string body(4096, 'A');
  17389. auto res = cli.Put("/api/test", body, "application/json");
  17390. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17391. EXPECT_EQ(StatusCode::OK_200, res->status);
  17392. EXPECT_EQ(body.size(), server_body_bytes.load());
  17393. }
  17394. #endif
  17395. template <typename S, typename C>
  17396. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17397. svr.Get("/stream", [&](const Request &, Response &res) {
  17398. auto data = new std::string("01234567890123456789");
  17399. res.set_content_provider(
  17400. data->size(), "text/plain",
  17401. [&, data](size_t offset, size_t length, DataSink &sink) {
  17402. const size_t DATA_CHUNK_SIZE = 4;
  17403. const auto &d = *data;
  17404. std::this_thread::sleep_for(std::chrono::seconds(1));
  17405. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17406. return true;
  17407. },
  17408. [data](bool success) {
  17409. EXPECT_FALSE(success);
  17410. delete data;
  17411. });
  17412. });
  17413. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17414. auto i = new size_t(0);
  17415. res.set_content_provider(
  17416. "text/plain",
  17417. [i](size_t, DataSink &sink) {
  17418. if (*i < 5) {
  17419. std::this_thread::sleep_for(std::chrono::seconds(1));
  17420. sink.write("abcd", 4);
  17421. (*i)++;
  17422. } else {
  17423. sink.done();
  17424. }
  17425. return true;
  17426. },
  17427. [i](bool success) {
  17428. EXPECT_FALSE(success);
  17429. delete i;
  17430. });
  17431. });
  17432. svr.Get("/chunked", [&](const Request &, Response &res) {
  17433. auto i = new size_t(0);
  17434. res.set_chunked_content_provider(
  17435. "text/plain",
  17436. [i](size_t, DataSink &sink) {
  17437. if (*i < 5) {
  17438. std::this_thread::sleep_for(std::chrono::seconds(1));
  17439. sink.os << "abcd";
  17440. (*i)++;
  17441. } else {
  17442. sink.done();
  17443. }
  17444. return true;
  17445. },
  17446. [i](bool success) {
  17447. EXPECT_FALSE(success);
  17448. delete i;
  17449. });
  17450. });
  17451. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17452. auto se = detail::scope_exit([&] {
  17453. svr.stop();
  17454. listen_thread.join();
  17455. ASSERT_FALSE(svr.is_running());
  17456. });
  17457. svr.wait_until_ready();
  17458. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17459. {
  17460. auto start = std::chrono::steady_clock::now();
  17461. auto res = cli.Get("/stream");
  17462. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17463. std::chrono::steady_clock::now() - start)
  17464. .count();
  17465. ASSERT_FALSE(res);
  17466. EXPECT_EQ(Error::Read, res.error());
  17467. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17468. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17469. }
  17470. {
  17471. auto start = std::chrono::steady_clock::now();
  17472. auto res = cli.Get("/stream_without_length");
  17473. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17474. std::chrono::steady_clock::now() - start)
  17475. .count();
  17476. ASSERT_FALSE(res);
  17477. EXPECT_EQ(Error::Read, res.error());
  17478. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17479. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17480. }
  17481. {
  17482. auto start = std::chrono::steady_clock::now();
  17483. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17484. EXPECT_EQ("abcd", string(data, data_length));
  17485. return true;
  17486. });
  17487. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17488. std::chrono::steady_clock::now() - start)
  17489. .count();
  17490. ASSERT_FALSE(res);
  17491. EXPECT_EQ(Error::Read, res.error());
  17492. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17493. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17494. }
  17495. }
  17496. TEST(MaxTimeoutTest, ContentStream) {
  17497. time_t timeout = 2000;
  17498. time_t threshold = 200;
  17499. Server svr;
  17500. Client cli("localhost", PORT);
  17501. max_timeout_test(svr, cli, timeout, threshold);
  17502. }
  17503. #ifdef CPPHTTPLIB_SSL_ENABLED
  17504. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17505. time_t timeout = 2000;
  17506. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17508. SSLClient cli("localhost", PORT);
  17509. cli.enable_server_certificate_verification(false);
  17510. max_timeout_test(svr, cli, timeout, threshold);
  17511. }
  17512. #endif
  17513. class EventDispatcher {
  17514. public:
  17515. EventDispatcher() {}
  17516. bool wait_event(DataSink *sink) {
  17517. unique_lock<mutex> lk(m_);
  17518. int id = id_;
  17519. // Wait with timeout to prevent hanging if client disconnects
  17520. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17521. [&] { return cid_ == id; })) {
  17522. return false; // Timeout occurred
  17523. }
  17524. sink->write(message_.data(), message_.size());
  17525. return true;
  17526. }
  17527. void send_event(const string &message) {
  17528. lock_guard<mutex> lk(m_);
  17529. cid_ = id_++;
  17530. message_ = message;
  17531. cv_.notify_all();
  17532. }
  17533. private:
  17534. mutex m_;
  17535. condition_variable cv_;
  17536. atomic_int id_{0};
  17537. atomic_int cid_{-1};
  17538. string message_;
  17539. };
  17540. TEST(ClientInThreadTest, Issue2068) {
  17541. EventDispatcher ed;
  17542. Server svr;
  17543. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17544. res.set_chunked_content_provider("text/event-stream",
  17545. [&](size_t /*offset*/, DataSink &sink) {
  17546. return ed.wait_event(&sink);
  17547. });
  17548. });
  17549. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17550. svr.wait_until_ready();
  17551. thread event_thread([&] {
  17552. int id = 0;
  17553. while (svr.is_running()) {
  17554. this_thread::sleep_for(chrono::milliseconds(500));
  17555. std::stringstream ss;
  17556. ss << "data: " << id << "\n\n";
  17557. ed.send_event(ss.str());
  17558. id++;
  17559. }
  17560. });
  17561. auto se = detail::scope_exit([&] {
  17562. svr.stop();
  17563. listen_thread.join();
  17564. event_thread.join();
  17565. ASSERT_FALSE(svr.is_running());
  17566. });
  17567. {
  17568. auto client = detail::make_unique<Client>(HOST, PORT);
  17569. client->set_read_timeout(std::chrono::minutes(10));
  17570. std::atomic<bool> stop{false};
  17571. std::thread t([&] {
  17572. client->Get("/event1",
  17573. [&](const char *, size_t) -> bool { return !stop; });
  17574. });
  17575. std::this_thread::sleep_for(std::chrono::seconds(2));
  17576. stop = true;
  17577. client->stop();
  17578. t.join();
  17579. // Reset client after thread has finished
  17580. client.reset();
  17581. }
  17582. }
  17583. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17584. auto handled = false;
  17585. Server svr;
  17586. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17587. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17588. auto se = detail::scope_exit([&] {
  17589. svr.stop();
  17590. t.join();
  17591. ASSERT_FALSE(svr.is_running());
  17592. ASSERT_FALSE(handled);
  17593. });
  17594. svr.wait_until_ready();
  17595. // Two Content-Length headers with different values — must be rejected
  17596. auto req = "POST /test HTTP/1.1\r\n"
  17597. "Content-Length: 5\r\n"
  17598. "Content-Length: 10\r\n"
  17599. "\r\n"
  17600. "hello";
  17601. std::string response;
  17602. ASSERT_TRUE(send_request(1, req, &response));
  17603. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17604. response.substr(0, response.find("\r\n")));
  17605. }
  17606. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17607. auto handled = false;
  17608. Server svr;
  17609. svr.Post("/test", [&](const Request &, Response &res) {
  17610. handled = true;
  17611. res.set_content("ok", "text/plain");
  17612. });
  17613. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17614. auto se = detail::scope_exit([&] {
  17615. svr.stop();
  17616. t.join();
  17617. ASSERT_FALSE(svr.is_running());
  17618. ASSERT_TRUE(handled);
  17619. });
  17620. svr.wait_until_ready();
  17621. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17622. auto req = "POST /test HTTP/1.1\r\n"
  17623. "Host: localhost\r\n"
  17624. "Content-Length: 5\r\n"
  17625. "Content-Length: 5\r\n"
  17626. "\r\n"
  17627. "hello";
  17628. std::string response;
  17629. ASSERT_TRUE(send_request(1, req, &response));
  17630. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17631. }
  17632. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17633. Server svr;
  17634. svr.Get("/test", [](const Request &, Response &res) {
  17635. res.set_content("ok", "text/plain");
  17636. });
  17637. auto port = svr.bind_to_any_port(HOST);
  17638. thread t = thread([&] { svr.listen_after_bind(); });
  17639. auto se = detail::scope_exit([&] {
  17640. svr.stop();
  17641. t.join();
  17642. ASSERT_FALSE(svr.is_running());
  17643. });
  17644. svr.wait_until_ready();
  17645. auto status_line = [&](const std::string &host_lines) {
  17646. std::string res;
  17647. send_request(
  17648. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17649. &res, port);
  17650. return res.substr(0, res.find("\r\n"));
  17651. };
  17652. const char *accepted[] = {
  17653. "Host: localhost\r\n",
  17654. "Host: a.example:8080\r\n",
  17655. "Host: my_service\r\n",
  17656. "Host: [::1]:8080\r\n",
  17657. "Host: [fe80::1%25eth0]\r\n",
  17658. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17659. };
  17660. for (auto host_lines : accepted) {
  17661. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17662. }
  17663. const char *rejected[] = {
  17664. "Host: a.example\r\nHost: b.example\r\n",
  17665. "Host: a.example\r\nHost: a.example\r\n",
  17666. "Host: a@b.example\r\n",
  17667. "Host: a.example/b\r\n",
  17668. "Host: a.example\\b\r\n",
  17669. "Host: a.example?b\r\n",
  17670. "Host: a.example#b\r\n",
  17671. "Host: a.example b.example\r\n",
  17672. };
  17673. for (auto host_lines : rejected) {
  17674. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17675. << host_lines;
  17676. }
  17677. }
  17678. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17679. Server svr;
  17680. svr.Get("/", [](const Request &req, Response &res) {
  17681. EXPECT_EQ(2U, req.trailers.size());
  17682. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17683. // Denied
  17684. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17685. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17686. // Accepted
  17687. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17688. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17689. EXPECT_TRUE(req.has_trailer("X-World"));
  17690. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17691. res.set_content("ok", "text/plain");
  17692. });
  17693. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17694. auto se = detail::scope_exit([&] {
  17695. svr.stop();
  17696. t.join();
  17697. ASSERT_FALSE(svr.is_running());
  17698. });
  17699. svr.wait_until_ready();
  17700. const std::string req = "GET / HTTP/1.1\r\n"
  17701. "Transfer-Encoding: chunked\r\n"
  17702. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17703. "\r\n"
  17704. "0\r\n"
  17705. "Content-Length: 10\r\n"
  17706. "Host: internal.local\r\n"
  17707. "Content-Type: malicious/content\r\n"
  17708. "Cookie: any\r\n"
  17709. "Set-Cookie: any\r\n"
  17710. "X-Forwarded-For: attacker.com\r\n"
  17711. "X-Real-Ip: 1.1.1.1\r\n"
  17712. "X-Hello: hello\r\n"
  17713. "X-World: world\r\n"
  17714. "\r\n";
  17715. std::string res;
  17716. ASSERT_TRUE(send_request(1, req, &res));
  17717. }
  17718. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17719. // several field lines, and the combined value is what has to be parsed. A
  17720. // Trailer field split across lines therefore declares every name it lists;
  17721. // reading only the first line silently drops the trailers the later lines
  17722. // declare. The prohibited-trailer filter still applies to every line.
  17723. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17724. Server svr;
  17725. size_t observed_trailer_count = 0;
  17726. std::string observed_hello;
  17727. std::string observed_world;
  17728. bool observed_content_length = true;
  17729. svr.Get("/", [&](const Request &req, Response &res) {
  17730. observed_trailer_count = req.trailers.size();
  17731. observed_hello = req.get_trailer_value("X-Hello");
  17732. observed_world = req.get_trailer_value("X-World");
  17733. observed_content_length = req.has_trailer("Content-Length");
  17734. res.set_content("ok", "text/plain");
  17735. });
  17736. auto port = svr.bind_to_any_port(HOST);
  17737. thread t = thread([&]() { svr.listen_after_bind(); });
  17738. auto se = detail::scope_exit([&] {
  17739. svr.stop();
  17740. t.join();
  17741. ASSERT_FALSE(svr.is_running());
  17742. });
  17743. svr.wait_until_ready();
  17744. const std::string req = "GET / HTTP/1.1\r\n"
  17745. "Host: localhost\r\n"
  17746. "Transfer-Encoding: chunked\r\n"
  17747. "Trailer: X-Hello\r\n"
  17748. "Trailer: X-World, Content-Length\r\n"
  17749. "\r\n"
  17750. "0\r\n"
  17751. "X-Hello: hello\r\n"
  17752. "X-World: world\r\n"
  17753. "Content-Length: 10\r\n"
  17754. "\r\n";
  17755. std::string res;
  17756. ASSERT_TRUE(send_request(1, req, &res, port));
  17757. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17758. // Accepted: both field lines contribute to the declared set
  17759. EXPECT_EQ(2U, observed_trailer_count);
  17760. EXPECT_EQ(observed_hello, "hello");
  17761. EXPECT_EQ(observed_world, "world");
  17762. // Denied: a prohibited name stays prohibited on a later field line
  17763. EXPECT_FALSE(observed_content_length);
  17764. }
  17765. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17766. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17767. // unbounded run of fields that are never declared, because the counter would
  17768. // only advance for declared fields.
  17769. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17770. Server svr;
  17771. bool handler_called = false;
  17772. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17773. handler_called = true;
  17774. res.set_content("ok", "text/plain");
  17775. });
  17776. auto port = svr.bind_to_any_port(HOST);
  17777. thread t = thread([&]() { svr.listen_after_bind(); });
  17778. auto se = detail::scope_exit([&] {
  17779. svr.stop();
  17780. t.join();
  17781. ASSERT_FALSE(svr.is_running());
  17782. });
  17783. svr.wait_until_ready();
  17784. // Declare nothing, then send far more undeclared trailer fields than the
  17785. // header-count limit. Parsing must stop and reject the request rather than
  17786. // read every line.
  17787. std::string req = "GET / HTTP/1.1\r\n"
  17788. "Transfer-Encoding: chunked\r\n"
  17789. "\r\n"
  17790. "0\r\n";
  17791. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17792. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17793. }
  17794. req += "\r\n";
  17795. std::string res;
  17796. ASSERT_TRUE(send_request(1, req, &res, port));
  17797. // The request is rejected before the handler runs.
  17798. EXPECT_FALSE(handler_called);
  17799. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17800. }
  17801. // The set of declared trailer names is capped so a peer cannot grow it without
  17802. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17803. // declared past the cap is not honored, even if the field is actually sent.
  17804. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17805. Server svr;
  17806. // One name inside the cap and one past it, so the test tracks the cap rather
  17807. // than a fixed count.
  17808. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17809. const std::string within_cap_name = "X-T-0";
  17810. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17811. bool observed_within_cap = false;
  17812. bool observed_past_cap = false;
  17813. svr.Get("/", [&](const Request &req, Response &res) {
  17814. observed_within_cap = req.has_trailer(within_cap_name);
  17815. observed_past_cap = req.has_trailer(past_cap_name);
  17816. res.set_content("ok", "text/plain");
  17817. });
  17818. auto port = svr.bind_to_any_port(HOST);
  17819. thread t = thread([&]() { svr.listen_after_bind(); });
  17820. auto se = detail::scope_exit([&] {
  17821. svr.stop();
  17822. t.join();
  17823. ASSERT_FALSE(svr.is_running());
  17824. });
  17825. svr.wait_until_ready();
  17826. // Declare more trailer names than the cap in a single Trailer field, then
  17827. // actually send the first (within the cap) and the last (past it).
  17828. std::string trailer_decl = "Trailer: ";
  17829. for (int i = 0; i < declared_count; i++) {
  17830. if (i != 0) { trailer_decl += ", "; }
  17831. trailer_decl += "X-T-" + std::to_string(i);
  17832. }
  17833. trailer_decl += "\r\n";
  17834. const std::string req = "GET / HTTP/1.1\r\n"
  17835. "Host: localhost\r\n"
  17836. "Transfer-Encoding: chunked\r\n" +
  17837. trailer_decl +
  17838. "\r\n"
  17839. "0\r\n" +
  17840. within_cap_name + ": a\r\n" + past_cap_name +
  17841. ": b\r\n"
  17842. "\r\n";
  17843. std::string res;
  17844. ASSERT_TRUE(send_request(1, req, &res, port));
  17845. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17846. // A name within the cap is honored; one declared past the cap is dropped.
  17847. EXPECT_TRUE(observed_within_cap);
  17848. EXPECT_FALSE(observed_past_cap);
  17849. }
  17850. // A direct client that is not listed in trusted_proxies must not be able to
  17851. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17852. // the peer address on the actual TCP connection determines whether the
  17853. // header is honored.
  17854. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17855. Server svr;
  17856. // Deliberately does NOT include the loopback address the test client
  17857. // actually connects from, so the direct connection is not a trusted proxy.
  17858. svr.set_trusted_proxies({"203.0.113.66"});
  17859. std::string observed_remote_addr;
  17860. svr.Get("/ip", [&](const Request &req, Response &res) {
  17861. observed_remote_addr = req.remote_addr;
  17862. res.set_content("ok", "text/plain");
  17863. });
  17864. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17865. auto se = detail::scope_exit([&] {
  17866. svr.stop();
  17867. t.join();
  17868. ASSERT_FALSE(svr.is_running());
  17869. });
  17870. svr.wait_until_ready();
  17871. Client cli(HOST, PORT);
  17872. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17874. EXPECT_EQ(StatusCode::OK_200, res->status);
  17875. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17876. // ignored entirely and the real connection-level address retained.
  17877. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17878. observed_remote_addr == "127.0.0.1");
  17879. }
  17880. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17881. Server svr;
  17882. std::string observed_remote_addr;
  17883. std::string observed_xff;
  17884. svr.Get("/ip", [&](const Request &req, Response &res) {
  17885. observed_remote_addr = req.remote_addr;
  17886. observed_xff = req.get_header_value("X-Forwarded-For");
  17887. res.set_content("ok", "text/plain");
  17888. });
  17889. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17890. auto se = detail::scope_exit([&] {
  17891. svr.stop();
  17892. t.join();
  17893. ASSERT_FALSE(svr.is_running());
  17894. });
  17895. svr.wait_until_ready();
  17896. Client cli(HOST, PORT);
  17897. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17899. EXPECT_EQ(StatusCode::OK_200, res->status);
  17900. EXPECT_EQ(observed_xff, "203.0.113.66");
  17901. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17902. observed_remote_addr == "127.0.0.1");
  17903. }
  17904. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17905. Server svr;
  17906. svr.set_trusted_proxies({"203.0.113.66"});
  17907. std::string observed_remote_addr;
  17908. std::string observed_xff;
  17909. svr.Get("/ip", [&](const Request &req, Response &res) {
  17910. observed_remote_addr = req.remote_addr;
  17911. observed_xff = req.get_header_value("X-Forwarded-For");
  17912. res.set_content("ok", "text/plain");
  17913. });
  17914. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17915. auto se = detail::scope_exit([&] {
  17916. svr.stop();
  17917. t.join();
  17918. ASSERT_FALSE(svr.is_running());
  17919. });
  17920. svr.wait_until_ready();
  17921. Client cli(HOST, PORT);
  17922. auto res = cli.Get("/ip");
  17923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17924. EXPECT_EQ(StatusCode::OK_200, res->status);
  17925. EXPECT_EQ(observed_xff, "");
  17926. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17927. observed_remote_addr == "127.0.0.1");
  17928. }
  17929. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17930. Server svr;
  17931. // Include the loopback address the test client actually connects from, so
  17932. // the direct connection itself is recognized as the trusted proxy hop.
  17933. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17934. std::string observed_remote_addr;
  17935. std::string observed_xff;
  17936. svr.Get("/ip", [&](const Request &req, Response &res) {
  17937. observed_remote_addr = req.remote_addr;
  17938. observed_xff = req.get_header_value("X-Forwarded-For");
  17939. res.set_content("ok", "text/plain");
  17940. });
  17941. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17942. auto se = detail::scope_exit([&] {
  17943. svr.stop();
  17944. t.join();
  17945. ASSERT_FALSE(svr.is_running());
  17946. });
  17947. svr.wait_until_ready();
  17948. Client cli(HOST, PORT);
  17949. auto res = cli.Get(
  17950. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17952. EXPECT_EQ(StatusCode::OK_200, res->status);
  17953. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17954. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17955. }
  17956. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17957. Server svr;
  17958. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17959. std::string observed_remote_addr;
  17960. std::string observed_xff;
  17961. svr.Get("/ip", [&](const Request &req, Response &res) {
  17962. observed_remote_addr = req.remote_addr;
  17963. observed_xff = req.get_header_value("X-Forwarded-For");
  17964. res.set_content("ok", "text/plain");
  17965. });
  17966. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17967. auto se = detail::scope_exit([&] {
  17968. svr.stop();
  17969. t.join();
  17970. ASSERT_FALSE(svr.is_running());
  17971. });
  17972. svr.wait_until_ready();
  17973. Client cli(HOST, PORT);
  17974. auto res = cli.Get(
  17975. "/ip",
  17976. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17978. EXPECT_EQ(StatusCode::OK_200, res->status);
  17979. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17980. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17981. }
  17982. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17983. Server svr;
  17984. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17985. std::string observed_remote_addr;
  17986. std::string observed_xff;
  17987. svr.Get("/ip", [&](const Request &req, Response &res) {
  17988. observed_remote_addr = req.remote_addr;
  17989. observed_xff = req.get_header_value("X-Forwarded-For");
  17990. res.set_content("ok", "text/plain");
  17991. });
  17992. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17993. auto se = detail::scope_exit([&] {
  17994. svr.stop();
  17995. t.join();
  17996. ASSERT_FALSE(svr.is_running());
  17997. });
  17998. svr.wait_until_ready();
  17999. Client cli(HOST, PORT);
  18000. auto res = cli.Get(
  18001. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18003. EXPECT_EQ(StatusCode::OK_200, res->status);
  18004. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18005. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18006. // and must not be selected.
  18007. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18008. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18009. }
  18010. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18011. Server svr;
  18012. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18013. std::string observed_remote_addr;
  18014. svr.Get("/ip", [&](const Request &req, Response &res) {
  18015. observed_remote_addr = req.remote_addr;
  18016. res.set_content("ok", "text/plain");
  18017. });
  18018. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18019. auto se = detail::scope_exit([&] {
  18020. svr.stop();
  18021. t.join();
  18022. ASSERT_FALSE(svr.is_running());
  18023. });
  18024. svr.wait_until_ready();
  18025. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18026. // a forged address and the trusted proxy's own address; the forged value must
  18027. // not win over the address the trusted proxy actually recorded.
  18028. Client cli(HOST, PORT);
  18029. auto res = cli.Get(
  18030. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18032. EXPECT_EQ(StatusCode::OK_200, res->status);
  18033. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18034. }
  18035. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18036. Server svr;
  18037. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18038. std::string observed_remote_addr;
  18039. std::string observed_xff;
  18040. svr.Get("/ip", [&](const Request &req, Response &res) {
  18041. observed_remote_addr = req.remote_addr;
  18042. observed_xff = req.get_header_value("X-Forwarded-For");
  18043. res.set_content("ok", "text/plain");
  18044. });
  18045. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18046. auto se = detail::scope_exit([&] {
  18047. svr.stop();
  18048. t.join();
  18049. ASSERT_FALSE(svr.is_running());
  18050. });
  18051. svr.wait_until_ready();
  18052. Client cli(HOST, PORT);
  18053. auto res = cli.Get(
  18054. "/ip",
  18055. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18057. EXPECT_EQ(StatusCode::OK_200, res->status);
  18058. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18059. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18060. }
  18061. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18062. Server svr;
  18063. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18064. std::string observed_remote_addr;
  18065. std::string observed_xff;
  18066. svr.Get("/ip", [&](const Request &req, Response &res) {
  18067. observed_remote_addr = req.remote_addr;
  18068. observed_xff = req.get_header_value("X-Forwarded-For");
  18069. res.set_content("ok", "text/plain");
  18070. });
  18071. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18072. auto se = detail::scope_exit([&] {
  18073. svr.stop();
  18074. t.join();
  18075. ASSERT_FALSE(svr.is_running());
  18076. });
  18077. svr.wait_until_ready();
  18078. std::string raw_req =
  18079. "GET /ip HTTP/1.1\r\n"
  18080. "Host: localhost\r\n"
  18081. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18082. "Connection: close\r\n"
  18083. "\r\n";
  18084. std::string out;
  18085. ASSERT_TRUE(send_request(5, raw_req, &out));
  18086. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18087. // Header parser trims surrounding whitespace of the header value
  18088. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18089. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18090. }
  18091. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18092. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18093. // their own X-Forwarded-For as a separate field line rather than extending the
  18094. // one the client sent, so every occurrence has to be taken into account.
  18095. // Reading only the first one hands back the address the client chose.
  18096. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18097. Server svr;
  18098. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18099. std::string observed_remote_addr;
  18100. size_t observed_xff_count = 0;
  18101. svr.Get("/ip", [&](const Request &req, Response &res) {
  18102. observed_remote_addr = req.remote_addr;
  18103. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18104. res.set_content("ok", "text/plain");
  18105. });
  18106. auto port = svr.bind_to_any_port(HOST);
  18107. thread t = thread([&]() { svr.listen_after_bind(); });
  18108. auto se = detail::scope_exit([&] {
  18109. svr.stop();
  18110. t.join();
  18111. ASSERT_FALSE(svr.is_running());
  18112. });
  18113. svr.wait_until_ready();
  18114. // The client supplies the first field line; the trusted proxy appends the
  18115. // address it observed as a second one.
  18116. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18117. "Host: localhost\r\n"
  18118. "X-Forwarded-For: 1.2.3.4\r\n"
  18119. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18120. "Connection: close\r\n"
  18121. "\r\n";
  18122. std::string out;
  18123. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18124. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18125. EXPECT_EQ(observed_xff_count, 2U);
  18126. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18127. // The same chain spread over one field line per hop derives the same client
  18128. // address, i.e. the split and the comma-joined representations agree.
  18129. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18130. "Host: localhost\r\n"
  18131. "X-Forwarded-For: 1.2.3.4\r\n"
  18132. "X-Forwarded-For: 198.51.100.23\r\n"
  18133. "X-Forwarded-For: 192.0.2.45\r\n"
  18134. "Connection: close\r\n"
  18135. "\r\n";
  18136. out.clear();
  18137. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18138. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18139. EXPECT_EQ(observed_xff_count, 3U);
  18140. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18141. }
  18142. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18143. // crash the server (it used to call front() on an empty vector inside
  18144. // get_client_ip). The connection-level remote address must be retained instead.
  18145. static void run_malformed_xff_test(const std::string &xff_value) {
  18146. Server svr;
  18147. svr.set_trusted_proxies({"192.0.2.45"});
  18148. std::string observed_remote_addr;
  18149. svr.Get("/ip", [&](const Request &req, Response &res) {
  18150. observed_remote_addr = req.remote_addr;
  18151. res.set_content("ok", "text/plain");
  18152. });
  18153. int port = 0;
  18154. thread t = thread([&]() {
  18155. port = svr.bind_to_any_port(HOST);
  18156. svr.listen_after_bind();
  18157. });
  18158. auto se = detail::scope_exit([&] {
  18159. svr.stop();
  18160. t.join();
  18161. ASSERT_FALSE(svr.is_running());
  18162. });
  18163. svr.wait_until_ready();
  18164. Client cli(HOST, port);
  18165. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18167. EXPECT_EQ(StatusCode::OK_200, res->status);
  18168. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18169. observed_remote_addr == "127.0.0.1");
  18170. }
  18171. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18172. run_malformed_xff_test("");
  18173. }
  18174. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18175. run_malformed_xff_test(",");
  18176. }
  18177. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18178. run_malformed_xff_test(", , ,");
  18179. }
  18180. // The same rule applies to Accept: a request whose acceptable types are spread
  18181. // over several field lines must be negotiated against all of them.
  18182. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18183. // case-insensitive connection options. Comparing the whole field value against
  18184. // one option misses a client that sends several of them, and misses every
  18185. // casing but the one written in the comparison.
  18186. //
  18187. // Sends req, reads the response, then reuses the same socket for a second
  18188. // request to find out whether the server kept the connection.
  18189. static void probe_connection_reuse(int port, const std::string &req,
  18190. bool *announced_close, bool *reusable) {
  18191. auto error = Error::Success;
  18192. auto sock = detail::create_client_socket(
  18193. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18194. /*connection_timeout_sec=*/5, 0,
  18195. /*read_timeout_sec=*/1, 0,
  18196. /*write_timeout_sec=*/5, 0, std::string(), error);
  18197. ASSERT_NE(sock, INVALID_SOCKET);
  18198. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18199. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18200. "Host: localhost\r\n"
  18201. "Connection: close\r\n"
  18202. "\r\n";
  18203. std::string first_response;
  18204. std::string second_response;
  18205. detail::process_client_socket(
  18206. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18207. [&](Stream &strm) {
  18208. if (strm.write(req.data(), req.size()) !=
  18209. static_cast<ssize_t>(req.size())) {
  18210. return false;
  18211. }
  18212. char buf[512];
  18213. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18214. // Headers plus the two-byte body of the handler below
  18215. while (reader.getline()) {
  18216. first_response += reader.ptr();
  18217. if (first_response.find("ok") != std::string::npos) { break; }
  18218. }
  18219. if (strm.write(second.data(), second.size()) !=
  18220. static_cast<ssize_t>(second.size())) {
  18221. return true;
  18222. }
  18223. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18224. while (reader2.getline()) {
  18225. second_response += reader2.ptr();
  18226. if (second_response.find("ok") != std::string::npos) { break; }
  18227. }
  18228. return true;
  18229. });
  18230. *announced_close =
  18231. first_response.find("Connection: close") != std::string::npos;
  18232. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18233. }
  18234. class ConnectionTokenTest : public ::testing::Test {
  18235. protected:
  18236. void SetUp() override {
  18237. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18238. res.set_content("ok", "text/plain");
  18239. });
  18240. port_ = svr_.bind_to_any_port(HOST);
  18241. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18242. svr_.wait_until_ready();
  18243. }
  18244. void TearDown() override {
  18245. svr_.stop();
  18246. if (thread_.joinable()) { thread_.join(); }
  18247. }
  18248. Server svr_;
  18249. int port_ = 0;
  18250. thread thread_;
  18251. };
  18252. // "close" alongside another option still closes the connection, and the
  18253. // response says so rather than leaving the peer to discover it.
  18254. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18255. bool announced_close = false;
  18256. bool reusable = true;
  18257. probe_connection_reuse(port_,
  18258. "GET /keepalive HTTP/1.1\r\n"
  18259. "Host: localhost\r\n"
  18260. "Connection: keep-alive, close\r\n"
  18261. "\r\n",
  18262. &announced_close, &reusable);
  18263. EXPECT_TRUE(announced_close);
  18264. EXPECT_FALSE(reusable);
  18265. }
  18266. // "close" split over two field lines is the same list, so it is honored too.
  18267. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18268. bool announced_close = false;
  18269. bool reusable = true;
  18270. probe_connection_reuse(port_,
  18271. "GET /keepalive HTTP/1.1\r\n"
  18272. "Host: localhost\r\n"
  18273. "Connection: keep-alive\r\n"
  18274. "Connection: close\r\n"
  18275. "\r\n",
  18276. &announced_close, &reusable);
  18277. EXPECT_TRUE(announced_close);
  18278. EXPECT_FALSE(reusable);
  18279. }
  18280. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18281. // keep-alive in the spelling everyone actually sends keeps its connection.
  18282. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18283. bool announced_close = false;
  18284. bool reusable = false;
  18285. probe_connection_reuse(port_,
  18286. "GET /keepalive HTTP/1.0\r\n"
  18287. "Host: localhost\r\n"
  18288. "Connection: keep-alive\r\n"
  18289. "\r\n",
  18290. &announced_close, &reusable);
  18291. EXPECT_FALSE(announced_close);
  18292. EXPECT_TRUE(reusable);
  18293. }
  18294. // A token the value merely contains is not the token itself.
  18295. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18296. bool announced_close = false;
  18297. bool reusable = false;
  18298. probe_connection_reuse(port_,
  18299. "GET /keepalive HTTP/1.1\r\n"
  18300. "Host: localhost\r\n"
  18301. "Connection: notclose\r\n"
  18302. "\r\n",
  18303. &announced_close, &reusable);
  18304. EXPECT_FALSE(announced_close);
  18305. EXPECT_TRUE(reusable);
  18306. }
  18307. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18308. Server svr;
  18309. std::vector<std::string> observed_types;
  18310. svr.Get("/", [&](const Request &req, Response &res) {
  18311. observed_types = req.accept_content_types;
  18312. res.set_content("ok", "text/plain");
  18313. });
  18314. auto port = svr.bind_to_any_port(HOST);
  18315. thread t = thread([&]() { svr.listen_after_bind(); });
  18316. auto se = detail::scope_exit([&] {
  18317. svr.stop();
  18318. t.join();
  18319. ASSERT_FALSE(svr.is_running());
  18320. });
  18321. svr.wait_until_ready();
  18322. Client cli(HOST, port);
  18323. Headers headers;
  18324. headers.emplace("Accept", "text/plain;q=0.5");
  18325. headers.emplace("Accept", "application/json");
  18326. auto res = cli.Get("/", headers);
  18327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18328. EXPECT_EQ(StatusCode::OK_200, res->status);
  18329. // Sorted by q-value, so the second field line's type comes first
  18330. ASSERT_EQ(2U, observed_types.size());
  18331. EXPECT_EQ("application/json", observed_types[0]);
  18332. EXPECT_EQ("text/plain", observed_types[1]);
  18333. }
  18334. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18335. // empty field line must not contribute a bare comma to the combined value.
  18336. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18337. Server svr;
  18338. std::vector<std::string> observed_types;
  18339. svr.Get("/", [&](const Request &req, Response &res) {
  18340. observed_types = req.accept_content_types;
  18341. res.set_content("ok", "text/plain");
  18342. });
  18343. auto port = svr.bind_to_any_port(HOST);
  18344. thread t = thread([&]() { svr.listen_after_bind(); });
  18345. auto se = detail::scope_exit([&] {
  18346. svr.stop();
  18347. t.join();
  18348. ASSERT_FALSE(svr.is_running());
  18349. });
  18350. svr.wait_until_ready();
  18351. // Empty first field line, then a real one
  18352. std::string raw_req = "GET / HTTP/1.1\r\n"
  18353. "Host: localhost\r\n"
  18354. "Accept:\r\n"
  18355. "Accept: application/json\r\n"
  18356. "Connection: close\r\n"
  18357. "\r\n";
  18358. std::string out;
  18359. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18360. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18361. ASSERT_EQ(1U, observed_types.size());
  18362. EXPECT_EQ("application/json", observed_types[0]);
  18363. }
  18364. // The skip in get_combined_header_value() is what keeps an empty field line
  18365. // from contributing a bare comma. Only a trailing empty field line exercises
  18366. // it: a leading one is already covered by the "combined is still empty" check,
  18367. // and parse_accept_header() now ignores the empty element either way, so the
  18368. // request-level test above can no longer tell the two apart.
  18369. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18370. Headers headers;
  18371. headers.emplace("Accept", "text/html");
  18372. headers.emplace("Accept", "");
  18373. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18374. headers.clear();
  18375. headers.emplace("Accept", "");
  18376. headers.emplace("Accept", "application/json");
  18377. EXPECT_EQ("application/json",
  18378. detail::get_combined_header_value(headers, "Accept"));
  18379. }
  18380. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18381. // An encoding offered on a later Accept-Encoding field line is still offered.
  18382. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18383. Server svr;
  18384. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18385. res.set_content(std::string(1024, 'x'), "text/plain");
  18386. });
  18387. auto port = svr.bind_to_any_port(HOST);
  18388. thread t = thread([&]() { svr.listen_after_bind(); });
  18389. auto se = detail::scope_exit([&] {
  18390. svr.stop();
  18391. t.join();
  18392. ASSERT_FALSE(svr.is_running());
  18393. });
  18394. svr.wait_until_ready();
  18395. Client cli(HOST, port);
  18396. cli.set_decompress(false);
  18397. Headers headers;
  18398. headers.emplace("Accept-Encoding", "identity");
  18399. headers.emplace("Accept-Encoding", "gzip");
  18400. auto res = cli.Get("/", headers);
  18401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18402. EXPECT_EQ(StatusCode::OK_200, res->status);
  18403. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18404. }
  18405. #endif
  18406. #ifndef _WIN32
  18407. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18408. Server svr;
  18409. svr.Post("/post", [&](const Request &req, Response &res) {
  18410. res.set_content(req.body, "text/plain");
  18411. });
  18412. svr.Put("/put", [&](const Request &req, Response &res) {
  18413. res.set_content(req.body, "text/plain");
  18414. });
  18415. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18416. res.set_content(req.body, "text/plain");
  18417. });
  18418. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18419. res.set_content(req.body, "text/plain");
  18420. });
  18421. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18422. auto se = detail::scope_exit([&] {
  18423. svr.stop();
  18424. t.join();
  18425. ASSERT_FALSE(svr.is_running());
  18426. });
  18427. svr.wait_until_ready();
  18428. std::string resp;
  18429. // POST without Content-Length
  18430. ASSERT_TRUE(send_request(5,
  18431. "POST /post HTTP/1.1\r\n"
  18432. "Host: localhost\r\n"
  18433. "Connection: close\r\n"
  18434. "\r\n",
  18435. &resp));
  18436. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18437. // PUT without Content-Length
  18438. resp.clear();
  18439. ASSERT_TRUE(send_request(5,
  18440. "PUT /put HTTP/1.1\r\n"
  18441. "Host: localhost\r\n"
  18442. "Connection: close\r\n"
  18443. "\r\n",
  18444. &resp));
  18445. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18446. // PATCH without Content-Length
  18447. resp.clear();
  18448. ASSERT_TRUE(send_request(5,
  18449. "PATCH /patch HTTP/1.1\r\n"
  18450. "Host: localhost\r\n"
  18451. "Connection: close\r\n"
  18452. "\r\n",
  18453. &resp));
  18454. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18455. // DELETE without Content-Length
  18456. resp.clear();
  18457. ASSERT_TRUE(send_request(5,
  18458. "DELETE /delete HTTP/1.1\r\n"
  18459. "Host: localhost\r\n"
  18460. "Connection: close\r\n"
  18461. "\r\n",
  18462. &resp));
  18463. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18464. }
  18465. #endif
  18466. //==============================================================================
  18467. // open_stream() Tests
  18468. //==============================================================================
  18469. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18470. std::string result;
  18471. char buf[8192];
  18472. ssize_t n;
  18473. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18474. result.append(buf, static_cast<size_t>(n));
  18475. }
  18476. return result;
  18477. }
  18478. // Mock stream for unit tests
  18479. class MockStream : public Stream {
  18480. public:
  18481. std::string data;
  18482. size_t pos = 0;
  18483. ssize_t error_after = -1; // -1 = no error
  18484. explicit MockStream(const std::string &d, ssize_t err = -1)
  18485. : data(d), error_after(err) {}
  18486. bool is_readable() const override { return true; }
  18487. bool wait_readable() const override { return true; }
  18488. bool wait_writable() const override { return true; }
  18489. ssize_t read(char *ptr, size_t size) override {
  18490. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18491. if (pos >= data.size()) return 0;
  18492. size_t limit =
  18493. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18494. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18495. std::memcpy(ptr, data.data() + pos, to_read);
  18496. pos += to_read;
  18497. return static_cast<ssize_t>(to_read);
  18498. }
  18499. ssize_t write(const char *, size_t) override { return -1; }
  18500. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18501. ip = "127.0.0.1";
  18502. port = 0;
  18503. }
  18504. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18505. ip = "127.0.0.1";
  18506. port = 0;
  18507. }
  18508. socket_t socket() const override { return INVALID_SOCKET; }
  18509. time_t duration() const override { return 0; }
  18510. };
  18511. TEST(StreamHandleTest, Basic) {
  18512. ClientImpl::StreamHandle handle;
  18513. EXPECT_FALSE(handle.is_valid());
  18514. handle.response = detail::make_unique<Response>();
  18515. handle.error = Error::Connection;
  18516. EXPECT_FALSE(handle.is_valid());
  18517. handle.error = Error::Success;
  18518. EXPECT_TRUE(handle.is_valid());
  18519. }
  18520. TEST(BodyReaderTest, Basic) {
  18521. MockStream stream("Hello, World!");
  18522. detail::BodyReader reader;
  18523. reader.stream = &stream;
  18524. reader.content_length = 13;
  18525. char buf[32];
  18526. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18527. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18528. EXPECT_TRUE(reader.eof);
  18529. }
  18530. TEST(BodyReaderTest, NoStream) {
  18531. detail::BodyReader reader;
  18532. char buf[32];
  18533. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18534. EXPECT_EQ(Error::Connection, reader.last_error);
  18535. }
  18536. TEST(BodyReaderTest, Error) {
  18537. MockStream stream("Hello, World!", 5);
  18538. detail::BodyReader reader;
  18539. reader.stream = &stream;
  18540. reader.content_length = 13;
  18541. char buf[32];
  18542. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18543. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18544. EXPECT_EQ(Error::Read, reader.last_error);
  18545. }
  18546. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18547. // Mock-based StreamHandle tests relying on private internals are removed.
  18548. class OpenStreamTest : public ::testing::Test {
  18549. protected:
  18550. void SetUp() override {
  18551. svr_.Get("/hello", [](const Request &, Response &res) {
  18552. res.set_content("Hello World!", "text/plain");
  18553. });
  18554. svr_.Get("/large", [](const Request &, Response &res) {
  18555. res.set_content(std::string(10000, 'X'), "text/plain");
  18556. });
  18557. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18558. res.set_content("Hello World!", "image/jpeg");
  18559. res.set_header("Content-Encoding", "UTF-8");
  18560. });
  18561. svr_.Get("/chunked", [](const Request &, Response &res) {
  18562. res.set_chunked_content_provider("text/plain",
  18563. [](size_t offset, DataSink &sink) {
  18564. if (offset < 15) {
  18565. sink.write("chunk", 5);
  18566. return true;
  18567. }
  18568. sink.done();
  18569. return true;
  18570. });
  18571. });
  18572. svr_.Get("/compressible", [](const Request &, Response &res) {
  18573. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18574. DataSink &sink) {
  18575. if (offset < 100 * 1024) {
  18576. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18577. sink.write(chunk.data(), chunk.size());
  18578. return true;
  18579. }
  18580. sink.done();
  18581. return true;
  18582. });
  18583. });
  18584. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18585. [](const Request & /*req*/, Response &res) {
  18586. auto i = new int(0);
  18587. res.set_header("Trailer", "Content-Length, X-Allowed");
  18588. res.set_chunked_content_provider(
  18589. "text/plain",
  18590. [i](size_t /*offset*/, DataSink &sink) {
  18591. switch (*i) {
  18592. case 0: sink.os << "123"; break;
  18593. case 1: sink.os << "456"; break;
  18594. case 2: sink.os << "789"; break;
  18595. case 3: {
  18596. sink.done_with_trailer(
  18597. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18598. } break;
  18599. }
  18600. (*i)++;
  18601. return true;
  18602. },
  18603. [i](bool success) {
  18604. EXPECT_TRUE(success);
  18605. delete i;
  18606. });
  18607. });
  18608. // Echo headers endpoint for header-related tests
  18609. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18610. std::string body;
  18611. for (const auto &h : req.headers) {
  18612. body.append(h.first);
  18613. body.push_back(':');
  18614. body.append(h.second);
  18615. body.push_back('\n');
  18616. }
  18617. res.set_content(body, "text/plain");
  18618. });
  18619. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18620. std::string body;
  18621. for (const auto &h : req.headers) {
  18622. body.append(h.first);
  18623. body.push_back(':');
  18624. body.append(h.second);
  18625. body.push_back('\n');
  18626. }
  18627. res.set_content(body, "text/plain");
  18628. });
  18629. port_ = svr_.bind_to_any_port("127.0.0.1");
  18630. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18631. svr_.wait_until_ready();
  18632. }
  18633. void TearDown() override {
  18634. svr_.stop();
  18635. if (thread_.joinable()) thread_.join();
  18636. }
  18637. Server svr_;
  18638. std::thread thread_;
  18639. int port_ = 0;
  18640. };
  18641. TEST_F(OpenStreamTest, Basic) {
  18642. Client cli("127.0.0.1", port_);
  18643. auto handle = cli.open_stream("GET", "/hello");
  18644. EXPECT_TRUE(handle.is_valid());
  18645. EXPECT_EQ("Hello World!", read_all(handle));
  18646. }
  18647. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18648. Client cli("127.0.0.1", port_);
  18649. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18650. ASSERT_TRUE(handle.is_valid());
  18651. EXPECT_EQ("Hello World!", read_all(handle));
  18652. }
  18653. TEST_F(OpenStreamTest, SmallBuffer) {
  18654. Client cli("127.0.0.1", port_);
  18655. auto handle = cli.open_stream("GET", "/hello");
  18656. std::string result;
  18657. char buf[4];
  18658. ssize_t n;
  18659. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18660. result.append(buf, static_cast<size_t>(n));
  18661. EXPECT_EQ("Hello World!", result);
  18662. }
  18663. TEST_F(OpenStreamTest, DefaultHeaders) {
  18664. Client cli("127.0.0.1", port_);
  18665. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18666. {
  18667. auto handle = cli.open_stream("GET", "/echo-headers");
  18668. ASSERT_TRUE(handle.is_valid());
  18669. auto body = read_all(handle);
  18670. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18671. std::string::npos);
  18672. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18673. std::string::npos);
  18674. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18675. }
  18676. // open_stream POST with body and no explicit content_type should NOT add
  18677. // text/plain Content-Type (behavior differs from non-streaming path), but
  18678. // should include Content-Length
  18679. {
  18680. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18681. ASSERT_TRUE(handle.is_valid());
  18682. auto body = read_all(handle);
  18683. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18684. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18685. }
  18686. // open_stream POST with explicit Content-Type should preserve it
  18687. {
  18688. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18689. {{"Content-Type", "application/custom"}},
  18690. "{}", "application/custom");
  18691. ASSERT_TRUE(handle.is_valid());
  18692. auto body = read_all(handle);
  18693. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18694. }
  18695. // User-specified User-Agent must not be overwritten for stream API
  18696. {
  18697. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18698. {{"User-Agent", "MyAgent/1.2"}});
  18699. ASSERT_TRUE(handle.is_valid());
  18700. auto body = read_all(handle);
  18701. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18702. }
  18703. }
  18704. TEST_F(OpenStreamTest, Large) {
  18705. Client cli("127.0.0.1", port_);
  18706. auto handle = cli.open_stream("GET", "/large");
  18707. EXPECT_EQ(10000u, read_all(handle).size());
  18708. }
  18709. TEST_F(OpenStreamTest, ConnectionError) {
  18710. Client cli("127.0.0.1", 9999);
  18711. auto handle = cli.open_stream("GET", "/hello");
  18712. EXPECT_FALSE(handle.is_valid());
  18713. }
  18714. TEST_F(OpenStreamTest, Chunked) {
  18715. Client cli("127.0.0.1", port_);
  18716. auto handle = cli.open_stream("GET", "/chunked");
  18717. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18718. "Transfer-Encoding") == "chunked");
  18719. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18720. }
  18721. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18722. Client cli("127.0.0.1", port_);
  18723. auto handle =
  18724. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18725. ASSERT_TRUE(handle.is_valid());
  18726. // Consume body to allow trailers to be received/parsed
  18727. auto body = read_all(handle);
  18728. // Explicitly parse trailers (ensure trailers are available for assertion)
  18729. handle.parse_trailers_if_needed();
  18730. EXPECT_EQ(std::string("123456789"), body);
  18731. // The response should include a Trailer header declaring both names
  18732. ASSERT_TRUE(handle.response);
  18733. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18734. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18735. handle.response->get_header_value("Trailer"));
  18736. // Prohibited trailer must not be present
  18737. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18738. // Allowed trailer should be present
  18739. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18740. EXPECT_EQ(std::string("yes"),
  18741. handle.response->get_trailer_value("X-Allowed"));
  18742. // Verify trailers are NOT present as regular headers
  18743. EXPECT_EQ(std::string(""),
  18744. handle.response->get_header_value("Content-Length"));
  18745. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18746. }
  18747. // Accepts one connection on an OS-assigned port, which it hands over through
  18748. // port_promise, reads the request head and sends back response. after_send,
  18749. // if given, runs on the connection before it is closed.
  18750. static std::thread
  18751. serve_single_response(std::promise<int> &port_promise,
  18752. const std::string &response,
  18753. std::function<void(socket_t)> after_send = nullptr) {
  18754. return std::thread([&port_promise, response, after_send] {
  18755. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18756. default_socket_options(srv);
  18757. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18758. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18759. sockaddr_in addr{};
  18760. addr.sin_family = AF_INET;
  18761. addr.sin_port = htons(0); // Let OS assign a free port
  18762. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18763. int opt = 1;
  18764. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18765. #ifdef _WIN32
  18766. reinterpret_cast<const char *>(&opt),
  18767. #else
  18768. &opt,
  18769. #endif
  18770. sizeof(opt));
  18771. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18772. ::listen(srv, 1) != 0) {
  18773. port_promise.set_value(-1);
  18774. detail::close_socket(srv);
  18775. return;
  18776. }
  18777. socklen_t addr_len = sizeof(addr);
  18778. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18779. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18780. sockaddr_in cli_addr{};
  18781. socklen_t cli_len = sizeof(cli_addr);
  18782. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18783. if (cli != INVALID_SOCKET) {
  18784. // Read the complete HTTP request (until the blank line that terminates
  18785. // headers) before sending the response. If the server closes the socket
  18786. // while the client's request data is still unread in the kernel receive
  18787. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18788. // connection on both sides: it discards the client's receive buffer
  18789. // (which already holds our response) and causes any in-progress write on
  18790. // the client to fail with ECONNRESET. Reading all request data first
  18791. // ensures close() emits a graceful FIN.
  18792. {
  18793. char rbuf[256];
  18794. std::string req;
  18795. while (req.find("\r\n\r\n") == std::string::npos) {
  18796. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18797. if (n <= 0) { break; }
  18798. req.append(rbuf, static_cast<size_t>(n));
  18799. }
  18800. }
  18801. ::send(cli,
  18802. #ifdef _WIN32
  18803. static_cast<const char *>(response.c_str()),
  18804. static_cast<int>(response.size()),
  18805. #else
  18806. response.c_str(), response.size(),
  18807. #endif
  18808. 0);
  18809. if (after_send) { after_send(cli); }
  18810. detail::close_socket(cli);
  18811. }
  18812. detail::close_socket(srv);
  18813. });
  18814. }
  18815. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18816. #ifndef _WIN32
  18817. signal(SIGPIPE, SIG_IGN);
  18818. #endif
  18819. std::promise<int> port_promise;
  18820. auto port_future = port_promise.get_future();
  18821. auto server_thread =
  18822. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18823. "Content-Type: text/plain\r\n"
  18824. "Content-Length: not-a-number\r\n"
  18825. "Connection: close\r\n"
  18826. "\r\n"
  18827. "hello");
  18828. auto port = port_future.get();
  18829. ASSERT_GT(port, 0);
  18830. Client cli("127.0.0.1", port);
  18831. auto handle = cli.open_stream("GET", "/");
  18832. EXPECT_FALSE(handle.is_valid());
  18833. server_thread.join();
  18834. }
  18835. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18836. #ifndef _WIN32
  18837. signal(SIGPIPE, SIG_IGN);
  18838. #endif
  18839. std::promise<int> port_promise;
  18840. auto port_future = port_promise.get_future();
  18841. auto server_thread = serve_single_response(
  18842. port_promise, "HTTP/1.1 200 OK\r\n"
  18843. "Content-Type: text/plain\r\n"
  18844. "Content-Length: 99999999999999999999999999\r\n"
  18845. "Connection: close\r\n"
  18846. "\r\n"
  18847. "hello");
  18848. auto port = port_future.get();
  18849. ASSERT_GT(port, 0);
  18850. // Historically std::stoull would throw std::out_of_range here and crash
  18851. // the process, then parsing silently clamped to a bogus framing length and
  18852. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18853. // so the stream fails to open, matching the not-a-number case above. The
  18854. // process still must NOT terminate.
  18855. Client cli("127.0.0.1", port);
  18856. auto handle = cli.open_stream("GET", "/");
  18857. EXPECT_FALSE(handle.is_valid());
  18858. server_thread.join();
  18859. }
  18860. // Serves `response` to the single request `fn` makes with a fresh client.
  18861. template <typename Fn>
  18862. static void with_single_response(const std::string &response, Fn fn) {
  18863. #ifndef _WIN32
  18864. signal(SIGPIPE, SIG_IGN);
  18865. #endif
  18866. std::promise<int> port_promise;
  18867. auto port_future = port_promise.get_future();
  18868. auto server_thread = serve_single_response(port_promise, response);
  18869. auto se = detail::scope_exit([&] { server_thread.join(); });
  18870. auto port = port_future.get();
  18871. ASSERT_GT(port, 0);
  18872. Client cli("127.0.0.1", port);
  18873. fn(cli);
  18874. }
  18875. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  18876. const char *responses[] = {
  18877. "HTTP/1.1 103 Early Hints\r\n"
  18878. "Link: </style.css>; rel=preload\r\n"
  18879. "\r\n"
  18880. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18881. "HTTP/1.1 100 Continue\r\n"
  18882. "X-Note: interim\r\n"
  18883. "\r\n"
  18884. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18885. };
  18886. for (auto response : responses) {
  18887. with_single_response(response, [](Client &cli) {
  18888. auto res = cli.Get("/");
  18889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18890. EXPECT_EQ(StatusCode::OK_200, res->status);
  18891. EXPECT_EQ("ok", res->body);
  18892. });
  18893. }
  18894. }
  18895. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  18896. #ifndef _WIN32
  18897. signal(SIGPIPE, SIG_IGN);
  18898. #endif
  18899. // The server answers the head without asking for the body. Bytes it then
  18900. // reads on the connection would be taken for the body the request declared.
  18901. auto closed_by_client = false;
  18902. std::promise<int> port_promise;
  18903. auto server_thread = serve_single_response(
  18904. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  18905. [&](socket_t sock) {
  18906. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  18907. char buf[256];
  18908. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  18909. });
  18910. Client cli("127.0.0.1", port_promise.get_future().get());
  18911. cli.set_keep_alive(true);
  18912. cli.set_read_timeout(1, 0);
  18913. // Long enough for the client to send Expect: 100-continue.
  18914. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18916. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  18917. cli.Get("/second");
  18918. server_thread.join();
  18919. EXPECT_TRUE(closed_by_client);
  18920. }
  18921. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  18922. // Long enough for the client to send Expect: 100-continue
  18923. with_single_response(
  18924. "HTTP/1.1 103 Early Hints\r\n"
  18925. "Link: </style.css>; rel=preload\r\n"
  18926. "\r\n"
  18927. "HTTP/1.1 401 Unauthorized\r\n"
  18928. "Content-Length: 0\r\n\r\n",
  18929. [](Client &cli) {
  18930. cli.set_read_timeout(2, 0);
  18931. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18933. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  18934. });
  18935. }
  18936. #ifdef CPPHTTPLIB_SSL_ENABLED
  18937. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  18938. #ifndef _WIN32
  18939. signal(SIGPIPE, SIG_IGN);
  18940. #endif
  18941. auto reused = false;
  18942. std::promise<int> port_promise;
  18943. auto server_thread = serve_single_response(
  18944. port_promise,
  18945. "HTTP/1.1 401 Unauthorized\r\n"
  18946. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  18947. "Content-Length: 0\r\n\r\n",
  18948. [&](socket_t sock) {
  18949. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  18950. char buf[256];
  18951. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  18952. });
  18953. Client cli("127.0.0.1", port_promise.get_future().get());
  18954. cli.set_keep_alive(true);
  18955. cli.set_digest_auth("user", "pass");
  18956. cli.set_read_timeout(1, 0);
  18957. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18958. server_thread.join();
  18959. EXPECT_FALSE(reused);
  18960. }
  18961. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  18962. // Any other answer to CONNECT would read as the origin's response.
  18963. struct {
  18964. const char *response;
  18965. bool passed_on;
  18966. } cases[] = {
  18967. {"HTTP/1.1 201 Created\r\n"
  18968. "Set-Cookie: session=from-proxy\r\n"
  18969. "Content-Length: 0\r\n\r\n",
  18970. false},
  18971. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  18972. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  18973. "Content-Length: 0\r\n\r\n",
  18974. true},
  18975. };
  18976. for (const auto &c : cases) {
  18977. std::promise<int> port_promise;
  18978. auto server_thread = serve_single_response(port_promise, c.response);
  18979. SSLClient cli("example.com", 443);
  18980. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  18981. auto res = cli.Get("/");
  18982. server_thread.join();
  18983. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  18984. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  18985. if (res) {
  18986. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18987. }
  18988. }
  18989. }
  18990. #endif
  18991. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18992. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18993. // the chunked coding and drop Content-Length, so a front-end that trusts
  18994. // Content-Length would disagree about where the body ends (response
  18995. // smuggling). The client must reject such a response.
  18996. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18997. for (const char *te : {"chunked", "gzip, chunked"}) {
  18998. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18999. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19000. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19001. "5\r\nhello\r\n0\r\n\r\n";
  19002. with_single_response(response, [&](Client &cli) {
  19003. auto res = cli.Get("/");
  19004. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19005. EXPECT_EQ(Error::Read, res.error()) << te;
  19006. });
  19007. with_single_response(response, [&](Client &cli) {
  19008. auto handle = cli.open_stream("GET", "/");
  19009. EXPECT_FALSE(handle.is_valid()) << te;
  19010. EXPECT_EQ(Error::Read, handle.error) << te;
  19011. });
  19012. }
  19013. }
  19014. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19015. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19016. // closing the connection (unlike a request, which must be rejected).
  19017. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19018. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19019. "Transfer-Encoding: chunked\r\n"
  19020. "Connection: close\r\n"
  19021. "\r\n"
  19022. "5\r\nhello\r\n0\r\n\r\n",
  19023. "HTTP/1.1 200 OK\r\n"
  19024. "Transfer-Encoding: gzip\r\n"
  19025. "Connection: close\r\n"
  19026. "\r\n"
  19027. "hello"}) {
  19028. with_single_response(response, [&](Client &cli) {
  19029. auto res = cli.Get("/");
  19030. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19031. EXPECT_EQ("hello", res->body);
  19032. });
  19033. with_single_response(response, [&](Client &cli) {
  19034. auto handle = cli.open_stream("GET", "/");
  19035. ASSERT_TRUE(handle.is_valid()) << response;
  19036. EXPECT_EQ("hello", read_all(handle));
  19037. });
  19038. }
  19039. }
  19040. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19041. // framing headers describe nothing to read and must not be rejected.
  19042. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19043. const std::string framing = "Content-Length: 5\r\n"
  19044. "Transfer-Encoding: chunked\r\n"
  19045. "Connection: close\r\n"
  19046. "\r\n";
  19047. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19048. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19049. });
  19050. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19051. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19052. });
  19053. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19054. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19055. with_single_response(response, [&](Client &cli) {
  19056. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19057. });
  19058. with_single_response(response, [&](Client &cli) {
  19059. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19060. });
  19061. }
  19062. }
  19063. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19064. // response, is faulty framing, so the connection is not reused after it.
  19065. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19066. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19067. "Content-Length: 0\r\n"
  19068. "Transfer-Encoding: chunked\r\n"
  19069. "\r\n"
  19070. "5\r\nhello\r\n0\r\n\r\n",
  19071. "HTTP/1.0 200 Connection established\r\n"
  19072. "Connection: keep-alive\r\n"
  19073. "Transfer-Encoding: chunked\r\n"
  19074. "\r\n"
  19075. "5\r\nhello\r\n0\r\n\r\n"}) {
  19076. with_single_response(response, [&](Client &cli) {
  19077. cli.set_keep_alive(true);
  19078. auto res = cli.Get("/");
  19079. ASSERT_TRUE(res) << response;
  19080. EXPECT_EQ("hello", res->body);
  19081. EXPECT_FALSE(cli.is_socket_open()) << response;
  19082. });
  19083. }
  19084. }
  19085. // A payload max length of 0 means no limit, however the body is framed.
  19086. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19087. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19088. "Transfer-Encoding: chunked\r\n"
  19089. "\r\n"
  19090. "5\r\nhello\r\n0\r\n\r\n",
  19091. "HTTP/1.1 200 OK\r\n"
  19092. "Connection: close\r\n"
  19093. "\r\n"
  19094. "hello"}) {
  19095. with_single_response(response, [&](Client &cli) {
  19096. cli.set_payload_max_length(0);
  19097. auto res = cli.Get("/");
  19098. ASSERT_TRUE(res) << response;
  19099. EXPECT_EQ("hello", res->body) << response;
  19100. });
  19101. }
  19102. }
  19103. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19104. Server svr;
  19105. svr.set_payload_max_length(0);
  19106. svr.Post("/echo", [](const Request &req, Response &res) {
  19107. res.set_content(req.body, "text/plain");
  19108. });
  19109. auto port = svr.bind_to_any_port(HOST);
  19110. thread t = thread([&] { svr.listen_after_bind(); });
  19111. auto se = detail::scope_exit([&] {
  19112. svr.stop();
  19113. t.join();
  19114. ASSERT_FALSE(svr.is_running());
  19115. });
  19116. svr.wait_until_ready();
  19117. Client cli(HOST, port);
  19118. auto res = cli.Post(
  19119. "/echo",
  19120. [](size_t /*offset*/, DataSink &sink) {
  19121. sink.write("hello", 5);
  19122. sink.done();
  19123. return true;
  19124. },
  19125. "text/plain");
  19126. ASSERT_TRUE(res);
  19127. EXPECT_EQ(StatusCode::OK_200, res->status);
  19128. EXPECT_EQ("hello", res->body);
  19129. }
  19130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19131. TEST_F(OpenStreamTest, Gzip) {
  19132. Client cli("127.0.0.1", port_);
  19133. auto handle = cli.open_stream("GET", "/compressible", {},
  19134. {{"Accept-Encoding", "gzip"}});
  19135. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19136. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19137. }
  19138. #endif
  19139. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19140. TEST_F(OpenStreamTest, Brotli) {
  19141. Client cli("127.0.0.1", port_);
  19142. auto handle =
  19143. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19144. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19145. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19146. }
  19147. #endif
  19148. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19149. TEST_F(OpenStreamTest, Zstd) {
  19150. Client cli("127.0.0.1", port_);
  19151. auto handle = cli.open_stream("GET", "/compressible", {},
  19152. {{"Accept-Encoding", "zstd"}});
  19153. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19154. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19155. }
  19156. #endif
  19157. #ifdef CPPHTTPLIB_SSL_ENABLED
  19158. class SSLOpenStreamTest : public ::testing::Test {
  19159. protected:
  19160. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19161. void SetUp() override {
  19162. svr_.Get("/hello", [](const Request &, Response &res) {
  19163. res.set_content("Hello SSL World!", "text/plain");
  19164. });
  19165. svr_.Get("/chunked", [](const Request &, Response &res) {
  19166. res.set_chunked_content_provider("text/plain",
  19167. [](size_t offset, DataSink &sink) {
  19168. if (offset < 15) {
  19169. sink.write("chunk", 5);
  19170. return true;
  19171. }
  19172. sink.done();
  19173. return true;
  19174. });
  19175. });
  19176. svr_.Post("/echo", [](const Request &req, Response &res) {
  19177. res.set_content(req.body, req.get_header_value("Content-Type"));
  19178. });
  19179. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19180. std::string body = req.body;
  19181. res.set_chunked_content_provider(
  19182. "text/plain", [body](size_t offset, DataSink &sink) {
  19183. if (offset < body.size()) {
  19184. sink.write(body.data() + offset, body.size() - offset);
  19185. }
  19186. sink.done();
  19187. return true;
  19188. });
  19189. });
  19190. port_ = svr_.bind_to_any_port("127.0.0.1");
  19191. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19192. svr_.wait_until_ready();
  19193. }
  19194. void TearDown() override {
  19195. svr_.stop();
  19196. if (thread_.joinable()) thread_.join();
  19197. }
  19198. SSLServer svr_;
  19199. std::thread thread_;
  19200. int port_ = 0;
  19201. };
  19202. TEST_F(SSLOpenStreamTest, Basic) {
  19203. SSLClient cli("127.0.0.1", port_);
  19204. cli.enable_server_certificate_verification(false);
  19205. auto handle = cli.open_stream("GET", "/hello");
  19206. ASSERT_TRUE(handle.is_valid());
  19207. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19208. }
  19209. TEST_F(SSLOpenStreamTest, Chunked) {
  19210. SSLClient cli("127.0.0.1", port_);
  19211. cli.enable_server_certificate_verification(false);
  19212. auto handle = cli.open_stream("GET", "/chunked");
  19213. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19214. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19215. "Transfer-Encoding") == "chunked");
  19216. auto body = read_all(handle);
  19217. EXPECT_EQ("chunkchunkchunk", body);
  19218. }
  19219. TEST_F(SSLOpenStreamTest, Post) {
  19220. SSLClient cli("127.0.0.1", port_);
  19221. cli.enable_server_certificate_verification(false);
  19222. auto handle =
  19223. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19224. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19225. EXPECT_EQ(200, handle.response->status);
  19226. auto body = read_all(handle);
  19227. EXPECT_EQ("Hello SSL POST", body);
  19228. }
  19229. TEST_F(SSLOpenStreamTest, PostChunked) {
  19230. SSLClient cli("127.0.0.1", port_);
  19231. cli.enable_server_certificate_verification(false);
  19232. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19233. "Chunked SSL Data", "text/plain");
  19234. ASSERT_TRUE(handle.is_valid());
  19235. EXPECT_EQ(200, handle.response->status);
  19236. auto body = read_all(handle);
  19237. EXPECT_EQ("Chunked SSL Data", body);
  19238. }
  19239. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19240. // Content-Length is terminated by the server closing the connection. When the
  19241. // SSL peer sends a close_notify after the body, the client must treat it as a
  19242. // clean EOF and return a successful response rather than an error.
  19243. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19244. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19245. ASSERT_TRUE(svr.is_valid());
  19246. svr.set_keep_alive_max_count(1);
  19247. const std::string expected_body = "Hello from connection-close response!";
  19248. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19249. res.set_content_provider("text/plain",
  19250. [&](size_t offset, DataSink &sink) -> bool {
  19251. if (offset < expected_body.size()) {
  19252. sink.write(expected_body.data() + offset,
  19253. expected_body.size() - offset);
  19254. }
  19255. sink.done();
  19256. return true;
  19257. });
  19258. });
  19259. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19260. auto se = detail::scope_exit([&] {
  19261. svr.stop();
  19262. listen_thread.join();
  19263. ASSERT_FALSE(svr.is_running());
  19264. });
  19265. svr.wait_until_ready();
  19266. SSLClient cli(HOST, PORT);
  19267. cli.enable_server_certificate_verification(false);
  19268. auto res = cli.Get("/no-content-length");
  19269. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19270. EXPECT_EQ(StatusCode::OK_200, res->status);
  19271. EXPECT_EQ(expected_body, res->body);
  19272. }
  19273. #endif // CPPHTTPLIB_SSL_ENABLED
  19274. //==============================================================================
  19275. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19276. // results for various scenarios.
  19277. //==============================================================================
  19278. TEST(ParityTest, GetVsOpenStream) {
  19279. Server svr;
  19280. const std::string path = "/parity";
  19281. const std::string content = "Parity test content: hello world";
  19282. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19283. res.set_content(content, "text/plain");
  19284. });
  19285. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19286. auto se = detail::scope_exit([&] {
  19287. svr.stop();
  19288. t.join();
  19289. ASSERT_FALSE(svr.is_running());
  19290. });
  19291. svr.wait_until_ready();
  19292. Client cli(HOST, PORT);
  19293. // Non-stream path
  19294. auto r1 = cli.Get(path);
  19295. ASSERT_TRUE(r1);
  19296. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19297. // Stream path
  19298. auto h = cli.open_stream("GET", path);
  19299. ASSERT_TRUE(h.is_valid());
  19300. EXPECT_EQ(r1->body, read_all(h));
  19301. }
  19302. // Helper to compress data with provided compressor type T
  19303. template <typename Compressor>
  19304. static std::string compress_payload_for_parity(const std::string &in) {
  19305. std::string out;
  19306. Compressor compressor;
  19307. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19308. [&](const char *data, size_t n) {
  19309. out.append(data, n);
  19310. return true;
  19311. });
  19312. EXPECT_TRUE(ok);
  19313. return out;
  19314. }
  19315. // Helper function for compression parity tests
  19316. template <typename Compressor>
  19317. static void test_compression_parity(const std::string &original,
  19318. const std::string &path,
  19319. const std::string &encoding) {
  19320. const std::string compressed =
  19321. compress_payload_for_parity<Compressor>(original);
  19322. Server svr;
  19323. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19324. res.set_content(compressed, "application/octet-stream");
  19325. res.set_header("Content-Encoding", encoding);
  19326. });
  19327. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19328. auto se = detail::scope_exit([&] {
  19329. svr.stop();
  19330. t.join();
  19331. ASSERT_FALSE(svr.is_running());
  19332. });
  19333. svr.wait_until_ready();
  19334. Client cli(HOST, PORT);
  19335. // Non-streaming
  19336. {
  19337. auto res = cli.Get(path);
  19338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19339. EXPECT_EQ(StatusCode::OK_200, res->status);
  19340. EXPECT_EQ(original, res->body);
  19341. }
  19342. // Streaming
  19343. {
  19344. auto h = cli.open_stream("GET", path);
  19345. ASSERT_TRUE(h.is_valid());
  19346. EXPECT_EQ(original, read_all(h));
  19347. }
  19348. }
  19349. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19350. TEST(ParityTest, Gzip) {
  19351. test_compression_parity<detail::gzip_compressor>(
  19352. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19353. }
  19354. #endif
  19355. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19356. TEST(ParityTest, Brotli) {
  19357. test_compression_parity<detail::brotli_compressor>(
  19358. "Hello, brotli parity test payload", "/parity-br", "br");
  19359. }
  19360. #endif
  19361. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19362. TEST(ParityTest, Zstd) {
  19363. test_compression_parity<detail::zstd_compressor>(
  19364. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19365. }
  19366. #endif
  19367. //==============================================================================
  19368. // New Stream API Tests
  19369. //==============================================================================
  19370. inline std::string read_body(httplib::stream::Result &result) {
  19371. std::string body;
  19372. while (result.next()) {
  19373. body.append(result.data(), result.size());
  19374. }
  19375. return body;
  19376. }
  19377. TEST(ClientConnectionTest, Basic) {
  19378. httplib::ClientConnection conn;
  19379. EXPECT_FALSE(conn.is_open());
  19380. conn.sock = 1;
  19381. EXPECT_TRUE(conn.is_open());
  19382. httplib::ClientConnection conn2(std::move(conn));
  19383. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19384. conn2.sock = INVALID_SOCKET;
  19385. }
  19386. // Unified test server for all stream::* tests
  19387. class StreamApiTest : public ::testing::Test {
  19388. protected:
  19389. void SetUp() override {
  19390. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19391. res.set_content("Hello World!", "text/plain");
  19392. });
  19393. svr_.Get("/echo-params",
  19394. [](const httplib::Request &req, httplib::Response &res) {
  19395. std::string r;
  19396. for (const auto &p : req.params) {
  19397. if (!r.empty()) r += "&";
  19398. r += p.first + "=" + p.second;
  19399. }
  19400. res.set_content(r, "text/plain");
  19401. });
  19402. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19403. res.set_content(req.body, req.get_header_value("Content-Type"));
  19404. });
  19405. svr_.Post("/echo-headers",
  19406. [](const httplib::Request &req, httplib::Response &res) {
  19407. std::string r;
  19408. for (const auto &h : req.headers)
  19409. r += h.first + ": " + h.second + "\n";
  19410. res.set_content(r, "text/plain");
  19411. });
  19412. svr_.Post("/echo-params",
  19413. [](const httplib::Request &req, httplib::Response &res) {
  19414. std::string r = "params:";
  19415. for (const auto &p : req.params)
  19416. r += p.first + "=" + p.second + ";";
  19417. res.set_content(r + " body:" + req.body, "text/plain");
  19418. });
  19419. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19420. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19421. });
  19422. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19423. res.set_content("PUT:" + req.body, "text/plain");
  19424. });
  19425. svr_.Patch("/echo",
  19426. [](const httplib::Request &req, httplib::Response &res) {
  19427. res.set_content("PATCH:" + req.body, "text/plain");
  19428. });
  19429. svr_.Delete(
  19430. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19431. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19432. "text/plain");
  19433. });
  19434. svr_.Get("/head-test",
  19435. [](const httplib::Request &, httplib::Response &res) {
  19436. res.set_content("body for HEAD", "text/plain");
  19437. });
  19438. svr_.Options("/options",
  19439. [](const httplib::Request &, httplib::Response &res) {
  19440. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19441. });
  19442. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19443. svr_.wait_until_ready();
  19444. }
  19445. void TearDown() override {
  19446. svr_.stop();
  19447. if (thread_.joinable()) thread_.join();
  19448. }
  19449. httplib::Server svr_;
  19450. std::thread thread_;
  19451. };
  19452. // stream::Get tests
  19453. TEST_F(StreamApiTest, GetBasic) {
  19454. httplib::Client cli(HOST, PORT);
  19455. auto result = httplib::stream::Get(cli, "/hello");
  19456. ASSERT_TRUE(result.is_valid());
  19457. EXPECT_EQ(200, result.status());
  19458. EXPECT_EQ("Hello World!", read_body(result));
  19459. }
  19460. TEST_F(StreamApiTest, GetWithParams) {
  19461. httplib::Client cli(HOST, PORT);
  19462. httplib::Params params{{"foo", "bar"}};
  19463. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19464. ASSERT_TRUE(result.is_valid());
  19465. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19466. }
  19467. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19468. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19469. httplib::Client cli(HOST, PORT);
  19470. cli.set_payload_max_length(0);
  19471. auto result = httplib::stream::Get(cli, "/hello");
  19472. ASSERT_TRUE(result.is_valid());
  19473. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19474. EXPECT_EQ("Hello World!", read_body(result));
  19475. }
  19476. #endif
  19477. TEST_F(StreamApiTest, GetConnectionError) {
  19478. httplib::Client cli(HOST, 9999);
  19479. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19480. }
  19481. TEST_F(StreamApiTest, Get404) {
  19482. httplib::Client cli(HOST, PORT);
  19483. auto result = httplib::stream::Get(cli, "/nonexistent");
  19484. EXPECT_TRUE(result.is_valid());
  19485. EXPECT_EQ(404, result.status());
  19486. }
  19487. // stream::Post tests
  19488. TEST_F(StreamApiTest, PostBasic) {
  19489. httplib::Client cli(HOST, PORT);
  19490. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19491. "application/json");
  19492. ASSERT_TRUE(result.is_valid());
  19493. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19494. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19495. }
  19496. TEST_F(StreamApiTest, PostWithHeaders) {
  19497. httplib::Client cli(HOST, PORT);
  19498. httplib::Headers headers{{"X-Custom", "value"}};
  19499. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19500. "text/plain");
  19501. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19502. }
  19503. TEST_F(StreamApiTest, PostWithParams) {
  19504. httplib::Client cli(HOST, PORT);
  19505. httplib::Params params{{"k", "v"}};
  19506. auto result =
  19507. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19508. auto body = read_body(result);
  19509. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19510. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19511. }
  19512. TEST_F(StreamApiTest, PostLarge) {
  19513. httplib::Client cli(HOST, PORT);
  19514. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19515. size_t total = 0;
  19516. while (result.next()) {
  19517. total += result.size();
  19518. }
  19519. EXPECT_EQ(100u * 1024u, total);
  19520. }
  19521. // stream::Put/Patch tests
  19522. TEST_F(StreamApiTest, PutAndPatch) {
  19523. httplib::Client cli(HOST, PORT);
  19524. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19525. EXPECT_EQ("PUT:test", read_body(put));
  19526. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19527. EXPECT_EQ("PATCH:test", read_body(patch));
  19528. }
  19529. // stream::Delete tests
  19530. TEST_F(StreamApiTest, Delete) {
  19531. httplib::Client cli(HOST, PORT);
  19532. auto del1 = httplib::stream::Delete(cli, "/resource");
  19533. EXPECT_EQ("Deleted", read_body(del1));
  19534. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19535. EXPECT_EQ("Deleted:data", read_body(del2));
  19536. }
  19537. // stream::Head/Options tests
  19538. TEST_F(StreamApiTest, HeadAndOptions) {
  19539. httplib::Client cli(HOST, PORT);
  19540. auto head = httplib::stream::Head(cli, "/head-test");
  19541. EXPECT_TRUE(head.is_valid());
  19542. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19543. auto opts = httplib::stream::Options(cli, "/options");
  19544. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19545. }
  19546. // SSL stream::* tests
  19547. #ifdef CPPHTTPLIB_SSL_ENABLED
  19548. class SSLStreamApiTest : public ::testing::Test {
  19549. protected:
  19550. void SetUp() override {
  19551. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19552. res.set_content("Hello SSL!", "text/plain");
  19553. });
  19554. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19555. res.set_content(req.body, "text/plain");
  19556. });
  19557. port_ = svr_.bind_to_any_port("127.0.0.1");
  19558. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19559. svr_.wait_until_ready();
  19560. }
  19561. void TearDown() override {
  19562. svr_.stop();
  19563. if (thread_.joinable()) thread_.join();
  19564. }
  19565. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19566. std::thread thread_;
  19567. int port_ = 0;
  19568. };
  19569. TEST_F(SSLStreamApiTest, GetAndPost) {
  19570. httplib::SSLClient cli("127.0.0.1", port_);
  19571. cli.enable_server_certificate_verification(false);
  19572. auto get = httplib::stream::Get(cli, "/hello");
  19573. EXPECT_EQ("Hello SSL!", read_body(get));
  19574. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19575. EXPECT_EQ("test", read_body(post));
  19576. }
  19577. #endif
  19578. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19579. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19580. // BodyReader
  19581. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19582. // Test that read timeout during streaming is detected
  19583. // Use a large content-length response where server delays mid-stream
  19584. Server svr;
  19585. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19586. // Send a large response with delay in the middle
  19587. res.set_content_provider(
  19588. 1000, // content_length
  19589. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19590. if (offset < 100) {
  19591. // Send first 100 bytes immediately
  19592. std::string data(100, 'A');
  19593. sink.write(data.c_str(), data.size());
  19594. return true;
  19595. }
  19596. // Then delay longer than client timeout
  19597. std::this_thread::sleep_for(std::chrono::seconds(3));
  19598. std::string data(900, 'B');
  19599. sink.write(data.c_str(), data.size());
  19600. return true;
  19601. });
  19602. });
  19603. auto port = 8091;
  19604. std::thread t([&]() { svr.listen("localhost", port); });
  19605. svr.wait_until_ready();
  19606. Client cli("localhost", port);
  19607. cli.set_read_timeout(1, 0); // 1 second timeout
  19608. auto handle = cli.open_stream("GET", "/slow-stream");
  19609. ASSERT_TRUE(handle.is_valid());
  19610. char buf[256];
  19611. ssize_t total = 0;
  19612. ssize_t n;
  19613. bool got_error = false;
  19614. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19615. total += n;
  19616. }
  19617. if (n < 0) {
  19618. got_error = true;
  19619. // Should be timeout or read error
  19620. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19621. handle.get_read_error() == Error::Read)
  19622. << "Actual error: " << to_string(handle.get_read_error());
  19623. }
  19624. // Either we got an error, or we got less data than expected
  19625. EXPECT_TRUE(got_error || total < 1000)
  19626. << "Expected timeout but got all " << total << " bytes";
  19627. svr.stop();
  19628. t.join();
  19629. }
  19630. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19631. // Test connection closed detection via BodyReader
  19632. Server svr;
  19633. std::atomic<bool> close_now{false};
  19634. svr.Get("/will-close", [&](const Request &, Response &res) {
  19635. res.set_content_provider(
  19636. 10000, // Large content_length that we won't fully send
  19637. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19638. if (offset < 100) {
  19639. std::string data(100, 'X');
  19640. sink.write(data.c_str(), data.size());
  19641. return true;
  19642. }
  19643. // Wait for signal then abort
  19644. while (!close_now) {
  19645. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19646. }
  19647. return false; // Abort - server will close connection
  19648. });
  19649. });
  19650. auto port = 8092;
  19651. std::thread t([&]() { svr.listen("localhost", port); });
  19652. svr.wait_until_ready();
  19653. Client cli("localhost", port);
  19654. auto handle = cli.open_stream("GET", "/will-close");
  19655. ASSERT_TRUE(handle.is_valid());
  19656. char buf[256];
  19657. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19658. EXPECT_GT(n, 0) << "First read should succeed";
  19659. // Signal server to close
  19660. close_now = true;
  19661. // Keep reading until error or EOF
  19662. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19663. // Keep reading
  19664. }
  19665. // Should get an error since content_length wasn't satisfied
  19666. if (n < 0) {
  19667. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19668. handle.get_read_error() == Error::Read)
  19669. << "Actual error: " << to_string(handle.get_read_error());
  19670. }
  19671. svr.stop();
  19672. t.join();
  19673. }
  19674. #ifdef CPPHTTPLIB_SSL_ENABLED
  19675. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19676. // Test that read timeout during SSL streaming is detected
  19677. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19678. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19679. res.set_content_provider(
  19680. 1000, "text/plain",
  19681. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19682. if (offset < 100) {
  19683. std::string data(100, 'A');
  19684. sink.write(data.c_str(), data.size());
  19685. return true;
  19686. }
  19687. std::this_thread::sleep_for(std::chrono::seconds(3));
  19688. std::string data(900, 'B');
  19689. sink.write(data.c_str(), data.size());
  19690. return true;
  19691. });
  19692. });
  19693. auto port = 8093;
  19694. std::thread t([&]() { svr.listen("localhost", port); });
  19695. svr.wait_until_ready();
  19696. SSLClient cli("localhost", port);
  19697. cli.enable_server_certificate_verification(false);
  19698. cli.set_read_timeout(1, 0); // 1 second timeout
  19699. auto handle = cli.open_stream("GET", "/slow-stream");
  19700. ASSERT_TRUE(handle.is_valid());
  19701. char buf[256];
  19702. ssize_t total = 0;
  19703. ssize_t n;
  19704. bool got_error = false;
  19705. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19706. total += n;
  19707. }
  19708. if (n < 0) {
  19709. got_error = true;
  19710. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19711. handle.get_read_error() == Error::Read)
  19712. << "Actual error: " << to_string(handle.get_read_error());
  19713. }
  19714. EXPECT_TRUE(got_error || total < 1000)
  19715. << "Expected timeout but got all " << total << " bytes";
  19716. svr.stop();
  19717. t.join();
  19718. }
  19719. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19720. // Test SSL connection closed detection
  19721. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19722. std::atomic<bool> close_now{false};
  19723. svr.Get("/will-close", [&](const Request &, Response &res) {
  19724. res.set_content_provider(
  19725. 10000, "text/plain",
  19726. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19727. if (offset < 100) {
  19728. std::string data(100, 'X');
  19729. sink.write(data.c_str(), data.size());
  19730. return true;
  19731. }
  19732. while (!close_now) {
  19733. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19734. }
  19735. return false;
  19736. });
  19737. });
  19738. auto port = 8094;
  19739. std::thread t([&]() { svr.listen("localhost", port); });
  19740. svr.wait_until_ready();
  19741. SSLClient cli("localhost", port);
  19742. cli.enable_server_certificate_verification(false);
  19743. auto handle = cli.open_stream("GET", "/will-close");
  19744. ASSERT_TRUE(handle.is_valid());
  19745. char buf[256];
  19746. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19747. EXPECT_GT(n, 0);
  19748. // Signal server to close
  19749. close_now = true;
  19750. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19751. // Keep reading
  19752. }
  19753. if (n < 0) {
  19754. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19755. handle.get_read_error() == Error::Read)
  19756. << "Actual error: " << to_string(handle.get_read_error());
  19757. }
  19758. svr.stop();
  19759. t.join();
  19760. }
  19761. #endif
  19762. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19763. using namespace httplib;
  19764. // Create a test file
  19765. const char *fname = "etag_testfile.txt";
  19766. const char *content = "etag-content";
  19767. {
  19768. std::ofstream ofs(fname);
  19769. ofs << content;
  19770. ASSERT_TRUE(ofs.good());
  19771. }
  19772. Server svr;
  19773. svr.set_mount_point("/static", ".");
  19774. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19775. svr.wait_until_ready();
  19776. Client cli(HOST, PORT);
  19777. // First request: should get 200 with ETag header
  19778. auto res1 = cli.Get("/static/etag_testfile.txt");
  19779. ASSERT_TRUE(res1);
  19780. ASSERT_EQ(200, res1->status);
  19781. ASSERT_TRUE(res1->has_header("ETag"));
  19782. std::string etag = res1->get_header_value("ETag");
  19783. EXPECT_FALSE(etag.empty());
  19784. // Verify ETag format: W/"hex-hex"
  19785. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19786. EXPECT_EQ('W', etag[0]);
  19787. EXPECT_EQ('/', etag[1]);
  19788. EXPECT_EQ('"', etag[2]);
  19789. EXPECT_EQ('"', etag.back());
  19790. // Exact match: expect 304 Not Modified
  19791. Headers h2 = {{"If-None-Match", etag}};
  19792. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19793. ASSERT_TRUE(res2);
  19794. EXPECT_EQ(304, res2->status);
  19795. // Wildcard match: expect 304 Not Modified
  19796. Headers h3 = {{"If-None-Match", "*"}};
  19797. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19798. ASSERT_TRUE(res3);
  19799. EXPECT_EQ(304, res3->status);
  19800. // Non-matching ETag: expect 200
  19801. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19802. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19803. ASSERT_TRUE(res4);
  19804. EXPECT_EQ(200, res4->status);
  19805. // Multiple ETags with one matching: expect 304
  19806. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19807. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19808. ASSERT_TRUE(res5);
  19809. EXPECT_EQ(304, res5->status);
  19810. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19811. // that equivalent to the single comma-separated list above, so the match on
  19812. // the second line must still be found.
  19813. Headers h6;
  19814. h6.emplace("If-None-Match", "W/\"other\"");
  19815. h6.emplace("If-None-Match", etag);
  19816. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19817. ASSERT_TRUE(res6);
  19818. EXPECT_EQ(304, res6->status);
  19819. svr.stop();
  19820. t.join();
  19821. std::remove(fname);
  19822. }
  19823. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19824. using namespace httplib;
  19825. Server svr;
  19826. svr.set_mount_point("/static", ".");
  19827. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19828. svr.wait_until_ready();
  19829. Client cli(HOST, PORT);
  19830. // Send If-None-Match: * to a non-existent file
  19831. Headers h = {{"If-None-Match", "*"}};
  19832. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19834. EXPECT_EQ(404, res->status);
  19835. svr.stop();
  19836. t.join();
  19837. }
  19838. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19839. using namespace httplib;
  19840. // Create a test file
  19841. const char *fname = "etag_boundary_testfile.txt";
  19842. const char *content = "boundary-test";
  19843. {
  19844. std::ofstream ofs(fname);
  19845. ofs << content;
  19846. ASSERT_TRUE(ofs.good());
  19847. }
  19848. Server svr;
  19849. svr.set_mount_point("/static", ".");
  19850. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19851. svr.wait_until_ready();
  19852. Client cli(HOST, PORT);
  19853. // Get the actual ETag
  19854. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19855. ASSERT_TRUE(res1);
  19856. ASSERT_EQ(200, res1->status);
  19857. ASSERT_TRUE(res1->has_header("ETag"));
  19858. std::string etag = res1->get_header_value("ETag");
  19859. // Test 1: Very long ETag value (longer than actual ETag)
  19860. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19861. Headers h1 = {{"If-None-Match", "W/"
  19862. "\"very-long-etag-value-that-is-much-longer-"
  19863. "than-the-actual-etag-value\""}};
  19864. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19865. ASSERT_TRUE(res2);
  19866. EXPECT_EQ(200, res2->status); // Should not match
  19867. // Test 2: Long string followed by wildcard
  19868. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19869. // string)
  19870. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19871. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19872. ASSERT_TRUE(res3);
  19873. EXPECT_EQ(304, res3->status); // Should match on "*"
  19874. // Test 3: Wildcard followed by long string
  19875. // Should match on "*" immediately and return 304
  19876. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19877. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19878. ASSERT_TRUE(res4);
  19879. EXPECT_EQ(304, res4->status); // Should match on "*"
  19880. // Test 4: Multiple long non-matching values
  19881. // Should NOT match and return 200 (test that all comparisons are safe)
  19882. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19883. "W/\"second-long-non-matching-value\", "
  19884. "W/\"third-long-non-matching-value\""}};
  19885. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19886. ASSERT_TRUE(res5);
  19887. EXPECT_EQ(200, res5->status); // Should not match
  19888. // Test 5: Single character that is not "*" (edge case)
  19889. Headers h5 = {{"If-None-Match", "X"}};
  19890. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19891. ASSERT_TRUE(res6);
  19892. EXPECT_EQ(200, res6->status); // Should not match
  19893. svr.stop();
  19894. t.join();
  19895. std::remove(fname);
  19896. }
  19897. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19898. using namespace httplib;
  19899. // Create a test file
  19900. const char *fname = "ims_testfile.txt";
  19901. const char *content = "if-modified-since-test";
  19902. {
  19903. std::ofstream ofs(fname);
  19904. ofs << content;
  19905. ASSERT_TRUE(ofs.good());
  19906. }
  19907. Server svr;
  19908. svr.set_mount_point("/static", ".");
  19909. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19910. svr.wait_until_ready();
  19911. Client cli(HOST, PORT);
  19912. // First request: should get 200 with Last-Modified header
  19913. auto res1 = cli.Get("/static/ims_testfile.txt");
  19914. ASSERT_TRUE(res1);
  19915. ASSERT_EQ(200, res1->status);
  19916. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19917. std::string last_modified = res1->get_header_value("Last-Modified");
  19918. EXPECT_FALSE(last_modified.empty());
  19919. // If-Modified-Since with same time: expect 304
  19920. Headers h2 = {{"If-Modified-Since", last_modified}};
  19921. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19922. ASSERT_TRUE(res2);
  19923. EXPECT_EQ(304, res2->status);
  19924. // If-Modified-Since with future time: expect 304
  19925. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19926. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19927. ASSERT_TRUE(res3);
  19928. EXPECT_EQ(304, res3->status);
  19929. // If-Modified-Since with past time: expect 200
  19930. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19931. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19932. ASSERT_TRUE(res4);
  19933. EXPECT_EQ(200, res4->status);
  19934. // If-None-Match takes precedence over If-Modified-Since
  19935. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19936. ASSERT_TRUE(res1->has_header("ETag"));
  19937. std::string etag = res1->get_header_value("ETag");
  19938. Headers h5 = {{"If-None-Match", etag},
  19939. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19940. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19941. ASSERT_TRUE(res5);
  19942. EXPECT_EQ(304, res5->status);
  19943. svr.stop();
  19944. t.join();
  19945. std::remove(fname);
  19946. }
  19947. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19948. using namespace httplib;
  19949. Server svr;
  19950. // Endpoint that returns compressible content
  19951. svr.Get("/compressible", [](const Request &, Response &res) {
  19952. // Return a large enough body to trigger compression
  19953. std::string body(1000, 'a');
  19954. res.set_content(body, "text/plain");
  19955. });
  19956. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19957. svr.wait_until_ready();
  19958. Client cli(HOST, PORT);
  19959. // Request with gzip support: should get Vary header when compressed
  19960. cli.set_compress(true);
  19961. auto res1 = cli.Get("/compressible");
  19962. ASSERT_TRUE(res1);
  19963. EXPECT_EQ(200, res1->status);
  19964. // If Content-Encoding is set, Vary should also be set
  19965. if (res1->has_header("Content-Encoding")) {
  19966. EXPECT_TRUE(res1->has_header("Vary"));
  19967. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19968. }
  19969. // Request without Accept-Encoding header: should not have compression
  19970. Headers h_no_compress;
  19971. auto res2 = cli.Get("/compressible", h_no_compress);
  19972. ASSERT_TRUE(res2);
  19973. EXPECT_EQ(200, res2->status);
  19974. // Verify Vary header is present when compression is applied
  19975. // (the exact behavior depends on server configuration)
  19976. svr.stop();
  19977. t.join();
  19978. }
  19979. TEST(ETagTest, IfRangeWithETag) {
  19980. using namespace httplib;
  19981. // Create a test file with known content
  19982. const char *fname = "if_range_testfile.txt";
  19983. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19984. {
  19985. std::ofstream ofs(fname);
  19986. ofs << content;
  19987. ASSERT_TRUE(ofs.good());
  19988. }
  19989. Server svr;
  19990. svr.set_mount_point("/static", ".");
  19991. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19992. svr.wait_until_ready();
  19993. Client cli(HOST, PORT);
  19994. // First request: get ETag
  19995. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19996. ASSERT_TRUE(res1);
  19997. ASSERT_EQ(200, res1->status);
  19998. ASSERT_TRUE(res1->has_header("ETag"));
  19999. std::string etag = res1->get_header_value("ETag");
  20000. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20001. // Since our server generates weak ETags (W/"..."), If-Range with our
  20002. // ETag should NOT result in partial content - it should return full content.
  20003. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20004. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20005. ASSERT_TRUE(res2);
  20006. // Weak ETag in If-Range -> full content (200), not partial (206)
  20007. EXPECT_EQ(200, res2->status);
  20008. EXPECT_EQ(content, res2->body);
  20009. EXPECT_FALSE(res2->has_header("Content-Range"));
  20010. // Range request with non-matching If-Range (ETag): should get 200 (full
  20011. // content)
  20012. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20013. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20014. ASSERT_TRUE(res3);
  20015. EXPECT_EQ(200, res3->status);
  20016. EXPECT_EQ(content, res3->body);
  20017. EXPECT_FALSE(res3->has_header("Content-Range"));
  20018. // Range request with strong ETag (hypothetical - our server doesn't generate
  20019. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20020. // should return full content)
  20021. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20022. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20023. ASSERT_TRUE(res4);
  20024. EXPECT_EQ(200, res4->status);
  20025. EXPECT_EQ(content, res4->body);
  20026. EXPECT_FALSE(res4->has_header("Content-Range"));
  20027. svr.stop();
  20028. t.join();
  20029. std::remove(fname);
  20030. }
  20031. TEST(ETagTest, IfRangeWithDate) {
  20032. using namespace httplib;
  20033. // Create a test file
  20034. const char *fname = "if_range_date_testfile.txt";
  20035. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20036. {
  20037. std::ofstream ofs(fname);
  20038. ofs << content;
  20039. ASSERT_TRUE(ofs.good());
  20040. }
  20041. Server svr;
  20042. svr.set_mount_point("/static", ".");
  20043. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20044. svr.wait_until_ready();
  20045. Client cli(HOST, PORT);
  20046. // First request: get Last-Modified
  20047. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20048. ASSERT_TRUE(res1);
  20049. ASSERT_EQ(200, res1->status);
  20050. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20051. std::string last_modified = res1->get_header_value("Last-Modified");
  20052. // Range request with matching If-Range (date): should get 206
  20053. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20054. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20055. ASSERT_TRUE(res2);
  20056. EXPECT_EQ(206, res2->status);
  20057. EXPECT_EQ("FGHIJ", res2->body);
  20058. // Range request with old If-Range date: should get 200 (full content)
  20059. Headers h3 = {{"Range", "bytes=5-9"},
  20060. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20061. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20062. ASSERT_TRUE(res3);
  20063. EXPECT_EQ(200, res3->status);
  20064. EXPECT_EQ(content, res3->body);
  20065. // Range request with future If-Range date: should get 206
  20066. Headers h4 = {{"Range", "bytes=0-4"},
  20067. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20068. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20069. ASSERT_TRUE(res4);
  20070. EXPECT_EQ(206, res4->status);
  20071. EXPECT_EQ("ABCDE", res4->body);
  20072. svr.stop();
  20073. t.join();
  20074. std::remove(fname);
  20075. }
  20076. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20077. using namespace httplib;
  20078. const char *fname = "etag_malformed.txt";
  20079. const char *content = "malformed-etag";
  20080. {
  20081. std::ofstream ofs(fname);
  20082. ofs << content;
  20083. ASSERT_TRUE(ofs.good());
  20084. }
  20085. Server svr;
  20086. svr.set_mount_point("/static", ".");
  20087. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20088. svr.wait_until_ready();
  20089. Client cli(HOST, PORT);
  20090. // baseline: should get 200 and an ETag
  20091. auto res1 = cli.Get("/static/etag_malformed.txt");
  20092. ASSERT_TRUE(res1);
  20093. ASSERT_EQ(200, res1->status);
  20094. ASSERT_TRUE(res1->has_header("ETag"));
  20095. // Malformed ETag value (missing quotes) should be treated as non-matching
  20096. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20097. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20098. ASSERT_TRUE(res_bad);
  20099. EXPECT_EQ(200, res_bad->status);
  20100. // Whitespace-only header value should be considered invalid / non-matching
  20101. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20102. "Host: localhost\r\n"
  20103. "If-None-Match: \r\n"
  20104. "Connection: close\r\n"
  20105. "\r\n";
  20106. std::string out;
  20107. ASSERT_TRUE(send_request(5, raw_req, &out));
  20108. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20109. svr.stop();
  20110. t.join();
  20111. std::remove(fname);
  20112. }
  20113. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20114. using namespace httplib;
  20115. const char *fname = "ims_invalid_format.txt";
  20116. const char *content = "ims-bad-format";
  20117. {
  20118. std::ofstream ofs(fname);
  20119. ofs << content;
  20120. ASSERT_TRUE(ofs.good());
  20121. }
  20122. Server svr;
  20123. svr.set_mount_point("/static", ".");
  20124. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20125. svr.wait_until_ready();
  20126. Client cli(HOST, PORT);
  20127. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20128. ASSERT_TRUE(res1);
  20129. ASSERT_EQ(200, res1->status);
  20130. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20131. // If-Modified-Since with invalid format should not result in 304
  20132. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20133. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20134. ASSERT_TRUE(res_bad);
  20135. EXPECT_EQ(200, res_bad->status);
  20136. // If-Range with invalid date format should be treated as mismatch -> full
  20137. // content (200)
  20138. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20139. {"If-Range", "invalid-date"}};
  20140. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20141. ASSERT_TRUE(res_ifrange);
  20142. EXPECT_EQ(200, res_ifrange->status);
  20143. svr.stop();
  20144. t.join();
  20145. std::remove(fname);
  20146. }
  20147. TEST(ETagTest, IfRangeWithMalformedETag) {
  20148. using namespace httplib;
  20149. const char *fname = "ifrange_malformed.txt";
  20150. const std::string content = "0123456789";
  20151. {
  20152. std::ofstream ofs(fname);
  20153. ofs << content;
  20154. ASSERT_TRUE(ofs.good());
  20155. }
  20156. Server svr;
  20157. svr.set_mount_point("/static", ".");
  20158. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20159. svr.wait_until_ready();
  20160. Client cli(HOST, PORT);
  20161. // First request: get ETag
  20162. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20163. ASSERT_TRUE(res1);
  20164. ASSERT_EQ(200, res1->status);
  20165. ASSERT_TRUE(res1->has_header("ETag"));
  20166. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20167. // full content (200)
  20168. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20169. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20170. ASSERT_TRUE(res2);
  20171. EXPECT_EQ(200, res2->status);
  20172. EXPECT_EQ(content, res2->body);
  20173. svr.stop();
  20174. t.join();
  20175. std::remove(fname);
  20176. }
  20177. TEST(ETagTest, ExtremeLargeDateValues) {
  20178. using namespace httplib;
  20179. const char *fname = "ims_extreme_date.txt";
  20180. const char *content = "ims-extreme-date";
  20181. {
  20182. std::ofstream ofs(fname);
  20183. ofs << content;
  20184. ASSERT_TRUE(ofs.good());
  20185. }
  20186. Server svr;
  20187. svr.set_mount_point("/static", ".");
  20188. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20189. svr.wait_until_ready();
  20190. Client cli(HOST, PORT);
  20191. auto res1 = cli.Get(std::string("/static/") + fname);
  20192. ASSERT_TRUE(res1);
  20193. ASSERT_EQ(200, res1->status);
  20194. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20195. // Extremely large year that may overflow date parsing routines.
  20196. Headers h_large_date = {
  20197. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20198. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20199. ASSERT_TRUE(res_bad);
  20200. // Expect server to treat this as invalid/mismatch and return full content
  20201. EXPECT_EQ(200, res_bad->status);
  20202. // If-Range with extremely large date should be treated as mismatch -> full
  20203. // content (200)
  20204. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20205. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20206. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20207. ASSERT_TRUE(res_ifrange);
  20208. EXPECT_EQ(200, res_ifrange->status);
  20209. svr.stop();
  20210. t.join();
  20211. std::remove(fname);
  20212. }
  20213. TEST(ETagTest, NegativeFileModificationTime) {
  20214. using namespace httplib;
  20215. const char *fname = "ims_negative_mtime.txt";
  20216. const std::string content = "negative-mtime";
  20217. {
  20218. std::ofstream ofs(fname);
  20219. ofs << content;
  20220. ASSERT_TRUE(ofs.good());
  20221. }
  20222. // Try to set file mtime to a negative value. This may fail on some
  20223. // platforms/filesystems; if it fails, the test will still verify server
  20224. // behaves safely by performing a regular conditional request.
  20225. #if defined(__APPLE__) || defined(__linux__)
  20226. bool set_negative = false;
  20227. do {
  20228. struct timeval times[2];
  20229. // access time: now
  20230. times[0].tv_sec = time(nullptr);
  20231. times[0].tv_usec = 0;
  20232. // modification time: negative (e.g., -1)
  20233. times[1].tv_sec = -1;
  20234. times[1].tv_usec = 0;
  20235. if (utimes(fname, times) == 0) { set_negative = true; }
  20236. } while (0);
  20237. #else
  20238. bool set_negative = false;
  20239. #endif
  20240. Server svr;
  20241. svr.set_mount_point("/static", ".");
  20242. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20243. svr.wait_until_ready();
  20244. Client cli(HOST, PORT);
  20245. auto res1 = cli.Get(std::string("/static/") + fname);
  20246. ASSERT_TRUE(res1);
  20247. ASSERT_EQ(200, res1->status);
  20248. bool has_last_modified = res1->has_header("Last-Modified");
  20249. std::string last_modified;
  20250. if (has_last_modified) {
  20251. last_modified = res1->get_header_value("Last-Modified");
  20252. }
  20253. if (set_negative) {
  20254. // If we successfully set a negative mtime, ensure server returns a
  20255. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20256. // with an old date and ensure server handles it without crash.
  20257. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20258. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20259. ASSERT_TRUE(res2);
  20260. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20261. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20262. } else {
  20263. // Could not set negative mtime on this platform; fall back to verifying
  20264. // that normal invalid/malformed dates are treated safely (non-304).
  20265. Headers h_bad_date = {
  20266. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20267. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20268. ASSERT_TRUE(res_bad);
  20269. EXPECT_EQ(200, res_bad->status);
  20270. }
  20271. svr.stop();
  20272. t.join();
  20273. std::remove(fname);
  20274. }
  20275. //==============================================================================
  20276. // Integration Tests with Server
  20277. //==============================================================================
  20278. class SSEIntegrationTest : public ::testing::Test {
  20279. protected:
  20280. void SetUp() override {
  20281. stop_server_.store(false);
  20282. events_.clear();
  20283. server_ = httplib::detail::make_unique<Server>();
  20284. setup_server();
  20285. start_server();
  20286. }
  20287. void TearDown() override {
  20288. stop_server_.store(true);
  20289. event_cv_.notify_all();
  20290. server_->stop();
  20291. if (server_thread_.joinable()) { server_thread_.join(); }
  20292. }
  20293. void setup_server() {
  20294. // Simple SSE endpoint
  20295. server_->Get("/events", [this](const Request &req, Response &res) {
  20296. auto last_id = req.get_header_value("Last-Event-ID");
  20297. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20298. res.set_chunked_content_provider(
  20299. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20300. std::unique_lock<std::mutex> lock(event_mutex_);
  20301. if (event_cv_.wait_for(
  20302. lock, std::chrono::milliseconds(200), [this] {
  20303. return !events_.empty() || stop_server_.load();
  20304. })) {
  20305. if (stop_server_.load()) { return false; }
  20306. if (!events_.empty()) {
  20307. std::string event = events_.front();
  20308. events_.erase(events_.begin());
  20309. sink.write(event.data(), event.size());
  20310. return true;
  20311. }
  20312. }
  20313. return !stop_server_.load();
  20314. });
  20315. });
  20316. // Endpoint that returns error
  20317. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20318. res.status = 500;
  20319. res.set_content("Internal Server Error", "text/plain");
  20320. });
  20321. // Endpoint for custom event types
  20322. server_->Get("/custom-events", [](const Request &, Response &res) {
  20323. res.set_chunked_content_provider(
  20324. "text/event-stream", [](size_t offset, DataSink &sink) {
  20325. if (offset == 0) {
  20326. std::string event = "event: update\ndata: updated\n\n"
  20327. "event: delete\ndata: deleted\n\n";
  20328. sink.write(event.data(), event.size());
  20329. }
  20330. return false; // End stream after sending
  20331. });
  20332. });
  20333. }
  20334. void start_server() {
  20335. port_ = server_->bind_to_any_port(HOST);
  20336. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20337. // Wait for server to start
  20338. while (!server_->is_running()) {
  20339. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20340. }
  20341. }
  20342. int get_port() const { return port_; }
  20343. void send_event(const std::string &event) {
  20344. std::lock_guard<std::mutex> lock(event_mutex_);
  20345. events_.push_back(event);
  20346. event_cv_.notify_all();
  20347. }
  20348. std::unique_ptr<Server> server_;
  20349. std::thread server_thread_;
  20350. std::mutex event_mutex_;
  20351. std::condition_variable event_cv_;
  20352. std::vector<std::string> events_;
  20353. std::atomic<bool> stop_server_{false};
  20354. std::string last_received_event_id_;
  20355. int port_ = 0;
  20356. };
  20357. //==============================================================================
  20358. // SSE Parsing Tests
  20359. //==============================================================================
  20360. class SSEParsingTest : public SSEIntegrationTest {
  20361. protected:
  20362. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20363. // A trailing sentinel event tells when the whole stream has been parsed.
  20364. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20365. auto body = stream + "event: end\ndata: end\n\n";
  20366. server_->Get("/parse", [body](const Request &, Response &res) {
  20367. res.set_content(body, "text/event-stream");
  20368. });
  20369. return collect("/parse");
  20370. }
  20371. // Runs SSEClient against path until an "end" event arrives and returns the
  20372. // messages dispatched before it
  20373. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20374. Client client(HOST, get_port());
  20375. sse::SSEClient sse(client, path);
  20376. std::mutex mutex;
  20377. std::condition_variable cv;
  20378. std::vector<sse::SSEMessage> messages;
  20379. auto done = false;
  20380. sse.on_message([&](const sse::SSEMessage &msg) {
  20381. std::lock_guard<std::mutex> lock(mutex);
  20382. // Ignore a replay from a reconnect that races with stop()
  20383. if (!done) { messages.push_back(msg); }
  20384. });
  20385. sse.on_event("end", [&](const sse::SSEMessage &) {
  20386. std::lock_guard<std::mutex> lock(mutex);
  20387. done = true;
  20388. cv.notify_all();
  20389. });
  20390. sse.set_reconnect_interval(100);
  20391. sse.start_async();
  20392. {
  20393. std::unique_lock<std::mutex> lock(mutex);
  20394. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20395. }
  20396. sse.stop();
  20397. EXPECT_TRUE(done);
  20398. return messages;
  20399. }
  20400. };
  20401. TEST_F(SSEParsingTest, SingleLineData) {
  20402. auto msgs = parse("data: hello\n\n");
  20403. ASSERT_EQ(msgs.size(), 1u);
  20404. EXPECT_EQ(msgs[0].data, "hello");
  20405. EXPECT_EQ(msgs[0].event, "message");
  20406. }
  20407. TEST_F(SSEParsingTest, MultiLineData) {
  20408. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20409. ASSERT_EQ(msgs.size(), 1u);
  20410. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20411. }
  20412. TEST_F(SSEParsingTest, CustomEventType) {
  20413. auto msgs = parse("event: update\ndata: payload\n\n");
  20414. ASSERT_EQ(msgs.size(), 1u);
  20415. EXPECT_EQ(msgs[0].event, "update");
  20416. EXPECT_EQ(msgs[0].data, "payload");
  20417. }
  20418. TEST_F(SSEParsingTest, EventIdHandling) {
  20419. auto msgs = parse("id: 12345\ndata: test\n\n");
  20420. ASSERT_EQ(msgs.size(), 1u);
  20421. EXPECT_EQ(msgs[0].id, "12345");
  20422. }
  20423. TEST_F(SSEParsingTest, EmptyEventId) {
  20424. auto msgs = parse("id:\ndata: test\n\n");
  20425. ASSERT_EQ(msgs.size(), 1u);
  20426. EXPECT_EQ(msgs[0].id, "");
  20427. }
  20428. TEST_F(SSEParsingTest, CommentsIgnored) {
  20429. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20430. ASSERT_EQ(msgs.size(), 1u);
  20431. EXPECT_EQ(msgs[0].data, "hello");
  20432. EXPECT_EQ(msgs[0].event, "message");
  20433. }
  20434. TEST_F(SSEParsingTest, ColonInValue) {
  20435. auto msgs = parse("data: hello:world:test\n\n");
  20436. ASSERT_EQ(msgs.size(), 1u);
  20437. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20438. }
  20439. TEST_F(SSEParsingTest, FieldNameOnly) {
  20440. // A line without a colon is a field name with an empty value
  20441. auto msgs = parse("data\n\n");
  20442. ASSERT_EQ(msgs.size(), 1u);
  20443. EXPECT_EQ(msgs[0].data, "");
  20444. }
  20445. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20446. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20447. ASSERT_EQ(msgs.size(), 1u);
  20448. EXPECT_EQ(msgs[0].event, "update");
  20449. EXPECT_EQ(msgs[0].data, "hello");
  20450. }
  20451. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20452. auto msgs = parse("data\r\n\r\n");
  20453. ASSERT_EQ(msgs.size(), 1u);
  20454. EXPECT_EQ(msgs[0].data, "");
  20455. }
  20456. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20457. auto msgs = parse("event: update\rdata: hello\r\r");
  20458. ASSERT_EQ(msgs.size(), 1u);
  20459. EXPECT_EQ(msgs[0].event, "update");
  20460. EXPECT_EQ(msgs[0].data, "hello");
  20461. }
  20462. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20463. // Chunk boundaries fall inside every \r\n and right before the first one
  20464. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20465. "\n\r", "\nevent: end\ndata: end\n\n"};
  20466. server_->Get("/split", [chunks](const Request &, Response &res) {
  20467. auto i = std::make_shared<size_t>(0);
  20468. res.set_chunked_content_provider(
  20469. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20470. if (*i == chunks.size()) {
  20471. sink.done();
  20472. } else {
  20473. sink.write(chunks[*i].data(), chunks[*i].size());
  20474. (*i)++;
  20475. }
  20476. return true;
  20477. });
  20478. });
  20479. auto msgs = collect("/split");
  20480. ASSERT_EQ(msgs.size(), 1u);
  20481. EXPECT_EQ(msgs[0].event, "update");
  20482. EXPECT_EQ(msgs[0].data, "hello");
  20483. }
  20484. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20485. // Only a BOM at the start of the stream is ignored
  20486. auto msgs = parse("\xEF\xBB\xBF"
  20487. "data: first\n\n"
  20488. "\xEF\xBB\xBF"
  20489. "data: second\n\n");
  20490. ASSERT_EQ(msgs.size(), 1u);
  20491. EXPECT_EQ(msgs[0].data, "first");
  20492. }
  20493. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20494. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20495. ASSERT_EQ(msgs.size(), 1u);
  20496. EXPECT_EQ(msgs[0].data, "hello");
  20497. EXPECT_EQ(msgs[0].event, "message");
  20498. }
  20499. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20500. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20501. ASSERT_EQ(msgs.size(), 2u);
  20502. EXPECT_EQ(msgs[0].data, "hello");
  20503. EXPECT_EQ(msgs[1].data, "hello");
  20504. }
  20505. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20506. // An event without data is not dispatched, and its type must not leak
  20507. // into the next event
  20508. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20509. ASSERT_EQ(msgs.size(), 1u);
  20510. EXPECT_EQ(msgs[0].event, "message");
  20511. EXPECT_EQ(msgs[0].data, "hello");
  20512. }
  20513. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20514. // The first connection sends only an id; the second echoes back the
  20515. // Last-Event-ID it was reconnected with
  20516. std::atomic<int> connection_count{0};
  20517. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20518. if (connection_count++ == 0) {
  20519. res.set_content("id: 42\n\n", "text/event-stream");
  20520. } else {
  20521. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20522. "\n\nevent: end\ndata: end\n\n",
  20523. "text/event-stream");
  20524. }
  20525. });
  20526. auto msgs = collect("/id-only");
  20527. ASSERT_EQ(msgs.size(), 1u);
  20528. EXPECT_EQ(msgs[0].data, "42");
  20529. }
  20530. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20531. // The first connection sets an id and then clears it with an empty one; the
  20532. // second reports whether it was reconnected with a Last-Event-ID
  20533. std::atomic<int> connection_count{0};
  20534. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20535. if (connection_count++ == 0) {
  20536. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20537. "text/event-stream");
  20538. } else {
  20539. res.set_content(
  20540. std::string("data: ") +
  20541. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20542. "\n\nevent: end\ndata: end\n\n",
  20543. "text/event-stream");
  20544. }
  20545. });
  20546. auto msgs = collect("/id-clear");
  20547. ASSERT_EQ(msgs.size(), 3u);
  20548. EXPECT_EQ(msgs[0].id, "1");
  20549. EXPECT_EQ(msgs[1].id, "");
  20550. EXPECT_EQ(msgs[2].data, "not sent");
  20551. }
  20552. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20553. // The first connection sets an id and then sends ids that cannot be carried
  20554. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20555. // with
  20556. std::atomic<int> connection_count{0};
  20557. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20558. if (connection_count++ == 0) {
  20559. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20560. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20561. "text/event-stream");
  20562. } else {
  20563. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20564. "\n\nevent: end\ndata: end\n\n",
  20565. "text/event-stream");
  20566. }
  20567. });
  20568. auto msgs = collect("/id-unsendable");
  20569. ASSERT_EQ(msgs.size(), 1u);
  20570. EXPECT_EQ(msgs[0].data, "42");
  20571. }
  20572. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20573. auto msgs = parse("event: notification\nid: evt-42\n"
  20574. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20575. ASSERT_EQ(msgs.size(), 1u);
  20576. EXPECT_EQ(msgs[0].event, "notification");
  20577. EXPECT_EQ(msgs[0].id, "evt-42");
  20578. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20579. }
  20580. TEST(SSEMessageTest, Clear) {
  20581. sse::SSEMessage msg;
  20582. msg.event = "custom";
  20583. msg.data = "some data";
  20584. msg.id = "123";
  20585. msg.clear();
  20586. EXPECT_EQ(msg.event, "message");
  20587. EXPECT_EQ(msg.data, "");
  20588. EXPECT_EQ(msg.id, "");
  20589. }
  20590. //==============================================================================
  20591. // SSE Integration Tests
  20592. //==============================================================================
  20593. // Test: Successful connection and on_open callback
  20594. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20595. // Add a simple endpoint that sends one event and closes
  20596. server_->Get("/simple-event", [](const Request &, Response &res) {
  20597. res.set_chunked_content_provider(
  20598. "text/event-stream", [](size_t offset, DataSink &sink) {
  20599. if (offset == 0) {
  20600. std::string event = "data: hello\n\n";
  20601. sink.write(event.data(), event.size());
  20602. }
  20603. return false; // Close stream after sending
  20604. });
  20605. });
  20606. Client client("localhost", get_port());
  20607. sse::SSEClient sse(client, "/simple-event");
  20608. std::atomic<bool> open_called{false};
  20609. std::atomic<bool> message_received{false};
  20610. sse.on_open([&open_called]() { open_called.store(true); });
  20611. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20612. if (msg.data == "hello") { message_received.store(true); }
  20613. });
  20614. sse.set_reconnect_interval(100);
  20615. sse.set_max_reconnect_attempts(1);
  20616. // Start async
  20617. sse.start_async();
  20618. // Wait for message to be processed
  20619. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20620. sse.stop();
  20621. EXPECT_TRUE(open_called.load());
  20622. EXPECT_TRUE(message_received.load());
  20623. }
  20624. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20625. // A data line that never ends.
  20626. server_->Get("/endless-line", [](const Request &, Response &res) {
  20627. res.set_chunked_content_provider(
  20628. "text/event-stream", [](size_t offset, DataSink &sink) {
  20629. if (offset == 0) { sink.write("data: ", 6); }
  20630. std::string chunk(64 * 1024, 'A');
  20631. return sink.write(chunk.data(), chunk.size());
  20632. });
  20633. });
  20634. Client client("localhost", get_port());
  20635. // Lift the payload limit, so that only the event limit can end this endless
  20636. // stream.
  20637. client.set_payload_max_length(0);
  20638. sse::SSEClient sse(client, "/endless-line");
  20639. std::atomic<bool> too_long{false};
  20640. sse.on_error([&](Error err) {
  20641. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20642. });
  20643. sse.set_max_reconnect_attempts(1);
  20644. sse.start_async();
  20645. for (int i = 0; i < 500 && !too_long; i++) {
  20646. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20647. }
  20648. sse.stop();
  20649. EXPECT_TRUE(too_long);
  20650. }
  20651. // Test: on_message callback
  20652. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20653. // Endpoint that sends multiple events then closes
  20654. server_->Get("/multi-event", [](const Request &, Response &res) {
  20655. res.set_chunked_content_provider(
  20656. "text/event-stream", [](size_t offset, DataSink &sink) {
  20657. if (offset == 0) {
  20658. std::string events = "data: message1\n\ndata: message2\n\n";
  20659. sink.write(events.data(), events.size());
  20660. }
  20661. return false;
  20662. });
  20663. });
  20664. Client client("localhost", get_port());
  20665. sse::SSEClient sse(client, "/multi-event");
  20666. std::vector<std::string> received_messages;
  20667. std::mutex messages_mutex;
  20668. sse.on_message([&](const sse::SSEMessage &msg) {
  20669. std::lock_guard<std::mutex> lock(messages_mutex);
  20670. received_messages.push_back(msg.data);
  20671. });
  20672. sse.set_reconnect_interval(100);
  20673. sse.set_max_reconnect_attempts(1);
  20674. sse.start_async();
  20675. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20676. sse.stop();
  20677. std::lock_guard<std::mutex> lock(messages_mutex);
  20678. EXPECT_GE(received_messages.size(), 2u);
  20679. if (received_messages.size() >= 2) {
  20680. EXPECT_EQ(received_messages[0], "message1");
  20681. EXPECT_EQ(received_messages[1], "message2");
  20682. }
  20683. }
  20684. // Test: on_event for specific types
  20685. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20686. Client client("localhost", get_port());
  20687. sse::SSEClient sse(client, "/custom-events");
  20688. std::atomic<bool> update_received{false};
  20689. std::atomic<bool> delete_received{false};
  20690. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20691. if (msg.data == "updated") { update_received.store(true); }
  20692. });
  20693. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20694. if (msg.data == "deleted") { delete_received.store(true); }
  20695. });
  20696. sse.set_max_reconnect_attempts(1);
  20697. sse.start_async();
  20698. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20699. sse.stop();
  20700. EXPECT_TRUE(update_received.load());
  20701. EXPECT_TRUE(delete_received.load());
  20702. }
  20703. // Test: on_error callback on connection failure
  20704. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20705. // Connect to a non-existent port
  20706. Client client("localhost", 59999);
  20707. sse::SSEClient sse(client, "/events");
  20708. std::atomic<bool> error_called{false};
  20709. Error received_error = Error::Success;
  20710. sse.on_error([&](Error err) {
  20711. error_called.store(true);
  20712. received_error = err;
  20713. });
  20714. sse.set_reconnect_interval(50);
  20715. sse.set_max_reconnect_attempts(1);
  20716. sse.start_async();
  20717. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20718. sse.stop();
  20719. EXPECT_TRUE(error_called.load());
  20720. EXPECT_NE(received_error, Error::Success);
  20721. }
  20722. // Test: Last-Event-ID header sent on reconnect
  20723. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20724. // Endpoint that sends event with ID
  20725. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20726. res.set_chunked_content_provider(
  20727. "text/event-stream", [](size_t offset, DataSink &sink) {
  20728. if (offset == 0) {
  20729. std::string event = "id: evt-123\ndata: test\n\n";
  20730. sink.write(event.data(), event.size());
  20731. }
  20732. return false;
  20733. });
  20734. });
  20735. Client client("localhost", get_port());
  20736. sse::SSEClient sse(client, "/event-with-id");
  20737. std::atomic<bool> id_received{false};
  20738. sse.on_message([&](const sse::SSEMessage &msg) {
  20739. if (!msg.id.empty()) { id_received.store(true); }
  20740. });
  20741. sse.set_reconnect_interval(100);
  20742. sse.set_max_reconnect_attempts(1);
  20743. sse.start_async();
  20744. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20745. sse.stop();
  20746. EXPECT_TRUE(id_received.load());
  20747. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20748. }
  20749. // Test: Manual stop
  20750. TEST_F(SSEIntegrationTest, ManualStop) {
  20751. // Endpoint that sends one event and stays open briefly
  20752. std::atomic<bool> handler_running{true};
  20753. server_->Get("/stay-open", [&handler_running](const Request &,
  20754. Response &res) {
  20755. res.set_chunked_content_provider(
  20756. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20757. if (offset == 0) {
  20758. std::string event = "data: connected\n\n";
  20759. sink.write(event.data(), event.size());
  20760. }
  20761. // Keep connection open while handler_running is true
  20762. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20763. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20764. }
  20765. return false;
  20766. });
  20767. });
  20768. Client client("localhost", get_port());
  20769. sse::SSEClient sse(client, "/stay-open");
  20770. std::atomic<bool> connected{false};
  20771. sse.on_open([&connected]() { connected.store(true); });
  20772. sse.set_reconnect_interval(100);
  20773. sse.set_max_reconnect_attempts(1);
  20774. sse.start_async();
  20775. // Wait for connection to establish
  20776. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20777. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20778. }
  20779. EXPECT_TRUE(connected.load());
  20780. EXPECT_TRUE(sse.is_connected());
  20781. // Signal handler to stop
  20782. handler_running.store(false);
  20783. // Stop SSE client
  20784. sse.stop();
  20785. EXPECT_FALSE(sse.is_connected());
  20786. }
  20787. // Test: SSEClient with custom headers
  20788. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20789. // Setup a server endpoint that checks for custom header
  20790. std::atomic<bool> header_received{false};
  20791. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20792. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20793. header_received.store(true);
  20794. }
  20795. res.set_chunked_content_provider("text/event-stream",
  20796. [](size_t, DataSink &) { return false; });
  20797. });
  20798. Client client("localhost", get_port());
  20799. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20800. sse::SSEClient sse(client, "/header-check", headers);
  20801. sse.set_max_reconnect_attempts(1);
  20802. sse.start_async();
  20803. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20804. sse.stop();
  20805. EXPECT_TRUE(header_received.load());
  20806. }
  20807. // Test: Reconnect interval configuration
  20808. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20809. Client client("localhost", get_port());
  20810. sse::SSEClient sse(client, "/events");
  20811. auto &result = sse.set_reconnect_interval(500);
  20812. // Builder pattern should return reference to self
  20813. EXPECT_EQ(&result, &sse);
  20814. }
  20815. // Test: Max reconnect attempts
  20816. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20817. // Connect to non-existent port to force reconnects
  20818. Client client("localhost", 59998);
  20819. sse::SSEClient sse(client, "/events");
  20820. std::atomic<int> error_count{0};
  20821. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20822. sse.set_reconnect_interval(50);
  20823. sse.set_max_reconnect_attempts(2);
  20824. auto start = std::chrono::steady_clock::now();
  20825. sse.start(); // Blocking call
  20826. auto end = std::chrono::steady_clock::now();
  20827. // Should have stopped after 2 failed attempts
  20828. EXPECT_GE(error_count.load(), 2);
  20829. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20830. auto duration =
  20831. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20832. #ifdef _WIN32
  20833. // Windows is much slower for socket connection failures
  20834. EXPECT_LT(duration.count(), 7000);
  20835. #else
  20836. EXPECT_LT(duration.count(), 1000);
  20837. #endif
  20838. }
  20839. // Test: Multi-line data in integration
  20840. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20841. // Endpoint with multi-line data
  20842. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20843. res.set_chunked_content_provider(
  20844. "text/event-stream", [](size_t offset, DataSink &sink) {
  20845. if (offset == 0) {
  20846. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20847. sink.write(event.data(), event.size());
  20848. }
  20849. return false;
  20850. });
  20851. });
  20852. Client client("localhost", get_port());
  20853. sse::SSEClient sse(client, "/multiline-data");
  20854. std::string received_data;
  20855. std::mutex data_mutex;
  20856. sse.on_message([&](const sse::SSEMessage &msg) {
  20857. std::lock_guard<std::mutex> lock(data_mutex);
  20858. received_data = msg.data;
  20859. });
  20860. sse.set_reconnect_interval(100);
  20861. sse.set_max_reconnect_attempts(1);
  20862. sse.start_async();
  20863. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20864. sse.stop();
  20865. std::lock_guard<std::mutex> lock(data_mutex);
  20866. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20867. }
  20868. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20869. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20870. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20871. DataSink &sink) {
  20872. if (offset == 0) {
  20873. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20874. sink.write(events.data(), events.size());
  20875. }
  20876. return false;
  20877. });
  20878. });
  20879. Client client("localhost", get_port());
  20880. sse::SSEClient sse(client, "/empty-data-lines");
  20881. std::mutex mutex;
  20882. std::condition_variable cv;
  20883. std::vector<std::string> received;
  20884. sse.on_message([&](const sse::SSEMessage &msg) {
  20885. std::lock_guard<std::mutex> lock(mutex);
  20886. received.push_back(msg.data);
  20887. cv.notify_all();
  20888. });
  20889. sse.set_max_reconnect_attempts(1);
  20890. sse.start_async();
  20891. {
  20892. std::unique_lock<std::mutex> lock(mutex);
  20893. cv.wait_for(lock, std::chrono::seconds(2),
  20894. [&] { return received.size() >= 3; });
  20895. }
  20896. sse.stop();
  20897. ASSERT_GE(received.size(), 3u);
  20898. EXPECT_EQ(received[0], "");
  20899. EXPECT_EQ(received[1], "\nhello");
  20900. EXPECT_EQ(received[2], "");
  20901. }
  20902. // Test: Auto-reconnect after server disconnection
  20903. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20904. std::atomic<int> connection_count{0};
  20905. std::atomic<int> message_count{0};
  20906. // Endpoint that sends one event and closes, forcing reconnect
  20907. server_->Get("/reconnect-test",
  20908. [&connection_count](const Request &, Response &res) {
  20909. connection_count.fetch_add(1);
  20910. res.set_chunked_content_provider(
  20911. "text/event-stream", [](size_t offset, DataSink &sink) {
  20912. if (offset == 0) {
  20913. std::string event = "data: hello\n\n";
  20914. sink.write(event.data(), event.size());
  20915. }
  20916. return false; // Close connection after sending
  20917. });
  20918. });
  20919. Client client("localhost", get_port());
  20920. sse::SSEClient sse(client, "/reconnect-test");
  20921. sse.on_message([&message_count](const sse::SSEMessage &) {
  20922. message_count.fetch_add(1);
  20923. });
  20924. sse.set_reconnect_interval(100);
  20925. sse.set_max_reconnect_attempts(3);
  20926. sse.start_async();
  20927. // Wait long enough for multiple reconnects
  20928. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20929. sse.stop();
  20930. // Should have connected multiple times (initial + reconnects)
  20931. EXPECT_GE(connection_count.load(), 2);
  20932. // Should have received messages from multiple connections
  20933. EXPECT_GE(message_count.load(), 2);
  20934. }
  20935. // Test: A retry field that is not all ASCII digits is ignored
  20936. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20937. std::atomic<int> connection_count{0};
  20938. server_->Get("/bad-retry",
  20939. [&connection_count](const Request &, Response &res) {
  20940. connection_count.fetch_add(1);
  20941. res.set_chunked_content_provider(
  20942. "text/event-stream", [](size_t offset, DataSink &sink) {
  20943. if (offset == 0) {
  20944. std::string event = "retry: -1\ndata: hello\n\n";
  20945. sink.write(event.data(), event.size());
  20946. }
  20947. return false;
  20948. });
  20949. });
  20950. Client client("localhost", get_port());
  20951. sse::SSEClient sse(client, "/bad-retry");
  20952. sse.set_reconnect_interval(10000);
  20953. sse.start_async();
  20954. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20955. sse.stop();
  20956. EXPECT_EQ(connection_count.load(), 1);
  20957. }
  20958. // Test: A retry field of all ASCII digits sets the reconnection time
  20959. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20960. std::mutex mutex;
  20961. std::condition_variable cv;
  20962. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20963. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20964. {
  20965. std::lock_guard<std::mutex> lock(mutex);
  20966. connected_at.push_back(std::chrono::steady_clock::now());
  20967. cv.notify_all();
  20968. }
  20969. res.set_chunked_content_provider(
  20970. "text/event-stream", [](size_t offset, DataSink &sink) {
  20971. if (offset == 0) {
  20972. std::string event = "retry: 0\ndata: hello\n\n";
  20973. sink.write(event.data(), event.size());
  20974. }
  20975. return false;
  20976. });
  20977. });
  20978. Client client("localhost", get_port());
  20979. sse::SSEClient sse(client, "/zero-retry");
  20980. sse.set_reconnect_interval(10000);
  20981. sse.start_async();
  20982. {
  20983. std::unique_lock<std::mutex> lock(mutex);
  20984. cv.wait_for(lock, std::chrono::seconds(5),
  20985. [&] { return connected_at.size() >= 2; });
  20986. }
  20987. sse.stop();
  20988. // The server-supplied interval is applied, but never below 100ms, so
  20989. // "retry: 0" does not cause a busy reconnect loop
  20990. std::lock_guard<std::mutex> lock(mutex);
  20991. ASSERT_GE(connected_at.size(), 2u);
  20992. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20993. connected_at[1] - connected_at[0])
  20994. .count();
  20995. EXPECT_GE(interval_ms, 100);
  20996. }
  20997. // Test: Last-Event-ID sent on reconnect
  20998. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20999. std::atomic<int> connection_count{0};
  21000. std::vector<std::string> received_last_event_ids;
  21001. std::mutex id_mutex;
  21002. // Endpoint that checks Last-Event-ID header and sends event with ID
  21003. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21004. int conn = connection_count.fetch_add(1);
  21005. // Capture the Last-Event-ID header from each connection
  21006. {
  21007. std::lock_guard<std::mutex> lock(id_mutex);
  21008. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21009. }
  21010. res.set_chunked_content_provider(
  21011. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21012. if (offset == 0) {
  21013. std::string event =
  21014. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21015. sink.write(event.data(), event.size());
  21016. }
  21017. return false;
  21018. });
  21019. });
  21020. Client client("localhost", get_port());
  21021. sse::SSEClient sse(client, "/reconnect-with-id");
  21022. sse.set_reconnect_interval(100);
  21023. sse.set_max_reconnect_attempts(3);
  21024. sse.start_async();
  21025. // Wait for at least 2 connections
  21026. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21027. sse.stop();
  21028. // Verify behavior
  21029. std::lock_guard<std::mutex> lock(id_mutex);
  21030. EXPECT_GE(received_last_event_ids.size(), 2u);
  21031. // First connection should have no Last-Event-ID
  21032. if (!received_last_event_ids.empty()) {
  21033. EXPECT_EQ(received_last_event_ids[0], "");
  21034. }
  21035. // Second connection should have Last-Event-ID from first connection
  21036. if (received_last_event_ids.size() >= 2) {
  21037. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21038. }
  21039. }
  21040. // Test: set_headers updates headers used on reconnect
  21041. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21042. std::vector<std::string> received_tokens;
  21043. std::mutex token_mutex;
  21044. // Endpoint that captures Authorization header
  21045. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21046. {
  21047. std::lock_guard<std::mutex> lock(token_mutex);
  21048. received_tokens.push_back(req.get_header_value("Authorization"));
  21049. }
  21050. res.set_chunked_content_provider(
  21051. "text/event-stream", [](size_t offset, DataSink &sink) {
  21052. if (offset == 0) {
  21053. std::string event = "data: hello\n\n";
  21054. sink.write(event.data(), event.size());
  21055. }
  21056. return false; // Close connection to trigger reconnect
  21057. });
  21058. });
  21059. Client client("localhost", get_port());
  21060. Headers headers = {{"Authorization", "Bearer old-token"}};
  21061. sse::SSEClient sse(client, "/auth-check", headers);
  21062. // Update headers on each successful connection
  21063. sse.on_open(
  21064. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21065. sse.set_reconnect_interval(100);
  21066. sse.set_max_reconnect_attempts(3);
  21067. sse.start_async();
  21068. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21069. sse.stop();
  21070. std::lock_guard<std::mutex> lock(token_mutex);
  21071. ASSERT_GE(received_tokens.size(), 2u);
  21072. // First connection uses original header
  21073. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21074. // Second connection uses updated header from set_headers
  21075. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21076. }
  21077. // Test: 401 allows reconnection (so on_error can refresh headers)
  21078. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21079. std::atomic<int> connection_count{0};
  21080. // Endpoint: returns 401 on first attempt, 200 on second
  21081. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21082. int conn = connection_count.fetch_add(1);
  21083. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21084. res.status = StatusCode::Unauthorized_401;
  21085. res.set_content("Unauthorized", "text/plain");
  21086. return;
  21087. }
  21088. res.set_chunked_content_provider(
  21089. "text/event-stream", [](size_t offset, DataSink &sink) {
  21090. if (offset == 0) {
  21091. std::string event = "data: authenticated\n\n";
  21092. sink.write(event.data(), event.size());
  21093. }
  21094. return false;
  21095. });
  21096. });
  21097. Client client("localhost", get_port());
  21098. Headers headers = {{"Authorization", "Bearer expired"}};
  21099. sse::SSEClient sse(client, "/auth-retry", headers);
  21100. std::atomic<bool> message_received{false};
  21101. // Refresh token on error
  21102. sse.on_error(
  21103. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21104. sse.on_message([&](const sse::SSEMessage &msg) {
  21105. if (msg.data == "authenticated") { message_received.store(true); }
  21106. });
  21107. sse.set_reconnect_interval(100);
  21108. sse.set_max_reconnect_attempts(3);
  21109. sse.start_async();
  21110. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21111. sse.stop();
  21112. // Should have reconnected after 401 and succeeded with new token
  21113. EXPECT_GE(connection_count.load(), 2);
  21114. EXPECT_TRUE(message_received.load());
  21115. }
  21116. TEST(Issue2318Test, EmptyHostString) {
  21117. {
  21118. httplib::Client cli_empty("", PORT);
  21119. auto res = cli_empty.Get("/");
  21120. ASSERT_FALSE(res);
  21121. EXPECT_EQ(httplib::Error::Connection, res.error());
  21122. }
  21123. {
  21124. httplib::Client cli(" ", PORT);
  21125. auto res = cli.Get("/");
  21126. ASSERT_FALSE(res);
  21127. EXPECT_EQ(httplib::Error::Connection, res.error());
  21128. }
  21129. }
  21130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21131. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21132. Server svr;
  21133. // Set a small payload limit (1KB)
  21134. svr.set_payload_max_length(1024);
  21135. svr.Post("/test", [&](const Request &req, Response &res) {
  21136. res.set_content("Body size: " + std::to_string(req.body.size()),
  21137. "text/plain");
  21138. });
  21139. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21140. auto se = detail::scope_exit([&] {
  21141. svr.stop();
  21142. listen_thread.join();
  21143. });
  21144. svr.wait_until_ready();
  21145. // Create data that compresses well but exceeds limit when decompressed
  21146. // 8KB of repeated null bytes compresses to a very small size
  21147. std::string original_data(8 * 1024, '\0');
  21148. // Compress the data using gzip
  21149. std::string compressed_data;
  21150. detail::gzip_compressor compressor;
  21151. compressor.compress(original_data.data(), original_data.size(), true,
  21152. [&](const char *data, size_t size) {
  21153. compressed_data.append(data, size);
  21154. return true;
  21155. });
  21156. // Verify compression worked (compressed should be much smaller)
  21157. ASSERT_LT(compressed_data.size(), original_data.size());
  21158. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21159. // Send compressed data with Content-Encoding: gzip
  21160. Client cli(HOST, PORT);
  21161. Headers headers = {{"Content-Encoding", "gzip"}};
  21162. auto res =
  21163. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21164. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21166. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21167. }
  21168. #endif
  21169. // ============================================================================
  21170. // OpenSSL-Specific Tests
  21171. // ============================================================================
  21172. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21173. X509 *readCertificate(const std::string &strFileName) {
  21174. std::ifstream inStream(strFileName);
  21175. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21176. std::istreambuf_iterator<char>());
  21177. if (strCertPEM.empty()) return (nullptr);
  21178. BIO *pbCert = BIO_new(BIO_s_mem());
  21179. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21180. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21181. BIO_free(pbCert);
  21182. return (pCert);
  21183. }
  21184. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21185. std::ifstream inStream(strFileName);
  21186. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21187. std::istreambuf_iterator<char>());
  21188. if (strPrivateKeyPEM.empty()) return (nullptr);
  21189. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21190. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21191. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21192. BIO_free(pbPrivKey);
  21193. return (pPrivateKey);
  21194. }
  21195. TEST(BindServerTest, UpdateCerts) {
  21196. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21197. int port = svr.bind_to_any_port("0.0.0.0");
  21198. ASSERT_TRUE(svr.is_valid());
  21199. ASSERT_TRUE(port > 0);
  21200. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21201. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21202. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21203. ASSERT_TRUE(cert != nullptr);
  21204. ASSERT_TRUE(ca_cert != nullptr);
  21205. ASSERT_TRUE(key != nullptr);
  21206. X509_STORE *cert_store = X509_STORE_new();
  21207. X509_STORE_add_cert(cert_store, ca_cert);
  21208. // svr.update_certs(cert, key, cert_store); // deprecated
  21209. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21210. CLIENT_CA_CERT_FILE);
  21211. ASSERT_TRUE(svr.is_valid());
  21212. svr.stop();
  21213. X509_STORE_free(cert_store);
  21214. X509_free(cert);
  21215. X509_free(ca_cert);
  21216. EVP_PKEY_free(key);
  21217. }
  21218. // Test that update_certs() updates client CA list correctly
  21219. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21220. // Start with file-based constructor
  21221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21222. ASSERT_TRUE(svr.is_valid());
  21223. // Initially no client CA list should be set
  21224. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21225. ASSERT_TRUE(ssl_ctx != nullptr);
  21226. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21227. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21228. EXPECT_EQ(0, count_before);
  21229. // Now update with client CA (PEM string)
  21230. std::string cert_pem, key_pem, ca_pem;
  21231. read_file(SERVER_CERT_FILE, cert_pem);
  21232. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21233. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21234. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21235. ASSERT_TRUE(svr.is_valid());
  21236. // Now client CA list should be set
  21237. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21238. ASSERT_TRUE(ca_list_after != nullptr);
  21239. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21240. }
  21241. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21242. // Test that the file-path SSLServer constructor properly sets the client CA
  21243. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21244. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21245. ASSERT_TRUE(svr.is_valid());
  21246. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21247. ASSERT_TRUE(ssl_ctx != nullptr);
  21248. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21249. ASSERT_TRUE(ca_list != nullptr);
  21250. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21251. }
  21252. #endif
  21253. // ============================================================================
  21254. // MbedTLS-Specific Tests
  21255. // ============================================================================
  21256. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21257. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21258. using namespace httplib::tls;
  21259. // Track if callback was invoked
  21260. bool callback_invoked = false;
  21261. // The callback receives void* ctx which is actually MbedTlsContext*
  21262. // We can access the mbedtls_ssl_config via the context
  21263. auto setup_callback = [&callback_invoked](void *ctx) {
  21264. callback_invoked = true;
  21265. // Cast to MbedTlsContext* to access the ssl config
  21266. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21267. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21268. // Use static variables to hold certificate data (simplified for test)
  21269. static mbedtls_x509_crt own_cert;
  21270. static mbedtls_pk_context own_key;
  21271. static mbedtls_x509_crt ca_chain;
  21272. static bool initialized = false;
  21273. if (!initialized) {
  21274. mbedtls_x509_crt_init(&own_cert);
  21275. mbedtls_pk_init(&own_key);
  21276. mbedtls_x509_crt_init(&ca_chain);
  21277. // Load server certificate
  21278. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21279. return false;
  21280. }
  21281. // Load server private key.
  21282. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21283. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21284. #if MBEDTLS_VERSION_MAJOR == 3
  21285. ,
  21286. mbedtls_ctr_drbg_random, nullptr
  21287. #endif
  21288. ) != 0) {
  21289. return false;
  21290. }
  21291. // Load CA chain for client verification
  21292. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21293. return false;
  21294. }
  21295. initialized = true;
  21296. }
  21297. // Configure the SSL config
  21298. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21299. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21300. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21301. // Set minimum TLS version using mbedTLS native API
  21302. #if MBEDTLS_VERSION_MAJOR >= 3
  21303. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21304. #else
  21305. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21306. MBEDTLS_SSL_MINOR_VERSION_3);
  21307. #endif
  21308. return true;
  21309. };
  21310. SSLServer svr(setup_callback);
  21311. ASSERT_TRUE(svr.is_valid());
  21312. ASSERT_TRUE(callback_invoked);
  21313. svr.Get("/test", [&](const Request &req, Response &res) {
  21314. res.set_content("test", "text/plain");
  21315. auto cert = req.peer_cert();
  21316. ASSERT_TRUE(static_cast<bool>(cert));
  21317. auto common_name = cert.subject_cn();
  21318. EXPECT_EQ("Common Name", common_name);
  21319. });
  21320. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21321. auto se = detail::scope_exit([&] {
  21322. svr.stop();
  21323. t.join();
  21324. ASSERT_FALSE(svr.is_running());
  21325. });
  21326. svr.wait_until_ready();
  21327. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21328. cli.enable_server_certificate_verification(false);
  21329. cli.set_connection_timeout(30);
  21330. auto res = cli.Get("/test");
  21331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21332. ASSERT_EQ(StatusCode::OK_200, res->status);
  21333. }
  21334. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21335. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21336. // keep-alive SSL session, which reads through that config in
  21337. // mbedtls_ssl_close_notify.
  21338. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21340. ASSERT_TRUE(svr.is_valid());
  21341. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21342. res.set_content("test", "text/plain");
  21343. });
  21344. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21345. auto se = detail::scope_exit([&] {
  21346. svr.stop();
  21347. t.join();
  21348. ASSERT_FALSE(svr.is_running());
  21349. });
  21350. svr.wait_until_ready();
  21351. {
  21352. SSLClient cli(HOST, PORT);
  21353. cli.enable_server_certificate_verification(false);
  21354. cli.set_keep_alive(true);
  21355. auto res = cli.Get("/test");
  21356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21357. ASSERT_EQ(StatusCode::OK_200, res->status);
  21358. // cli is destructed here with the keep-alive SSL session still open.
  21359. }
  21360. }
  21361. #endif
  21362. // WebSocket Tests
  21363. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21364. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21365. // defining the meaning of these bits has been negotiated.
  21366. auto make_frame = [](uint8_t first_byte) {
  21367. std::string frame;
  21368. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21369. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21370. frame += "Hello";
  21371. return frame;
  21372. };
  21373. // RSV1 set (0x40)
  21374. {
  21375. detail::BufferStream strm;
  21376. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21377. ws::Opcode opcode;
  21378. std::string payload;
  21379. bool fin;
  21380. EXPECT_EQ(
  21381. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21382. ws::impl::FrameRead::Fail);
  21383. }
  21384. // RSV2 set (0x20)
  21385. {
  21386. detail::BufferStream strm;
  21387. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21388. ws::Opcode opcode;
  21389. std::string payload;
  21390. bool fin;
  21391. EXPECT_EQ(
  21392. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21393. ws::impl::FrameRead::Fail);
  21394. }
  21395. // RSV3 set (0x10)
  21396. {
  21397. detail::BufferStream strm;
  21398. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21399. ws::Opcode opcode;
  21400. std::string payload;
  21401. bool fin;
  21402. EXPECT_EQ(
  21403. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21404. ws::impl::FrameRead::Fail);
  21405. }
  21406. // No RSV bits set - should succeed
  21407. {
  21408. detail::BufferStream strm;
  21409. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21410. ws::Opcode opcode;
  21411. std::string payload;
  21412. bool fin;
  21413. EXPECT_EQ(
  21414. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21415. ws::impl::FrameRead::Ok);
  21416. EXPECT_EQ(ws::Opcode::Text, opcode);
  21417. EXPECT_EQ("Hello", payload);
  21418. EXPECT_TRUE(fin);
  21419. }
  21420. }
  21421. TEST(WebSocketTest, ControlFrameValidation) {
  21422. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21423. // payload length <= 125.
  21424. // Ping with FIN=0 - must be rejected
  21425. {
  21426. detail::BufferStream strm;
  21427. std::string frame;
  21428. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21429. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21430. strm.write(frame.data(), frame.size());
  21431. ws::Opcode opcode;
  21432. std::string payload;
  21433. bool fin;
  21434. EXPECT_EQ(
  21435. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21436. ws::impl::FrameRead::Fail);
  21437. }
  21438. // Close with FIN=0 - must be rejected
  21439. {
  21440. detail::BufferStream strm;
  21441. std::string frame;
  21442. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21443. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21444. strm.write(frame.data(), frame.size());
  21445. ws::Opcode opcode;
  21446. std::string payload;
  21447. bool fin;
  21448. EXPECT_EQ(
  21449. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21450. ws::impl::FrameRead::Fail);
  21451. }
  21452. // Ping with payload_len=126 (extended length) - must be rejected
  21453. {
  21454. detail::BufferStream strm;
  21455. std::string frame;
  21456. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21457. frame += static_cast<char>(126); // payload_len=126 (>125)
  21458. frame += static_cast<char>(0x00); // extended length high byte
  21459. frame += static_cast<char>(126); // extended length low byte
  21460. frame += std::string(126, 'x');
  21461. strm.write(frame.data(), frame.size());
  21462. ws::Opcode opcode;
  21463. std::string payload;
  21464. bool fin;
  21465. EXPECT_EQ(
  21466. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21467. ws::impl::FrameRead::Fail);
  21468. }
  21469. // Ping with FIN=1 and payload_len=125 - should succeed
  21470. {
  21471. detail::BufferStream strm;
  21472. std::string frame;
  21473. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21474. frame += static_cast<char>(125); // payload_len=125
  21475. frame += std::string(125, 'x');
  21476. strm.write(frame.data(), frame.size());
  21477. ws::Opcode opcode;
  21478. std::string payload;
  21479. bool fin;
  21480. EXPECT_EQ(
  21481. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21482. ws::impl::FrameRead::Ok);
  21483. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21484. EXPECT_EQ(125u, payload.size());
  21485. EXPECT_TRUE(fin);
  21486. }
  21487. }
  21488. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21489. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21490. // length MUST be 0.
  21491. // MSB set - must be rejected
  21492. {
  21493. detail::BufferStream strm;
  21494. std::string frame;
  21495. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21496. frame += static_cast<char>(127); // 64-bit extended length
  21497. frame += static_cast<char>(0x80); // MSB set (invalid)
  21498. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21499. strm.write(frame.data(), frame.size());
  21500. ws::Opcode opcode;
  21501. std::string payload;
  21502. bool fin;
  21503. EXPECT_EQ(
  21504. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21505. ws::impl::FrameRead::Fail);
  21506. }
  21507. // MSB clear - should pass length parsing (will be rejected by max_len,
  21508. // but that's a different check; use a small length to verify)
  21509. {
  21510. detail::BufferStream strm;
  21511. std::string frame;
  21512. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21513. frame += static_cast<char>(127); // 64-bit extended length
  21514. frame += std::string(7, '\0'); // high bytes = 0
  21515. frame += static_cast<char>(0x03); // length = 3
  21516. frame += "abc";
  21517. strm.write(frame.data(), frame.size());
  21518. ws::Opcode opcode;
  21519. std::string payload;
  21520. bool fin;
  21521. EXPECT_EQ(
  21522. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21523. ws::impl::FrameRead::Ok);
  21524. EXPECT_EQ(ws::Opcode::Text, opcode);
  21525. EXPECT_EQ("abc", payload);
  21526. }
  21527. }
  21528. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21529. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21530. // Valid UTF-8
  21531. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21532. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21533. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21534. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21535. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21536. // Invalid UTF-8
  21537. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21538. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21539. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21540. EXPECT_FALSE(
  21541. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21542. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21543. }
  21544. TEST(WebSocketTest, ConnectAndDisconnect) {
  21545. Server svr;
  21546. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21547. std::string msg;
  21548. while (ws.read(msg)) {}
  21549. });
  21550. auto port = svr.bind_to_any_port(HOST);
  21551. std::thread t([&]() { svr.listen_after_bind(); });
  21552. svr.wait_until_ready();
  21553. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21554. auto res = client.connect();
  21555. ASSERT_TRUE(res);
  21556. EXPECT_EQ(Error::Success, res.error());
  21557. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21558. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21559. EXPECT_TRUE(client.is_open());
  21560. client.close();
  21561. EXPECT_FALSE(client.is_open());
  21562. svr.stop();
  21563. t.join();
  21564. }
  21565. TEST(WebSocketTest, ValidURL) {
  21566. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21567. EXPECT_TRUE(ws1.is_valid());
  21568. ws::WebSocketClient ws2("ws://example.com/path");
  21569. EXPECT_TRUE(ws2.is_valid());
  21570. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21571. EXPECT_TRUE(ws3.is_valid());
  21572. #ifdef CPPHTTPLIB_SSL_ENABLED
  21573. ws::WebSocketClient wss1("wss://example.com/path");
  21574. EXPECT_TRUE(wss1.is_valid());
  21575. ws::WebSocketClient wss2("wss://example.com:443/path");
  21576. EXPECT_TRUE(wss2.is_valid());
  21577. #endif
  21578. }
  21579. TEST(WebSocketTest, InvalidURL) {
  21580. // No scheme
  21581. ws::WebSocketClient ws1("localhost:8080/path");
  21582. EXPECT_FALSE(ws1.is_valid());
  21583. // No path
  21584. ws::WebSocketClient ws2("ws://localhost:8080");
  21585. EXPECT_FALSE(ws2.is_valid());
  21586. // Empty string
  21587. ws::WebSocketClient ws3("");
  21588. EXPECT_FALSE(ws3.is_valid());
  21589. // Missing host
  21590. ws::WebSocketClient ws4("ws://:8080/path");
  21591. EXPECT_FALSE(ws4.is_valid());
  21592. // Port number overflow — should not crash
  21593. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21594. EXPECT_FALSE(ws5.is_valid());
  21595. // Port out of range
  21596. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21597. EXPECT_FALSE(ws6.is_valid());
  21598. }
  21599. TEST(WebSocketTest, UnsupportedScheme) {
  21600. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21601. ws::WebSocketClient ws1("http://localhost:8080/path");
  21602. EXPECT_FALSE(ws1.is_valid());
  21603. ws::WebSocketClient ws2("https://localhost:8080/path");
  21604. EXPECT_FALSE(ws2.is_valid());
  21605. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21606. EXPECT_FALSE(ws3.is_valid());
  21607. #else
  21608. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21609. std::invalid_argument);
  21610. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21611. std::invalid_argument);
  21612. #endif
  21613. }
  21614. TEST(WebSocketTest, ConnectWhenInvalid) {
  21615. ws::WebSocketClient ws("not a valid url");
  21616. EXPECT_FALSE(ws.is_valid());
  21617. auto res = ws.connect();
  21618. EXPECT_FALSE(res);
  21619. EXPECT_EQ(Error::Connection, res.error());
  21620. EXPECT_EQ(-1, res.status());
  21621. }
  21622. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21623. // Grab a port that is free, then close it again so nothing listens there
  21624. Server svr;
  21625. auto port = svr.bind_to_any_port(HOST);
  21626. svr.stop();
  21627. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21628. auto res = client.connect();
  21629. ASSERT_FALSE(res);
  21630. EXPECT_EQ(Error::Connection, res.error());
  21631. EXPECT_EQ(-1, res.status());
  21632. }
  21633. TEST(WebSocketTest, DefaultPort) {
  21634. ws::WebSocketClient ws1("ws://example.com/path");
  21635. EXPECT_TRUE(ws1.is_valid());
  21636. // ws:// defaults to port 80 (verified by successful parse)
  21637. #ifdef CPPHTTPLIB_SSL_ENABLED
  21638. ws::WebSocketClient ws2("wss://example.com/path");
  21639. EXPECT_TRUE(ws2.is_valid());
  21640. // wss:// defaults to port 443 (verified by successful parse)
  21641. #endif
  21642. }
  21643. TEST(WebSocketTest, IPv6LiteralAddress) {
  21644. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21645. EXPECT_TRUE(ws1.is_valid());
  21646. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21647. EXPECT_TRUE(ws2.is_valid());
  21648. }
  21649. TEST(WebSocketTest, ComplexPath) {
  21650. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21651. EXPECT_TRUE(ws1.is_valid());
  21652. ws::WebSocketClient ws2("ws://localhost:8080/");
  21653. EXPECT_TRUE(ws2.is_valid());
  21654. }
  21655. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21656. Server svr;
  21657. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21658. std::string msg;
  21659. while (ws.read(msg)) {}
  21660. });
  21661. auto port = svr.bind_to_any_port(HOST);
  21662. std::thread t([&]() { svr.listen_after_bind(); });
  21663. svr.wait_until_ready();
  21664. auto another_host = "example.com";
  21665. auto wrong_ip = "192.0.2.1";
  21666. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21667. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21668. ASSERT_TRUE(client.connect());
  21669. EXPECT_TRUE(client.is_open());
  21670. client.close();
  21671. svr.stop();
  21672. t.join();
  21673. }
  21674. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21675. Server svr;
  21676. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21677. std::string msg;
  21678. while (ws.read(msg)) {}
  21679. });
  21680. auto port = svr.bind_to_any_port(HOST);
  21681. std::thread t([&]() { svr.listen_after_bind(); });
  21682. svr.wait_until_ready();
  21683. auto wrong_ip = "192.0.2.1";
  21684. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21685. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21686. client.set_connection_timeout(1);
  21687. client.set_read_timeout(1);
  21688. client.set_write_timeout(1);
  21689. EXPECT_FALSE(client.connect());
  21690. EXPECT_FALSE(client.is_open());
  21691. svr.stop();
  21692. t.join();
  21693. }
  21694. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21695. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21696. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21697. // (RFC 6761) is only a map key and the Host header value.
  21698. auto host = "target.invalid";
  21699. Server svr;
  21700. std::string received_host;
  21701. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21702. received_host = req.get_header_value("Host");
  21703. std::string msg;
  21704. while (ws.read(msg)) {}
  21705. });
  21706. auto port = svr.bind_to_any_port(HOST);
  21707. std::thread t([&]() { svr.listen_after_bind(); });
  21708. // ASSERT_* below returns from the test body, which would leave t joinable
  21709. // and make ~thread call std::terminate.
  21710. auto se = detail::scope_exit([&] {
  21711. svr.stop();
  21712. if (t.joinable()) { t.join(); }
  21713. });
  21714. svr.wait_until_ready();
  21715. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21716. std::to_string(port) + "/ws");
  21717. client.set_hostname_addr_map({{host, HOST}});
  21718. ASSERT_TRUE(client.connect());
  21719. EXPECT_TRUE(client.is_open());
  21720. client.close();
  21721. svr.stop();
  21722. t.join();
  21723. // The mapping only redirects the connection; the identity stays host_.
  21724. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21725. }
  21726. class WebSocketIntegrationTest : public ::testing::Test {
  21727. protected:
  21728. void SetUp() override {
  21729. server_ = httplib::detail::make_unique<Server>();
  21730. setup_server();
  21731. start_server();
  21732. }
  21733. void TearDown() override {
  21734. server_->stop();
  21735. if (server_thread_.joinable()) { server_thread_.join(); }
  21736. }
  21737. void setup_server() {
  21738. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21739. std::string msg;
  21740. ws::ReadResult ret;
  21741. while ((ret = ws.read(msg))) {
  21742. if (ret == ws::Binary) {
  21743. ws.send(msg.data(), msg.size());
  21744. } else {
  21745. ws.send(msg);
  21746. }
  21747. }
  21748. });
  21749. server_->WebSocket("/ws-echo-string",
  21750. [](const Request &, ws::WebSocket &ws) {
  21751. std::string msg;
  21752. while (ws.read(msg)) {
  21753. ws.send("echo: " + msg);
  21754. }
  21755. });
  21756. server_->WebSocket(
  21757. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21758. // Echo back request metadata
  21759. ws.send("path:" + req.path);
  21760. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21761. std::string msg;
  21762. while (ws.read(msg)) {}
  21763. });
  21764. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21765. std::string msg;
  21766. ws.read(msg); // wait for a message
  21767. ws.close();
  21768. });
  21769. server_->WebSocket("/ws-close-status",
  21770. [](const Request &, ws::WebSocket &ws) {
  21771. std::string msg;
  21772. ws.read(msg); // wait for a message
  21773. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21774. });
  21775. server_->WebSocket(
  21776. "/ws-subprotocol",
  21777. [](const Request &, ws::WebSocket &ws) {
  21778. std::string msg;
  21779. while (ws.read(msg)) {
  21780. ws.send(msg);
  21781. }
  21782. },
  21783. [](const std::vector<std::string> &protocols) -> std::string {
  21784. for (const auto &p : protocols) {
  21785. if (p == "graphql-ws") { return p; }
  21786. }
  21787. return "";
  21788. });
  21789. server_->WebSocket(
  21790. "/ws-subprotocol-unoffered",
  21791. [](const Request &, ws::WebSocket &ws) {
  21792. std::string msg;
  21793. while (ws.read(msg)) {
  21794. ws.send(msg);
  21795. }
  21796. },
  21797. [](const std::vector<std::string> &) -> std::string {
  21798. return "admin";
  21799. });
  21800. }
  21801. void start_server() {
  21802. port_ = server_->bind_to_any_port(HOST);
  21803. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21804. server_->wait_until_ready();
  21805. }
  21806. std::unique_ptr<Server> server_;
  21807. std::thread server_thread_;
  21808. int port_ = 0;
  21809. };
  21810. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21811. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21812. "/ws-echo");
  21813. ASSERT_TRUE(client.connect());
  21814. ASSERT_TRUE(client.is_open());
  21815. ASSERT_TRUE(client.send("Hello WebSocket"));
  21816. std::string msg;
  21817. EXPECT_EQ(ws::Text, client.read(msg));
  21818. EXPECT_EQ("Hello WebSocket", msg);
  21819. client.close();
  21820. }
  21821. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21822. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21823. "/ws-echo");
  21824. ASSERT_TRUE(client.connect());
  21825. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21826. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21827. std::string msg;
  21828. EXPECT_EQ(ws::Binary, client.read(msg));
  21829. EXPECT_EQ(binary_data, msg);
  21830. client.close();
  21831. }
  21832. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21833. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21834. "/ws-echo");
  21835. ASSERT_TRUE(client.connect());
  21836. for (int i = 0; i < 10; i++) {
  21837. auto text = "message " + std::to_string(i);
  21838. ASSERT_TRUE(client.send(text));
  21839. std::string msg;
  21840. ASSERT_TRUE(client.read(msg));
  21841. EXPECT_EQ(text, msg);
  21842. }
  21843. client.close();
  21844. }
  21845. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21846. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21847. "/ws-close");
  21848. ASSERT_TRUE(client.connect());
  21849. // Send a message to trigger the server to close
  21850. ASSERT_TRUE(client.send("trigger close"));
  21851. // The server will close, so read should return false
  21852. std::string msg;
  21853. EXPECT_FALSE(client.read(msg));
  21854. EXPECT_FALSE(client.is_open());
  21855. }
  21856. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21857. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21858. "/ws-echo");
  21859. ASSERT_TRUE(client.connect());
  21860. // 128KB message
  21861. std::string large_data(128 * 1024, 'X');
  21862. ASSERT_TRUE(client.send(large_data));
  21863. std::string msg;
  21864. ASSERT_TRUE(client.read(msg));
  21865. EXPECT_EQ(large_data, msg);
  21866. client.close();
  21867. }
  21868. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21869. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21870. "/ws-echo");
  21871. ASSERT_TRUE(client.connect());
  21872. const int num_threads = 4;
  21873. std::vector<std::thread> threads;
  21874. std::atomic<int> send_count{0};
  21875. for (int t = 0; t < num_threads; t++) {
  21876. threads.emplace_back([&client, &send_count, t]() {
  21877. for (int i = 0; i < 5; i++) {
  21878. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21879. if (client.send(text)) { send_count++; }
  21880. }
  21881. });
  21882. }
  21883. for (auto &th : threads) {
  21884. th.join();
  21885. }
  21886. int received = 0;
  21887. std::string msg;
  21888. while (received < send_count.load()) {
  21889. if (!client.read(msg)) { break; }
  21890. received++;
  21891. }
  21892. EXPECT_EQ(send_count.load(), received);
  21893. client.close();
  21894. }
  21895. TEST_F(WebSocketIntegrationTest, ReadString) {
  21896. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21897. "/ws-echo-string");
  21898. ASSERT_TRUE(client.connect());
  21899. ASSERT_TRUE(client.send("hello"));
  21900. std::string msg;
  21901. ASSERT_TRUE(client.read(msg));
  21902. EXPECT_EQ("echo: hello", msg);
  21903. ASSERT_TRUE(client.send("world"));
  21904. ASSERT_TRUE(client.read(msg));
  21905. EXPECT_EQ("echo: world", msg);
  21906. client.close();
  21907. }
  21908. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21909. Headers headers = {{"X-Test-Header", "test-value"}};
  21910. ws::WebSocketClient client(
  21911. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21912. ASSERT_TRUE(client.connect());
  21913. std::string msg;
  21914. ASSERT_TRUE(client.read(msg));
  21915. EXPECT_EQ("path:/ws-request-info", msg);
  21916. ASSERT_TRUE(client.read(msg));
  21917. EXPECT_EQ("header:test-value", msg);
  21918. client.close();
  21919. }
  21920. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21921. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21922. "/ws-echo");
  21923. client.set_read_timeout(1, 0); // 1 second
  21924. ASSERT_TRUE(client.connect());
  21925. // Don't send anything — server echo handler waits for a message, so read()
  21926. // should time out. The connection survives it: nothing was consumed.
  21927. std::string msg;
  21928. EXPECT_EQ(client.read(msg), ws::Timeout);
  21929. EXPECT_TRUE(client.is_open());
  21930. // And it is still usable afterwards.
  21931. EXPECT_TRUE(client.send("after timeout"));
  21932. EXPECT_EQ(client.read(msg), ws::Text);
  21933. EXPECT_EQ(msg, "after timeout");
  21934. }
  21935. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21936. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21937. "/ws-echo");
  21938. client.set_read_timeout(1, 0);
  21939. ASSERT_TRUE(client.connect());
  21940. ASSERT_TRUE(client.send("first"));
  21941. std::string msg;
  21942. ASSERT_EQ(client.read(msg), ws::Text);
  21943. ASSERT_EQ(msg, "first");
  21944. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21945. // not be used with a read timeout: it would reprocess the previous message.
  21946. EXPECT_EQ(client.read(msg), ws::Timeout);
  21947. EXPECT_EQ(msg, "first");
  21948. }
  21949. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21950. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21951. "/ws-echo");
  21952. ASSERT_TRUE(client.connect());
  21953. // Setting it once the connection is open reaches the live stream, not just
  21954. // the seed for the next connect().
  21955. client.set_read_timeout(1, 0);
  21956. std::string msg;
  21957. EXPECT_EQ(client.read(msg), ws::Timeout);
  21958. EXPECT_TRUE(client.is_open());
  21959. }
  21960. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21961. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21962. "/ws-echo");
  21963. client.set_read_timeout(5, 0);
  21964. ASSERT_TRUE(client.connect());
  21965. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21966. // The server should reject it and close the connection.
  21967. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21968. client.send(oversized);
  21969. // The server's read() should have failed due to payload limit,
  21970. // so our read() should return false (connection closed).
  21971. std::string msg;
  21972. EXPECT_FALSE(client.read(msg));
  21973. }
  21974. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21975. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21976. "/ws-echo");
  21977. client.set_read_timeout(10, 0);
  21978. ASSERT_TRUE(client.connect());
  21979. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21980. // This should succeed.
  21981. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21982. ASSERT_TRUE(client.send(at_limit));
  21983. std::string msg;
  21984. ASSERT_TRUE(client.read(msg));
  21985. EXPECT_EQ(at_limit.size(), msg.size());
  21986. client.close();
  21987. }
  21988. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21989. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21990. "/nonexistent");
  21991. auto res = client.connect();
  21992. EXPECT_FALSE(res);
  21993. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21994. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21995. EXPECT_FALSE(client.is_open());
  21996. }
  21997. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21998. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21999. "/ws-echo");
  22000. ASSERT_TRUE(client.connect());
  22001. ASSERT_TRUE(client.send(""));
  22002. std::string msg;
  22003. EXPECT_EQ(ws::Text, client.read(msg));
  22004. EXPECT_EQ("", msg);
  22005. client.close();
  22006. }
  22007. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22008. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22009. "/ws-echo");
  22010. // First connection
  22011. ASSERT_TRUE(client.connect());
  22012. ASSERT_TRUE(client.send("first"));
  22013. std::string msg;
  22014. ASSERT_TRUE(client.read(msg));
  22015. EXPECT_EQ("first", msg);
  22016. client.close();
  22017. EXPECT_FALSE(client.is_open());
  22018. // Reconnect using the same client object
  22019. ASSERT_TRUE(client.connect());
  22020. ASSERT_TRUE(client.is_open());
  22021. ASSERT_TRUE(client.send("second"));
  22022. ASSERT_TRUE(client.read(msg));
  22023. EXPECT_EQ("second", msg);
  22024. client.close();
  22025. }
  22026. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22027. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22028. "/ws-close-status");
  22029. ASSERT_TRUE(client.connect());
  22030. // Trigger the server to close with GoingAway status
  22031. ASSERT_TRUE(client.send("trigger"));
  22032. // read() should return false after receiving the close frame
  22033. std::string msg;
  22034. EXPECT_FALSE(client.read(msg));
  22035. EXPECT_FALSE(client.is_open());
  22036. }
  22037. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22039. "/ws-echo");
  22040. ASSERT_TRUE(client.connect());
  22041. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22042. EXPECT_FALSE(client.is_open());
  22043. }
  22044. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22045. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22046. ws::WebSocketClient client(
  22047. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22048. ASSERT_TRUE(client.connect());
  22049. // Server should have selected graphql-ws
  22050. EXPECT_EQ("graphql-ws", client.subprotocol());
  22051. client.close();
  22052. }
  22053. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22054. Headers headers;
  22055. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22056. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22057. ws::WebSocketClient client(
  22058. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22059. ASSERT_TRUE(client.connect());
  22060. // The offer on the second field line counts too, so graphql-ws is selected
  22061. EXPECT_EQ("graphql-ws", client.subprotocol());
  22062. client.close();
  22063. }
  22064. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22065. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22066. ws::WebSocketClient client(
  22067. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22068. ASSERT_TRUE(client.connect());
  22069. // Server should not have selected any subprotocol
  22070. EXPECT_TRUE(client.subprotocol().empty());
  22071. client.close();
  22072. }
  22073. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22074. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22075. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22076. "/ws-subprotocol-unoffered",
  22077. headers);
  22078. ASSERT_TRUE(client.connect());
  22079. EXPECT_TRUE(client.subprotocol().empty());
  22080. client.close();
  22081. }
  22082. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22083. // Connect without requesting any subprotocol
  22084. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22085. "/ws-subprotocol");
  22086. ASSERT_TRUE(client.connect());
  22087. EXPECT_TRUE(client.subprotocol().empty());
  22088. client.close();
  22089. }
  22090. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22091. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22092. "/ws-echo");
  22093. client.set_tcp_nodelay(true);
  22094. client.set_connection_timeout(3, 0);
  22095. bool socket_options_called = false;
  22096. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22097. ASSERT_TRUE(client.connect());
  22098. ASSERT_TRUE(client.is_open());
  22099. EXPECT_TRUE(socket_options_called);
  22100. ASSERT_TRUE(client.send("hello"));
  22101. std::string msg;
  22102. auto result = client.read(msg);
  22103. EXPECT_EQ(result, ws::ReadResult::Text);
  22104. EXPECT_EQ(msg, "hello");
  22105. client.close();
  22106. }
  22107. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22108. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22109. "/ws-echo");
  22110. client.set_connection_timeout(std::chrono::seconds(3));
  22111. client.set_write_timeout(std::chrono::seconds(3));
  22112. // A sub-second remainder exercises the seconds/microseconds split.
  22113. client.set_read_timeout(std::chrono::milliseconds(1500));
  22114. ASSERT_TRUE(client.connect());
  22115. auto start = std::chrono::steady_clock::now();
  22116. std::string msg;
  22117. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22118. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22119. std::chrono::steady_clock::now() - start)
  22120. .count();
  22121. // Above 1s so that dropping the microseconds half of the split fails here.
  22122. // Ignoring the setter altogether would not reach this line at all: a client
  22123. // waits forever by default.
  22124. EXPECT_GE(elapsed, 1400);
  22125. EXPECT_LT(elapsed, 30000);
  22126. }
  22127. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22128. Server svr;
  22129. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22130. if (!req.has_header("Authorization")) {
  22131. res.status = StatusCode::Unauthorized_401;
  22132. res.set_content("Unauthorized", "text/plain");
  22133. return Server::HandlerResponse::Handled;
  22134. }
  22135. return Server::HandlerResponse::Unhandled;
  22136. });
  22137. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22138. std::string msg;
  22139. while (ws.read(msg)) {
  22140. ws.send(msg);
  22141. }
  22142. });
  22143. auto port = svr.bind_to_any_port("localhost");
  22144. std::thread t([&]() { svr.listen_after_bind(); });
  22145. svr.wait_until_ready();
  22146. // Without Authorization header - should be rejected before upgrade
  22147. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22148. EXPECT_FALSE(client1.connect());
  22149. // The rejection is framed like any other HTTP response
  22150. {
  22151. Client cli("localhost", port);
  22152. Headers headers = {{"Upgrade", "websocket"},
  22153. {"Connection", "Upgrade"},
  22154. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22155. {"Sec-WebSocket-Version", "13"}};
  22156. auto res = cli.Get("/ws", headers);
  22157. ASSERT_TRUE(res);
  22158. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22159. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22160. EXPECT_EQ("Unauthorized", res->body);
  22161. }
  22162. // With Authorization header - should succeed
  22163. Headers headers = {{"Authorization", "Bearer token123"}};
  22164. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22165. headers);
  22166. ASSERT_TRUE(client2.connect());
  22167. ASSERT_TRUE(client2.send("hello"));
  22168. std::string msg;
  22169. ASSERT_TRUE(client2.read(msg));
  22170. EXPECT_EQ("hello", msg);
  22171. client2.close();
  22172. svr.stop();
  22173. t.join();
  22174. }
  22175. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22176. Server svr;
  22177. std::atomic<int> pre_request_calls{0};
  22178. std::atomic<bool> route_matched{false};
  22179. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22180. pre_request_calls++;
  22181. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22182. if (req.get_header_value("Authorization") != "Bearer token123") {
  22183. res.status = StatusCode::Unauthorized_401;
  22184. res.set_content("Unauthorized", "text/plain");
  22185. return Server::HandlerResponse::Handled;
  22186. }
  22187. return Server::HandlerResponse::Unhandled;
  22188. });
  22189. std::atomic<bool> handler_called{false};
  22190. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22191. handler_called = true;
  22192. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22193. });
  22194. auto port = svr.bind_to_any_port("localhost");
  22195. std::thread t([&]() { svr.listen_after_bind(); });
  22196. svr.wait_until_ready();
  22197. // Without Authorization header - should be rejected before upgrade
  22198. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22199. "/ws/1");
  22200. EXPECT_FALSE(client1.connect());
  22201. EXPECT_FALSE(handler_called);
  22202. EXPECT_EQ(1, pre_request_calls);
  22203. EXPECT_TRUE(route_matched);
  22204. // The rejection is an ordinary HTTP response, not a protocol switch
  22205. {
  22206. Client cli("localhost", port);
  22207. Headers headers = {{"Upgrade", "websocket"},
  22208. {"Connection", "Upgrade"},
  22209. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22210. {"Sec-WebSocket-Version", "13"}};
  22211. auto res = cli.Get("/ws/1", headers);
  22212. ASSERT_TRUE(res);
  22213. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22214. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22215. EXPECT_EQ("Unauthorized", res->body);
  22216. }
  22217. EXPECT_FALSE(handler_called);
  22218. // With Authorization header - should succeed
  22219. Headers headers = {{"Authorization", "Bearer token123"}};
  22220. ws::WebSocketClient client2(
  22221. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22222. ASSERT_TRUE(client2.connect());
  22223. std::string msg;
  22224. ASSERT_TRUE(client2.read(msg));
  22225. EXPECT_EQ("/ws/:id 2", msg);
  22226. EXPECT_TRUE(handler_called);
  22227. client2.close();
  22228. svr.stop();
  22229. t.join();
  22230. }
  22231. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22232. Server svr;
  22233. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22234. // A read timeout is how a handler gets control back. Without it, a handler
  22235. // parked in read() can never write on the connection it is reading.
  22236. ws.set_read_timeout(std::chrono::milliseconds(100));
  22237. std::string msg;
  22238. while (ws.is_open()) {
  22239. auto r = ws.read(msg);
  22240. if (r == httplib::ws::Timeout) {
  22241. ws.send("tick");
  22242. continue;
  22243. }
  22244. if (r == httplib::ws::Fail) { break; }
  22245. ws.send(msg);
  22246. }
  22247. });
  22248. auto port = svr.bind_to_any_port("localhost");
  22249. std::thread t([&]() { svr.listen_after_bind(); });
  22250. svr.wait_until_ready();
  22251. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22252. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22253. ASSERT_TRUE(client.connect());
  22254. // The client sends nothing, so anything it receives came out of the
  22255. // handler's timeout path.
  22256. std::string msg;
  22257. ASSERT_EQ(client.read(msg), ws::Text);
  22258. EXPECT_EQ("tick", msg);
  22259. client.close();
  22260. svr.stop();
  22261. t.join();
  22262. }
  22263. // Stream::read may return fewer bytes than asked for. This is that contract at
  22264. // its worst -- one byte per call -- which is what a frame header straddling a
  22265. // read buffer's boundary looks like to the frame parser.
  22266. class WsByteAtATimeStream : public Stream {
  22267. public:
  22268. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22269. bool is_readable() const override { return true; }
  22270. bool wait_readable() const override { return true; }
  22271. bool wait_writable() const override { return true; }
  22272. ssize_t read(char *ptr, size_t size) override {
  22273. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22274. *ptr = data_[pos_++];
  22275. return 1;
  22276. }
  22277. ssize_t write(const char *, size_t size) override {
  22278. return static_cast<ssize_t>(size);
  22279. }
  22280. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22281. ip = "127.0.0.1";
  22282. port = 0;
  22283. }
  22284. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22285. ip = "127.0.0.1";
  22286. port = 0;
  22287. }
  22288. socket_t socket() const override { return INVALID_SOCKET; }
  22289. time_t duration() const override { return 0; }
  22290. private:
  22291. std::string data_;
  22292. size_t pos_ = 0;
  22293. };
  22294. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22295. // The payload uses the 16-bit extended length, so the header, the length
  22296. // and the mask key are all multi-byte fields here. Each used to be read
  22297. // with a single read() call, which fails as soon as one is split. The
  22298. // payload is also a little over one read chunk, so it is read in two.
  22299. std::string body;
  22300. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22301. body += static_cast<char>(i % 251);
  22302. }
  22303. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22304. std::string frame;
  22305. frame += static_cast<char>(0x81); // FIN + Text
  22306. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22307. frame += static_cast<char>(body.size() >> 8);
  22308. frame += static_cast<char>(body.size() & 0xff);
  22309. for (size_t i = 0; i < 4; i++) {
  22310. frame += static_cast<char>(mask[i]);
  22311. }
  22312. for (size_t i = 0; i < body.size(); i++) {
  22313. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22314. }
  22315. WsByteAtATimeStream strm(frame);
  22316. ws::Opcode opcode;
  22317. std::string payload;
  22318. bool fin = false;
  22319. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22320. /*expect_masked=*/true, body.size()),
  22321. ws::impl::FrameRead::Ok);
  22322. EXPECT_TRUE(fin);
  22323. EXPECT_EQ(opcode, ws::Opcode::Text);
  22324. EXPECT_EQ(payload, body);
  22325. }
  22326. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22327. std::string body(2000, 'x');
  22328. std::string frame;
  22329. frame += static_cast<char>(0x82); // FIN + Binary
  22330. frame += static_cast<char>(126); // 16-bit length follows
  22331. frame += static_cast<char>(body.size() >> 8);
  22332. frame += static_cast<char>(body.size() & 0xff);
  22333. frame += body;
  22334. detail::BufferStream strm;
  22335. strm.write(frame.data(), frame.size());
  22336. ws::Opcode opcode;
  22337. std::string payload;
  22338. bool fin;
  22339. EXPECT_EQ(
  22340. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22341. ws::impl::FrameRead::Ok);
  22342. EXPECT_EQ(body, payload);
  22343. }
  22344. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22345. // The header announces the largest payload allowed, and only 3 bytes of it
  22346. // ever arrive.
  22347. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22348. std::string frame;
  22349. frame += static_cast<char>(0x82); // FIN + Binary
  22350. frame += static_cast<char>(127); // 64-bit length follows
  22351. for (int shift = 56; shift >= 0; shift -= 8) {
  22352. frame += static_cast<char>((len >> shift) & 0xff);
  22353. }
  22354. frame += "abc";
  22355. detail::BufferStream strm;
  22356. strm.write(frame.data(), frame.size());
  22357. ws::Opcode opcode;
  22358. std::string payload;
  22359. bool fin;
  22360. EXPECT_EQ(
  22361. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22362. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22363. ws::impl::FrameRead::Fail);
  22364. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22365. }
  22366. TEST(WebSocketTest, QueryStringInHandshake) {
  22367. Server svr;
  22368. std::mutex mtx;
  22369. std::string received_target;
  22370. std::string received_token;
  22371. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22372. {
  22373. std::lock_guard<std::mutex> lock(mtx);
  22374. received_target = req.target;
  22375. if (req.has_param("token")) {
  22376. received_token = req.get_param_value("token");
  22377. }
  22378. }
  22379. std::string msg;
  22380. while (ws.read(msg)) {
  22381. ws.send(msg);
  22382. }
  22383. });
  22384. auto port = svr.bind_to_any_port("localhost");
  22385. std::thread t([&]() { svr.listen_after_bind(); });
  22386. svr.wait_until_ready();
  22387. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22388. "/ws?token=ABC&session=123");
  22389. ASSERT_TRUE(client.connect());
  22390. // Round-trip ensures the handler has run and captured the request.
  22391. ASSERT_TRUE(client.send("hello"));
  22392. std::string msg;
  22393. ASSERT_TRUE(client.read(msg));
  22394. EXPECT_EQ("hello", msg);
  22395. client.close();
  22396. {
  22397. std::lock_guard<std::mutex> lock(mtx);
  22398. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22399. EXPECT_EQ("ABC", received_token);
  22400. }
  22401. svr.stop();
  22402. t.join();
  22403. }
  22404. // Run a handshake against a throwaway server and hand the request the server
  22405. // received back to the caller, so tests can assert on the headers the client
  22406. // actually put on the wire.
  22407. static void capture_websocket_handshake_request(
  22408. const Headers &client_headers,
  22409. std::function<void(const Request &, int port)> verify) {
  22410. Server svr;
  22411. std::mutex mtx;
  22412. Request received;
  22413. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22414. {
  22415. std::lock_guard<std::mutex> lock(mtx);
  22416. received = req;
  22417. }
  22418. std::string msg;
  22419. while (ws.read(msg)) {
  22420. ws.send(msg);
  22421. }
  22422. });
  22423. auto port = svr.bind_to_any_port("localhost");
  22424. std::thread t([&]() { svr.listen_after_bind(); });
  22425. auto se = detail::scope_exit([&] {
  22426. svr.stop();
  22427. t.join();
  22428. });
  22429. svr.wait_until_ready();
  22430. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22431. client_headers);
  22432. ASSERT_TRUE(client.connect());
  22433. ASSERT_TRUE(client.send("hello"));
  22434. std::string msg;
  22435. ASSERT_TRUE(client.read(msg));
  22436. client.close();
  22437. {
  22438. std::lock_guard<std::mutex> lock(mtx);
  22439. verify(received, port);
  22440. }
  22441. }
  22442. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22443. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22444. // Non-default port must be present in the Host header. Default ports
  22445. // (80/443) are omitted; that logic is covered by
  22446. // MakeHostAndPortStringTest.
  22447. EXPECT_EQ("localhost:" + std::to_string(port),
  22448. req.get_header_value("Host"));
  22449. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22450. req.get_header_value("User-Agent"));
  22451. EXPECT_FALSE(req.has_header("Accept"));
  22452. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22453. EXPECT_FALSE(req.has_header("Content-Length"));
  22454. });
  22455. }
  22456. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22457. capture_websocket_handshake_request(
  22458. {{"Host", "example.com"},
  22459. {"User-Agent", "custom-agent"},
  22460. {"X-Custom", "value"}},
  22461. [](const Request &req, int) {
  22462. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22463. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22464. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22465. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22466. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22467. });
  22468. }
  22469. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22470. capture_websocket_handshake_request(
  22471. {{"Upgrade", "bogus"},
  22472. {"Connection", "close"},
  22473. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22474. {"Sec-WebSocket-Version", "8"}},
  22475. [](const Request &req, int) {
  22476. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22477. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22478. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22479. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22480. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22481. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22482. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22483. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22484. req.get_header_value("Sec-WebSocket-Key"));
  22485. });
  22486. }
  22487. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22488. // A header the client refuses to send must abort the handshake before any
  22489. // part of it reaches the wire; a lone request line would otherwise sit in
  22490. // the peer's buffer as a truncated request.
  22491. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22492. ASSERT_NE(INVALID_SOCKET, srv);
  22493. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22494. sockaddr_in addr{};
  22495. addr.sin_family = AF_INET;
  22496. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22497. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22498. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22499. ASSERT_EQ(0, ::listen(srv, 1));
  22500. sockaddr_in bound{};
  22501. socklen_t bound_len = sizeof(bound);
  22502. ASSERT_EQ(
  22503. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22504. auto port = ntohs(bound.sin_port);
  22505. ssize_t received = -1;
  22506. std::thread t([&] {
  22507. // Bound every blocking call so a regression fails the test with a bad
  22508. // value instead of hanging the suite.
  22509. fd_set rfds;
  22510. FD_ZERO(&rfds);
  22511. FD_SET(srv, &rfds);
  22512. timeval tv{5, 0};
  22513. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22514. 0) {
  22515. return;
  22516. }
  22517. sockaddr_in cli_addr{};
  22518. socklen_t cli_len = sizeof(cli_addr);
  22519. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22520. if (cli == INVALID_SOCKET) { return; }
  22521. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22522. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22523. char buf[4096];
  22524. received = ::recv(cli, buf, sizeof(buf), 0);
  22525. });
  22526. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22527. // connect() has already shut the socket down by the time it returns false,
  22528. // so the peer sees EOF without waiting for the client to be destroyed.
  22529. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22530. {{"X-Bad", "a\r\nInjected: 1"}});
  22531. EXPECT_FALSE(client.connect());
  22532. t.join();
  22533. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22534. EXPECT_EQ(0, received);
  22535. }
  22536. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22537. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22538. // contains "upgrade" as a substring is a different token and must not
  22539. // start a WebSocket handshake.
  22540. auto make_request = [](const std::vector<std::string> &connection_values) {
  22541. Request req;
  22542. req.method = "GET";
  22543. req.headers.emplace("Upgrade", "websocket");
  22544. for (const auto &value : connection_values) {
  22545. req.headers.emplace("Connection", value);
  22546. }
  22547. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22548. req.headers.emplace("Sec-WebSocket-Version", "13");
  22549. return req;
  22550. };
  22551. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22552. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22553. EXPECT_TRUE(
  22554. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22555. EXPECT_TRUE(
  22556. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22557. EXPECT_TRUE(
  22558. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22559. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22560. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22561. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22562. EXPECT_FALSE(
  22563. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22564. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22565. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22566. }
  22567. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22568. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22569. // asks recipients to match each protocol-name case-insensitively, and RFC
  22570. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22571. // client naming websocket alongside another protocol, or on a second field
  22572. // line, is offering websocket; a value that merely contains "websocket" as a
  22573. // substring is a different protocol name and is not.
  22574. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22575. Request req;
  22576. req.method = "GET";
  22577. for (const auto &value : upgrade_values) {
  22578. req.headers.emplace("Upgrade", value);
  22579. }
  22580. req.headers.emplace("Connection", "Upgrade");
  22581. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22582. req.headers.emplace("Sec-WebSocket-Version", "13");
  22583. return req;
  22584. };
  22585. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22586. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22587. EXPECT_TRUE(
  22588. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22589. EXPECT_TRUE(
  22590. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22591. EXPECT_TRUE(
  22592. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22593. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22594. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22595. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22596. EXPECT_FALSE(
  22597. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22598. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22599. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22600. }
  22601. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22602. Server svr;
  22603. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22604. auto port = svr.bind_to_any_port("localhost");
  22605. std::thread t([&]() { svr.listen_after_bind(); });
  22606. auto se = detail::scope_exit([&] {
  22607. svr.stop();
  22608. t.join();
  22609. });
  22610. svr.wait_until_ready();
  22611. Headers headers = {{"Upgrade", "websocket"},
  22612. {"Connection", "notupgrade"},
  22613. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22614. {"Sec-WebSocket-Version", "13"}};
  22615. Client cli("localhost", port);
  22616. auto res = cli.Get("/ws", headers);
  22617. // The route exists only as a WebSocket route, so a request that fails the
  22618. // handshake check falls through to ordinary routing.
  22619. ASSERT_TRUE(res);
  22620. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22621. }
  22622. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22623. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22624. // Connection value is the only thing left for the client to reject.
  22625. Server svr;
  22626. svr.Get("/ws", [](const Request &req, Response &res) {
  22627. res.status = StatusCode::SwitchingProtocol_101;
  22628. res.set_header("Upgrade", "websocket");
  22629. res.set_header("Connection", "notupgrade");
  22630. res.set_header("Sec-WebSocket-Accept",
  22631. detail::websocket_accept_key(
  22632. req.get_header_value("Sec-WebSocket-Key")));
  22633. });
  22634. auto port = svr.bind_to_any_port("localhost");
  22635. std::thread t([&]() { svr.listen_after_bind(); });
  22636. auto se = detail::scope_exit([&] {
  22637. svr.stop();
  22638. t.join();
  22639. });
  22640. svr.wait_until_ready();
  22641. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22642. auto res = client.connect();
  22643. EXPECT_FALSE(res);
  22644. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22645. EXPECT_FALSE(client.is_open());
  22646. }
  22647. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22648. Server svr;
  22649. svr.Get("/ws", [](const Request &req, Response &res) {
  22650. res.status = StatusCode::SwitchingProtocol_101;
  22651. res.set_header("Upgrade", "websocket");
  22652. res.set_header("Connection", "Upgrade");
  22653. res.set_header("Sec-WebSocket-Accept",
  22654. detail::websocket_accept_key(
  22655. req.get_header_value("Sec-WebSocket-Key")));
  22656. res.set_header("Sec-WebSocket-Protocol", "admin");
  22657. });
  22658. auto port = svr.bind_to_any_port("localhost");
  22659. std::thread t([&]() { svr.listen_after_bind(); });
  22660. auto se = detail::scope_exit([&] {
  22661. svr.stop();
  22662. t.join();
  22663. });
  22664. svr.wait_until_ready();
  22665. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22666. // Server selects a subprotocol the client never offered
  22667. {
  22668. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22669. ws::WebSocketClient client(url, headers);
  22670. auto res = client.connect();
  22671. EXPECT_FALSE(res);
  22672. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22673. EXPECT_FALSE(client.is_open());
  22674. EXPECT_TRUE(client.subprotocol().empty());
  22675. }
  22676. // Client offered none but the server named one anyway
  22677. {
  22678. ws::WebSocketClient client(url);
  22679. auto res = client.connect();
  22680. EXPECT_FALSE(res);
  22681. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22682. EXPECT_FALSE(client.is_open());
  22683. EXPECT_TRUE(client.subprotocol().empty());
  22684. }
  22685. }
  22686. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22687. // The socket path doubles as the URL host, so it must not contain '/'.
  22688. const char *shard = getenv("GTEST_SHARD_INDEX");
  22689. const std::string sock_path =
  22690. shard ? std::string("httplib-ws-") + shard + ".sock"
  22691. : std::string("httplib-ws.sock");
  22692. std::remove(sock_path.c_str());
  22693. Server svr;
  22694. std::mutex mtx;
  22695. std::string received_host;
  22696. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22697. {
  22698. std::lock_guard<std::mutex> lock(mtx);
  22699. received_host = req.get_header_value("Host");
  22700. }
  22701. std::string msg;
  22702. while (ws.read(msg)) {
  22703. ws.send(msg);
  22704. }
  22705. });
  22706. svr.set_address_family(AF_UNIX);
  22707. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22708. auto se = detail::scope_exit([&] {
  22709. svr.stop();
  22710. t.join();
  22711. std::remove(sock_path.c_str());
  22712. });
  22713. svr.wait_until_ready();
  22714. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22715. client.set_address_family(AF_UNIX);
  22716. ASSERT_TRUE(client.connect());
  22717. ASSERT_TRUE(client.send("hello"));
  22718. std::string msg;
  22719. ASSERT_TRUE(client.read(msg));
  22720. client.close();
  22721. {
  22722. std::lock_guard<std::mutex> lock(mtx);
  22723. // There is no host:port for a Unix socket, so the same "localhost"
  22724. // placeholder the HTTP client uses is expected.
  22725. EXPECT_EQ("localhost", received_host);
  22726. }
  22727. }
  22728. // Two threads must never parse WebSocket frames from the same stream.
  22729. // close() used to read the peer's Close reply with its own frame read, so it
  22730. // raced a reader thread that was in the middle of a payload: the payload loop
  22731. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22732. // so bytes taken by close() were replaced with bytes from further along the
  22733. // stream. The message kept its length and silently changed content.
  22734. //
  22735. // The raw peer below sends a frame header plus part of the payload, waits for
  22736. // the handler to call close(), and only then sends the rest. Whichever thread
  22737. // would win the race for those bytes, the message must arrive intact, because
  22738. // close() must not touch the stream while read() owns it.
  22739. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22740. #ifndef _WIN32
  22741. signal(SIGPIPE, SIG_IGN);
  22742. #endif
  22743. const size_t payload_len = 120; // fits the 7-bit length field
  22744. const size_t prefix_len = 8;
  22745. const int attempts = 8;
  22746. std::string expected(payload_len, '\0');
  22747. for (size_t i = 0; i < payload_len; i++) {
  22748. expected[i] = static_cast<char>('a' + i % 26);
  22749. }
  22750. std::atomic<bool> peer_stalled{false};
  22751. std::atomic<bool> handler_done{false};
  22752. std::mutex received_mutex;
  22753. std::vector<std::string> received;
  22754. // Bound every wait, so a regression fails the test instead of hanging the
  22755. // suite.
  22756. auto wait_for = [](const std::atomic<bool> &flag) {
  22757. for (int i = 0; i < 500 && !flag; i++) {
  22758. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22759. }
  22760. };
  22761. Server svr;
  22762. svr.set_websocket_ping_interval(0);
  22763. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22764. std::thread reader([&]() {
  22765. std::string msg;
  22766. while (ws.read(msg)) {
  22767. std::lock_guard<std::mutex> guard(received_mutex);
  22768. received.push_back(msg);
  22769. }
  22770. });
  22771. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22772. // inside read_websocket_frame() when close() runs.
  22773. wait_for(peer_stalled);
  22774. ws.close();
  22775. reader.join();
  22776. handler_done = true;
  22777. });
  22778. auto port = svr.bind_to_any_port("127.0.0.1");
  22779. std::thread t([&]() { svr.listen_after_bind(); });
  22780. auto se = detail::scope_exit([&] {
  22781. svr.stop();
  22782. t.join();
  22783. });
  22784. svr.wait_until_ready();
  22785. auto send_bytes = [](socket_t s, const std::string &data) {
  22786. #ifdef _WIN32
  22787. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22788. #else
  22789. auto n = ::send(s, data.data(), data.size(), 0);
  22790. #endif
  22791. return n == static_cast<decltype(n)>(data.size());
  22792. };
  22793. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22794. // Every length used here fits the 7-bit length field.
  22795. auto masked_header = [](uint8_t first_byte, size_t len) {
  22796. std::string h;
  22797. h += static_cast<char>(first_byte);
  22798. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22799. h.append(4, '\0'); // mask key
  22800. return h;
  22801. };
  22802. for (int attempt = 0; attempt < attempts; attempt++) {
  22803. peer_stalled = false;
  22804. handler_done = false;
  22805. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22806. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22807. auto se_sock = detail::scope_exit([&] {
  22808. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22809. });
  22810. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22811. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22812. sockaddr_in addr{};
  22813. addr.sin_family = AF_INET;
  22814. addr.sin_port = htons(static_cast<uint16_t>(port));
  22815. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22816. ASSERT_EQ(
  22817. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22818. << "attempt " << attempt;
  22819. ASSERT_TRUE(send_bytes(sock,
  22820. "GET /ws HTTP/1.1\r\n"
  22821. "Host: 127.0.0.1\r\n"
  22822. "Upgrade: websocket\r\n"
  22823. "Connection: Upgrade\r\n"
  22824. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22825. "Sec-WebSocket-Version: 13\r\n"
  22826. "\r\n"))
  22827. << "attempt " << attempt;
  22828. std::string response;
  22829. while (response.find("\r\n\r\n") == std::string::npos) {
  22830. char buf[512];
  22831. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22832. if (n <= 0) { break; }
  22833. response.append(buf, static_cast<size_t>(n));
  22834. }
  22835. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22836. << "attempt " << attempt;
  22837. // Send the header of a Binary message but only the first prefix_len bytes
  22838. // of its payload, leaving the reader thread stalled inside the payload.
  22839. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22840. expected.substr(0, prefix_len)))
  22841. << "attempt " << attempt;
  22842. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22843. peer_stalled = true;
  22844. // Let close() send its Close frame and park in its own read before the
  22845. // rest of the payload arrives, so both threads are waiting for it.
  22846. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22847. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22848. close_frame += static_cast<char>(0x03); // status 1000
  22849. close_frame += static_cast<char>(0xE8);
  22850. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22851. << "attempt " << attempt;
  22852. // Closing the peer releases the reader thread even on the buggy path,
  22853. // where it waits for bytes another thread already consumed.
  22854. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22855. detail::close_socket(sock);
  22856. sock = INVALID_SOCKET;
  22857. wait_for(handler_done);
  22858. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22859. }
  22860. std::lock_guard<std::mutex> guard(received_mutex);
  22861. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22862. << "a message in flight when close() ran was dropped";
  22863. for (size_t i = 0; i < received.size(); i++) {
  22864. EXPECT_EQ(expected, received[i]) << "message " << i;
  22865. }
  22866. }
  22867. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  22868. // returning the socket, or INVALID_SOCKET.
  22869. static socket_t connect_raw_websocket(int port, const std::string &path) {
  22870. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22871. if (sock == INVALID_SOCKET) { return sock; }
  22872. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22873. sockaddr_in addr{};
  22874. addr.sin_family = AF_INET;
  22875. addr.sin_port = htons(static_cast<uint16_t>(port));
  22876. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22877. std::string req = "GET " + path +
  22878. " HTTP/1.1\r\n"
  22879. "Host: 127.0.0.1\r\n"
  22880. "Upgrade: websocket\r\n"
  22881. "Connection: Upgrade\r\n"
  22882. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22883. "Sec-WebSocket-Version: 13\r\n"
  22884. "\r\n";
  22885. std::string res;
  22886. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  22887. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  22888. static_cast<int>(req.size())) {
  22889. char c;
  22890. while (res.find("\r\n\r\n") == std::string::npos &&
  22891. ::recv(sock, &c, 1, 0) == 1) {
  22892. res += c;
  22893. }
  22894. }
  22895. if (res.find(" 101 ") == std::string::npos) {
  22896. detail::close_socket(sock);
  22897. return INVALID_SOCKET;
  22898. }
  22899. return sock;
  22900. }
  22901. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  22902. // The payload must fit the 7-bit length field.
  22903. static std::string masked_frame(uint8_t first_byte,
  22904. const std::string &payload) {
  22905. std::string f;
  22906. f += static_cast<char>(first_byte);
  22907. f += static_cast<char>(0x80 | payload.size());
  22908. f.append(4, '\0');
  22909. return f + payload;
  22910. }
  22911. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22912. std::atomic<bool> done{false};
  22913. std::string received;
  22914. Server svr;
  22915. svr.set_websocket_ping_interval(0);
  22916. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22917. std::string msg;
  22918. if (ws.read(msg) == ws::Binary) { received = msg; }
  22919. done = true;
  22920. });
  22921. auto port = svr.bind_to_any_port("127.0.0.1");
  22922. std::thread t([&]() { svr.listen_after_bind(); });
  22923. auto se = detail::scope_exit([&] {
  22924. svr.stop();
  22925. t.join();
  22926. });
  22927. svr.wait_until_ready();
  22928. auto sock = connect_raw_websocket(port, "/ws");
  22929. ASSERT_NE(INVALID_SOCKET, sock);
  22930. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22931. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  22932. masked_frame(0x89, "p") + // FIN + Ping
  22933. masked_frame(0x80, "lo"); // FIN + Continuation
  22934. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  22935. for (int i = 0; i < 500 && !done; i++) {
  22936. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22937. }
  22938. ASSERT_TRUE(done);
  22939. EXPECT_EQ("Hello", received);
  22940. // The Ping between the fragments is answered with a Pong.
  22941. char pong[3];
  22942. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  22943. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  22944. }
  22945. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  22946. Server svr;
  22947. svr.set_websocket_ping_interval(0);
  22948. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22949. std::string msg;
  22950. while (ws.read(msg)) {}
  22951. });
  22952. auto port = svr.bind_to_any_port("127.0.0.1");
  22953. std::thread t([&]() { svr.listen_after_bind(); });
  22954. auto se = detail::scope_exit([&] {
  22955. svr.stop();
  22956. t.join();
  22957. });
  22958. svr.wait_until_ready();
  22959. // Each Close payload and the reply it should get: an echo when valid, 1002
  22960. // otherwise.
  22961. std::vector<std::pair<std::string, std::string>> cases = {
  22962. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  22963. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  22964. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  22965. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  22966. };
  22967. // Also between the fragments of a message.
  22968. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  22969. for (const auto &c : cases) {
  22970. auto sock = connect_raw_websocket(port, "/ws");
  22971. ASSERT_NE(INVALID_SOCKET, sock);
  22972. auto frames = prefix + masked_frame(0x88, c.first);
  22973. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  22974. std::string reply;
  22975. char buf[256];
  22976. while (reply.size() < 2 + c.second.size()) {
  22977. auto n = ::recv(sock, buf, sizeof(buf), 0);
  22978. if (n <= 0) { break; }
  22979. reply.append(buf, static_cast<size_t>(n));
  22980. }
  22981. detail::close_socket(sock);
  22982. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  22983. c.second,
  22984. reply);
  22985. }
  22986. }
  22987. }
  22988. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22989. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22990. protected:
  22991. void SetUp() override {
  22992. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22993. SERVER_PRIVATE_KEY_FILE);
  22994. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22995. std::string msg;
  22996. ws::ReadResult ret;
  22997. while ((ret = ws.read(msg))) {
  22998. if (ret == ws::Binary) {
  22999. ws.send(msg.data(), msg.size());
  23000. } else {
  23001. ws.send(msg);
  23002. }
  23003. }
  23004. });
  23005. port_ = server_->bind_to_any_port(HOST);
  23006. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23007. server_->wait_until_ready();
  23008. }
  23009. void TearDown() override {
  23010. server_->stop();
  23011. if (server_thread_.joinable()) { server_thread_.join(); }
  23012. }
  23013. std::unique_ptr<SSLServer> server_;
  23014. std::thread server_thread_;
  23015. int port_ = 0;
  23016. };
  23017. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23018. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23019. {
  23020. ws::WebSocketClient client(url);
  23021. client.enable_server_certificate_verification(false);
  23022. auto calls = 0;
  23023. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23024. calls++;
  23025. return false;
  23026. });
  23027. EXPECT_FALSE(client.connect());
  23028. EXPECT_GT(calls, 0);
  23029. }
  23030. {
  23031. ws::WebSocketClient client(url);
  23032. client.enable_server_certificate_verification(false);
  23033. client.set_session_verifier([](tls::session_t) {
  23034. return SSLVerifierResponse::CertificateRejected;
  23035. });
  23036. EXPECT_FALSE(client.connect());
  23037. }
  23038. {
  23039. ws::WebSocketClient client(url);
  23040. client.enable_server_certificate_verification(false);
  23041. client.set_session_verifier([](tls::session_t) {
  23042. return SSLVerifierResponse::CertificateAccepted;
  23043. });
  23044. EXPECT_TRUE(client.connect());
  23045. }
  23046. }
  23047. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23048. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23049. "/ws-echo");
  23050. client.enable_server_certificate_verification(false);
  23051. ASSERT_TRUE(client.connect());
  23052. ASSERT_TRUE(client.is_open());
  23053. ASSERT_TRUE(client.send("Hello WSS"));
  23054. std::string msg;
  23055. EXPECT_EQ(ws::Text, client.read(msg));
  23056. EXPECT_EQ("Hello WSS", msg);
  23057. client.close();
  23058. }
  23059. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23060. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23061. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23062. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23063. // client (without calling close() first) is the only path that runs
  23064. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23065. // bug exactly.
  23066. //
  23067. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23068. // when linked against an instrumented libssl; run under Valgrind to catch it
  23069. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23070. // suite (the freed session otherwise stalls on the close handshake) — this test
  23071. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23072. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23073. {
  23074. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23075. "/ws-echo");
  23076. client.enable_server_certificate_verification(false);
  23077. client.set_read_timeout(2, 0);
  23078. client.set_write_timeout(2, 0);
  23079. ASSERT_TRUE(client.connect());
  23080. ASSERT_TRUE(client.is_open());
  23081. ASSERT_TRUE(client.send("still open"));
  23082. // Intentionally do NOT call client.close(): leaving scope runs
  23083. // shutdown_and_close() with the WebSocket still open, which must send the
  23084. // close frame while the TLS session is still alive.
  23085. }
  23086. }
  23087. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23088. // shutdown_and_close() at the start of connect(), reproducing the same
  23089. // use-after-free within the test body rather than at scope exit. The second
  23090. // connect must succeed and echo, proving the close handshake ran over a live
  23091. // session. See the note above about memory-tool requirements.
  23092. TEST_F(WebSocketSSLIntegrationTest,
  23093. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23094. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23095. "/ws-echo");
  23096. client.enable_server_certificate_verification(false);
  23097. client.set_read_timeout(2, 0);
  23098. client.set_write_timeout(2, 0);
  23099. ASSERT_TRUE(client.connect());
  23100. ASSERT_TRUE(client.is_open());
  23101. ASSERT_TRUE(client.send("still open"));
  23102. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23103. // the still-open connection, which must not touch a freed TLS session.
  23104. ASSERT_TRUE(client.connect());
  23105. ASSERT_TRUE(client.is_open());
  23106. ASSERT_TRUE(client.send("after reconnect"));
  23107. std::string msg;
  23108. EXPECT_EQ(ws::Text, client.read(msg));
  23109. EXPECT_EQ("after reconnect", msg);
  23110. client.close();
  23111. }
  23112. #endif
  23113. #ifdef CPPHTTPLIB_SSL_ENABLED
  23114. class WebSocketSSLCATest : public ::testing::Test {
  23115. protected:
  23116. void SetUp() override {
  23117. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23118. SERVER_PRIVATE_KEY_FILE);
  23119. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23120. std::string msg;
  23121. while (ws.read(msg)) {
  23122. ws.send(msg);
  23123. }
  23124. });
  23125. port_ = server_->bind_to_any_port("127.0.0.1");
  23126. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23127. server_->wait_until_ready();
  23128. }
  23129. void TearDown() override {
  23130. server_->stop();
  23131. if (server_thread_.joinable()) { server_thread_.join(); }
  23132. }
  23133. std::string url() const {
  23134. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23135. }
  23136. std::unique_ptr<SSLServer> server_;
  23137. std::thread server_thread_;
  23138. int port_ = 0;
  23139. };
  23140. // A custom CA loaded as PEM verifies the server with full certificate
  23141. // verification enabled
  23142. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23143. ws::WebSocketClient client(url());
  23144. std::string cert;
  23145. read_file(SERVER_CERT2_FILE, cert);
  23146. client.load_ca_cert_store(cert.c_str(), cert.size());
  23147. ASSERT_TRUE(client.connect());
  23148. ASSERT_TRUE(client.send("hello"));
  23149. std::string msg;
  23150. EXPECT_EQ(ws::Text, client.read(msg));
  23151. EXPECT_EQ("hello", msg);
  23152. client.close();
  23153. }
  23154. // A custom CA that does not cover the server must fail verification (the
  23155. // custom CA is exclusive; system certs are not loaded alongside it)
  23156. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23157. ws::WebSocketClient client(url());
  23158. std::string cert;
  23159. read_file(CLIENT_CA_CERT_FILE, cert);
  23160. client.load_ca_cert_store(cert.c_str(), cert.size());
  23161. auto res = client.connect();
  23162. ASSERT_FALSE(res);
  23163. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23164. EXPECT_EQ(-1, res.status());
  23165. EXPECT_NE(0u, res.ssl_backend_error());
  23166. }
  23167. // The same CA as a file path rather than PEM in memory
  23168. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23169. ws::WebSocketClient client(url());
  23170. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23171. ASSERT_TRUE(client.connect());
  23172. ASSERT_TRUE(client.send("hello"));
  23173. std::string msg;
  23174. EXPECT_EQ(ws::Text, client.read(msg));
  23175. EXPECT_EQ("hello", msg);
  23176. client.close();
  23177. }
  23178. // ...and a CA file that does not cover the server still fails, so it is the
  23179. // path above that decides the outcome
  23180. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23181. ws::WebSocketClient client(url());
  23182. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23183. ASSERT_FALSE(client.connect());
  23184. }
  23185. // Regression test: reconnecting with a native custom CA store used to reuse
  23186. // a store handle the previous TLS context had already freed (use-after-free
  23187. // under the OpenSSL backend). The context now lives as long as the client.
  23188. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23189. ws::WebSocketClient client(url());
  23190. std::string cert;
  23191. read_file(SERVER_CERT2_FILE, cert);
  23192. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23193. ASSERT_TRUE(client.connect());
  23194. client.close();
  23195. ASSERT_TRUE(client.connect());
  23196. ASSERT_TRUE(client.send("again"));
  23197. std::string msg;
  23198. EXPECT_EQ(ws::Text, client.read(msg));
  23199. EXPECT_EQ("again", msg);
  23200. client.close();
  23201. }
  23202. // Regression test: a certificate with a trusted chain but no identity match
  23203. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23204. // verification entirely for IP hosts, so this connection succeeded there.
  23205. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23206. // chain verification while the identity check must still fail.
  23207. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23208. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23209. ASSERT_TRUE(svr.is_valid());
  23210. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23211. std::string msg;
  23212. while (ws.read(msg)) {
  23213. ws.send(msg);
  23214. }
  23215. });
  23216. auto port = svr.bind_to_any_port("127.0.0.1");
  23217. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23218. auto se = detail::scope_exit([&] {
  23219. svr.stop();
  23220. t.join();
  23221. });
  23222. svr.wait_until_ready();
  23223. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23224. "/echo");
  23225. std::string cert;
  23226. read_file(SERVER_CERT_FILE, cert);
  23227. client.load_ca_cert_store(cert.c_str(), cert.size());
  23228. ASSERT_FALSE(client.connect());
  23229. }
  23230. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23231. // SNI, so nothing binds the host name to the TLS session. These bind the
  23232. // server to "localhost" instead, the only shape that exercises the SNI and
  23233. // hostname-verification path with certificate verification left enabled.
  23234. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23235. protected:
  23236. void Start(const char *cert_file) {
  23237. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23238. SERVER_PRIVATE_KEY_FILE);
  23239. ASSERT_TRUE(server_->is_valid());
  23240. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23241. std::string msg;
  23242. while (ws.read(msg)) {
  23243. ws.send(msg);
  23244. }
  23245. });
  23246. port_ = server_->bind_to_any_port("localhost");
  23247. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23248. server_->wait_until_ready();
  23249. }
  23250. void TearDown() override {
  23251. if (server_) { server_->stop(); }
  23252. if (server_thread_.joinable()) { server_thread_.join(); }
  23253. }
  23254. std::string url() const {
  23255. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23256. }
  23257. std::unique_ptr<SSLServer> server_;
  23258. std::thread server_thread_;
  23259. int port_ = 0;
  23260. };
  23261. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23262. // out and the connection is usable
  23263. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23264. Start(SERVER_CERT2_FILE);
  23265. ws::WebSocketClient client(url());
  23266. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23267. ASSERT_TRUE(client.connect());
  23268. ASSERT_TRUE(client.send("hello"));
  23269. std::string msg;
  23270. EXPECT_EQ(ws::Text, client.read(msg));
  23271. EXPECT_EQ("hello", msg);
  23272. client.close();
  23273. }
  23274. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23275. // while the identity check must still reject "localhost"
  23276. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23277. Start(SERVER_CERT_FILE);
  23278. ws::WebSocketClient client(url());
  23279. client.set_ca_cert_path(SERVER_CERT_FILE);
  23280. auto res = client.connect();
  23281. ASSERT_FALSE(res);
  23282. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23283. EXPECT_EQ(-1, res.status());
  23284. }
  23285. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23286. // disabled: the chain is still checked, only the identity check is skipped
  23287. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23288. Start(SERVER_CERT_FILE);
  23289. ws::WebSocketClient client(url());
  23290. client.set_ca_cert_path(SERVER_CERT_FILE);
  23291. client.enable_server_hostname_verification(false);
  23292. ASSERT_TRUE(client.connect());
  23293. ASSERT_TRUE(client.send("hello"));
  23294. std::string msg;
  23295. EXPECT_EQ(ws::Text, client.read(msg));
  23296. EXPECT_EQ("hello", msg);
  23297. client.close();
  23298. }
  23299. // A CA that did not sign the server certificate fails the chain, even though
  23300. // the name would match
  23301. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23302. Start(SERVER_CERT2_FILE);
  23303. ws::WebSocketClient client(url());
  23304. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23305. ASSERT_FALSE(client.connect());
  23306. }
  23307. // With verification disabled, neither the chain nor the name is checked
  23308. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23309. Start(SERVER_CERT_FILE);
  23310. ws::WebSocketClient client(url());
  23311. client.enable_server_certificate_verification(false);
  23312. ASSERT_TRUE(client.connect());
  23313. ASSERT_TRUE(client.send("hello"));
  23314. std::string msg;
  23315. EXPECT_EQ(ws::Text, client.read(msg));
  23316. EXPECT_EQ("hello", msg);
  23317. client.close();
  23318. }
  23319. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23320. protected:
  23321. void SetUp() override {
  23322. server_ = httplib::detail::make_unique<SSLServer>(
  23323. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23324. ASSERT_TRUE(server_->is_valid());
  23325. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23326. std::string msg;
  23327. while (ws.read(msg)) {
  23328. ws.send(msg);
  23329. }
  23330. });
  23331. port_ = server_->bind_to_any_port("localhost");
  23332. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23333. server_->wait_until_ready();
  23334. }
  23335. void TearDown() override {
  23336. server_->stop();
  23337. if (server_thread_.joinable()) { server_thread_.join(); }
  23338. }
  23339. std::string url() const {
  23340. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23341. }
  23342. void ConnectWithClientCert(const std::string &client_cert_file,
  23343. const std::string &client_private_key_file,
  23344. const char *private_key_password) {
  23345. std::string cert_pem, key_pem;
  23346. read_file(client_cert_file, cert_pem);
  23347. read_file(client_private_key_file, key_pem);
  23348. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23349. key_pem.c_str(), key_pem.size(),
  23350. private_key_password};
  23351. ws::WebSocketClient client(url(), pem);
  23352. ASSERT_TRUE(client.is_valid());
  23353. client.enable_server_certificate_verification(false);
  23354. ASSERT_TRUE(client.connect());
  23355. ASSERT_TRUE(client.send("hello"));
  23356. std::string msg;
  23357. EXPECT_EQ(ws::Text, client.read(msg));
  23358. EXPECT_EQ("hello", msg);
  23359. client.close();
  23360. }
  23361. std::unique_ptr<SSLServer> server_;
  23362. std::thread server_thread_;
  23363. int port_ = 0;
  23364. };
  23365. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23366. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23367. }
  23368. // Control for the tests above: the fixture's server really does require a
  23369. // client certificate, so it is the PEM the constructor installed that decides
  23370. // the outcome.
  23371. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23372. ws::WebSocketClient client(url());
  23373. ASSERT_TRUE(client.is_valid());
  23374. client.enable_server_certificate_verification(false);
  23375. EXPECT_FALSE(client.connect());
  23376. }
  23377. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23378. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23379. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23380. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23381. }
  23382. #endif
  23383. #if !defined(_WIN32)
  23384. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23385. auto secret_dir = std::string("./symlink_test_secret");
  23386. auto served_dir = std::string("./symlink_test_served");
  23387. auto secret_file = secret_dir + "/secret.txt";
  23388. auto symlink_path = served_dir + "/escape";
  23389. // Setup: create directories and files
  23390. mkdir(secret_dir.c_str(), 0755);
  23391. mkdir(served_dir.c_str(), 0755);
  23392. {
  23393. std::ofstream ofs(secret_file);
  23394. ofs << "SECRET_DATA";
  23395. }
  23396. // Create symlink using absolute path so it resolves correctly
  23397. #ifdef PATH_MAX
  23398. char abs_secret[PATH_MAX];
  23399. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23400. #else
  23401. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23402. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23403. ASSERT_NE(nullptr, abs_secret);
  23404. #endif
  23405. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23406. auto se = detail::scope_exit([&] {
  23407. unlink(symlink_path.c_str());
  23408. unlink(secret_file.c_str());
  23409. rmdir(served_dir.c_str());
  23410. rmdir(secret_dir.c_str());
  23411. });
  23412. Server svr;
  23413. svr.set_mount_point("/", served_dir);
  23414. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23415. auto se2 = detail::scope_exit([&] {
  23416. svr.stop();
  23417. listen_thread.join();
  23418. });
  23419. svr.wait_until_ready();
  23420. Client cli("localhost", PORT);
  23421. // Symlink pointing outside base dir should be blocked
  23422. auto res = cli.Get("/escape/secret.txt");
  23423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23424. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23425. }
  23426. #endif
  23427. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23428. // "GET /smuggled" request), reads the first response, and only then sends the
  23429. // embedded request as the body. Returns how many times /smuggled ran.
  23430. //
  23431. // The body is sent AFTER receiving the first response (as in the original
  23432. // PoC) so that the stream_line_reader cannot buffer it together with the
  23433. // headers of the first request.
  23434. static int count_smuggled_requests(const std::string &outer_head,
  23435. std::string &first_response) {
  23436. Server svr;
  23437. svr.set_mount_point("/", "./www");
  23438. std::atomic<int> smuggled_count(0);
  23439. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23440. smuggled_count++;
  23441. res.set_content("oops", "text/plain");
  23442. });
  23443. svr.Post("/post", [&](const Request &req, Response &res) {
  23444. res.set_content(req.body, "text/plain");
  23445. });
  23446. auto port = svr.bind_to_any_port("localhost");
  23447. thread t = thread([&] { svr.listen_after_bind(); });
  23448. auto se = detail::scope_exit([&] {
  23449. svr.stop();
  23450. t.join();
  23451. });
  23452. svr.wait_until_ready();
  23453. auto error = Error::Success;
  23454. auto sock = detail::create_client_socket(
  23455. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23456. /*connection_timeout_sec=*/2, 0,
  23457. /*read_timeout_sec=*/2, 0,
  23458. /*write_timeout_sec=*/2, 0, std::string(), error);
  23459. EXPECT_NE(INVALID_SOCKET, sock);
  23460. if (sock == INVALID_SOCKET) { return -1; }
  23461. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23462. // The "smuggled" request will be sent as the body of the outer request
  23463. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23464. "Host: localhost\r\n"
  23465. "Connection: close\r\n"
  23466. "\r\n";
  23467. auto head = outer_head;
  23468. auto len = std::to_string(smuggled.size());
  23469. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23470. pos = head.find("{len}", pos + len.size())) {
  23471. head.replace(pos, 5, len);
  23472. }
  23473. // Step 1: Send only the outer request headers (no body yet)
  23474. auto sent = send(sock, head.data(), head.size(), 0);
  23475. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23476. // Step 2: Read the first response
  23477. char buf[4096];
  23478. for (;;) {
  23479. auto n = recv(sock, buf, sizeof(buf), 0);
  23480. if (n <= 0) break;
  23481. first_response.append(buf, static_cast<size_t>(n));
  23482. // Stop once we have a complete response (headers + body)
  23483. auto hdr_end = first_response.find("\r\n\r\n");
  23484. if (hdr_end != std::string::npos) {
  23485. // Check for Content-Length to know when the body is complete
  23486. auto cl_pos = first_response.find("Content-Length:");
  23487. if (cl_pos != std::string::npos) {
  23488. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23489. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23490. auto cl = std::stoul(
  23491. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23492. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23493. } else {
  23494. break; // No Content-Length, assume headers-only response
  23495. }
  23496. }
  23497. }
  23498. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23499. // vulnerable server the keep-alive loop reads this as a second request. The
  23500. // server may already have closed the connection, so the result is ignored.
  23501. send(sock, smuggled.data(), smuggled.size(), 0);
  23502. // Half-close so that a server which drained the body sees EOF and closes,
  23503. // instead of the read below waiting for the read timeout.
  23504. #ifdef _WIN32
  23505. ::shutdown(sock, SD_SEND);
  23506. #else
  23507. ::shutdown(sock, SHUT_WR);
  23508. #endif
  23509. // Step 4: Read until the server closes the connection
  23510. for (;;) {
  23511. auto n = recv(sock, buf, sizeof(buf), 0);
  23512. if (n <= 0) break;
  23513. }
  23514. return smuggled_count.load();
  23515. }
  23516. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23517. // A GET request with Content-Length to a static file handler must have its
  23518. // body drained before the keep-alive connection is reused. Otherwise the
  23519. // unread body bytes are interpreted as the next HTTP request.
  23520. std::string first_response;
  23521. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23522. "Host: localhost\r\n"
  23523. "Content-Length: {len}\r\n"
  23524. "\r\n",
  23525. first_response));
  23526. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23527. }
  23528. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23529. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23530. // be answered with 400 and the connection closed. Treating it as "no body"
  23531. // leaves the body to be parsed as the next request.
  23532. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23533. const char *targets[] = {
  23534. "GET /file", // handler that never reads the body
  23535. "GET /not-found", // no handler matches (404)
  23536. "POST /post", // handler that reads the body
  23537. };
  23538. for (auto target : targets) {
  23539. for (auto value : values) {
  23540. std::string first_response;
  23541. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23542. " HTTP/1.1\r\n"
  23543. "Host: localhost\r\n"
  23544. "Content-Length: " +
  23545. value + "\r\n\r\n",
  23546. first_response))
  23547. << target << " with Content-Length: " << value;
  23548. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23549. << target << " with Content-Length: " << value;
  23550. }
  23551. }
  23552. }
  23553. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23554. // A 400 for an unparseable request line leaves the rest of the message
  23555. // unread, so the connection must be closed rather than reused.
  23556. std::string first_response;
  23557. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23558. "Host: localhost\r\n"
  23559. "Content-Length: {len}\r\n"
  23560. "\r\n",
  23561. first_response));
  23562. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23563. }
  23564. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23565. // Same as above for a header block that fails to parse.
  23566. std::string first_response;
  23567. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23568. "Host: localhost\r\n"
  23569. "Bad Header\r\n"
  23570. "Content-Length: {len}\r\n"
  23571. "\r\n",
  23572. first_response));
  23573. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23574. }
  23575. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23576. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23577. // server must not read another request on that connection, even when the
  23578. // request had no body to drain.
  23579. std::string first_response;
  23580. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23581. "Host: localhost\r\n"
  23582. "\r\n",
  23583. first_response));
  23584. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23585. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23586. }
  23587. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23588. // A content reader that stops early leaves the stream inside the body.
  23589. // Draining the whole Content-Length from there, or reading the body again,
  23590. // reads into the next request, and whatever follows is parsed as a request
  23591. // of its own.
  23592. Server svr;
  23593. std::atomic<int> smuggled_count(0);
  23594. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23595. svr.Post("/upload", [](const Request &req, Response &res,
  23596. const ContentReader &content_reader) {
  23597. // Stop at the last chunk, so the whole body has been read however it
  23598. // arrives.
  23599. auto length = req.get_header_value_u64("Content-Length");
  23600. size_t total = 0;
  23601. auto consumed = content_reader([&](const char *, size_t n) {
  23602. total += n;
  23603. return total < length;
  23604. });
  23605. EXPECT_FALSE(consumed);
  23606. if (req.has_param("retry")) {
  23607. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23608. }
  23609. // Replace the 400 the aborted read set, which would close the connection.
  23610. res.set_redirect("/done");
  23611. });
  23612. auto port = svr.bind_to_any_port(HOST);
  23613. thread t = thread([&] { svr.listen_after_bind(); });
  23614. auto se = detail::scope_exit([&] {
  23615. svr.stop();
  23616. t.join();
  23617. });
  23618. svr.wait_until_ready();
  23619. // A front end sees the second request as a POST whose body is the GET. The
  23620. // first body is as long as the POST's headers, so draining it again reads
  23621. // exactly those and leaves the GET to be parsed next.
  23622. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23623. "Host: localhost\r\n"
  23624. "\r\n";
  23625. std::string second_head = "POST /post HTTP/1.1\r\n"
  23626. "Host: localhost\r\n"
  23627. "Content-Length: " +
  23628. std::to_string(inner.size()) +
  23629. "\r\n"
  23630. "\r\n";
  23631. for (auto target : {"/upload", "/upload?retry"}) {
  23632. smuggled_count = 0;
  23633. std::string request = "POST " + std::string(target) +
  23634. " HTTP/1.1\r\n"
  23635. "Host: localhost\r\n"
  23636. "Content-Length: " +
  23637. std::to_string(second_head.size()) +
  23638. "\r\n"
  23639. "\r\n" +
  23640. std::string(second_head.size(), 'A') + second_head +
  23641. inner;
  23642. std::string response;
  23643. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23644. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23645. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23646. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23647. EXPECT_EQ(0, smuggled_count.load()) << target;
  23648. }
  23649. }
  23650. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23651. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23652. // must be rejected with 400 Bad Request.
  23653. Server svr;
  23654. svr.Post("/test", [&](const Request &, Response &res) {
  23655. res.set_content("ok", "text/plain");
  23656. });
  23657. thread t = thread([&] { svr.listen(HOST, PORT); });
  23658. auto se = detail::scope_exit([&] {
  23659. svr.stop();
  23660. t.join();
  23661. ASSERT_FALSE(svr.is_running());
  23662. });
  23663. svr.wait_until_ready();
  23664. // Exact "chunked"
  23665. {
  23666. auto req = "POST /test HTTP/1.1\r\n"
  23667. "Host: localhost\r\n"
  23668. "Content-Length: 5\r\n"
  23669. "Transfer-Encoding: chunked\r\n"
  23670. "Connection: close\r\n"
  23671. "\r\n"
  23672. "hello";
  23673. std::string response;
  23674. ASSERT_TRUE(send_request(1, req, &response));
  23675. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23676. response.substr(0, response.find("\r\n")));
  23677. }
  23678. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23679. {
  23680. auto req = "POST /test HTTP/1.1\r\n"
  23681. "Host: localhost\r\n"
  23682. "Content-Length: 5\r\n"
  23683. "Transfer-Encoding: gzip, chunked\r\n"
  23684. "Connection: close\r\n"
  23685. "\r\n"
  23686. "hello";
  23687. std::string response;
  23688. ASSERT_TRUE(send_request(1, req, &response));
  23689. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23690. response.substr(0, response.find("\r\n")));
  23691. }
  23692. }
  23693. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23694. Server svr;
  23695. svr.Post("/test", [&](const Request &, Response &res) {
  23696. res.set_content("ok", "text/plain");
  23697. });
  23698. thread t = thread([&] { svr.listen(HOST, PORT); });
  23699. auto se = detail::scope_exit([&] {
  23700. svr.stop();
  23701. t.join();
  23702. ASSERT_FALSE(svr.is_running());
  23703. });
  23704. svr.wait_until_ready();
  23705. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23706. // length cannot be determined, so the server must answer 400 and close
  23707. // rather than treat the request as bodyless and leave the body in the
  23708. // socket for the next request to pick up.
  23709. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23710. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23711. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23712. std::string response;
  23713. ASSERT_TRUE(send_request(1, req, &response));
  23714. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23715. response.substr(0, response.find("\r\n")))
  23716. << transfer_encoding;
  23717. }
  23718. // RFC 9110 5.3: the codings may also be split across several
  23719. // Transfer-Encoding lines, which combine in the order they were received.
  23720. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23721. // just like the single-line "chunked, gzip" above.
  23722. {
  23723. auto req = "POST /test HTTP/1.1\r\n"
  23724. "Host: localhost\r\n"
  23725. "Transfer-Encoding: chunked\r\n"
  23726. "Transfer-Encoding: gzip\r\n"
  23727. "\r\n"
  23728. "0\r\n\r\n";
  23729. std::string response;
  23730. ASSERT_TRUE(send_request(1, req, &response));
  23731. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23732. response.substr(0, response.find("\r\n")));
  23733. }
  23734. // A sequence ending in chunked stays valid.
  23735. auto req = "POST /test HTTP/1.1\r\n"
  23736. "Host: localhost\r\n"
  23737. "Transfer-Encoding: gzip, chunked\r\n"
  23738. "Connection: close\r\n"
  23739. "\r\n"
  23740. "0\r\n\r\n";
  23741. std::string response;
  23742. ASSERT_TRUE(send_request(1, req, &response));
  23743. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23744. // ...including when it is spread over several lines.
  23745. auto split_req = "POST /test HTTP/1.1\r\n"
  23746. "Host: localhost\r\n"
  23747. "Transfer-Encoding: gzip\r\n"
  23748. "Transfer-Encoding: chunked\r\n"
  23749. "Connection: close\r\n"
  23750. "\r\n"
  23751. "0\r\n\r\n";
  23752. std::string split_response;
  23753. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23754. EXPECT_EQ("HTTP/1.1 200 OK",
  23755. split_response.substr(0, split_response.find("\r\n")));
  23756. }
  23757. // Regression for issue #2450: a DELETE without Content-Length on a
  23758. // keep-alive connection must not let the post-response drain consume the
  23759. // next request's bytes.
  23760. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23761. Server svr;
  23762. std::atomic<int> delete_count(0);
  23763. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23764. delete_count++;
  23765. res.status = StatusCode::NoContent_204;
  23766. });
  23767. auto port = svr.bind_to_any_port(HOST);
  23768. thread t = thread([&] { svr.listen_after_bind(); });
  23769. auto se = detail::scope_exit([&] {
  23770. svr.stop();
  23771. t.join();
  23772. });
  23773. svr.wait_until_ready();
  23774. auto error = Error::Success;
  23775. auto sock = detail::create_client_socket(
  23776. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23777. /*connection_timeout_sec=*/2, 0,
  23778. /*read_timeout_sec=*/2, 0,
  23779. /*write_timeout_sec=*/2, 0, std::string(), error);
  23780. ASSERT_NE(INVALID_SOCKET, sock);
  23781. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23782. auto send_request_and_read_response = [&](const std::string &req,
  23783. std::string &out) -> bool {
  23784. auto sent = send(sock, req.data(), req.size(), 0);
  23785. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23786. char buf[4096];
  23787. for (;;) {
  23788. auto n = recv(sock, buf, sizeof(buf), 0);
  23789. if (n <= 0) { return !out.empty(); }
  23790. out.append(buf, static_cast<size_t>(n));
  23791. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23792. }
  23793. };
  23794. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23795. "Host: localhost\r\n"
  23796. "\r\n";
  23797. std::string resp1;
  23798. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23799. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23800. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23801. "Host: localhost\r\n"
  23802. "Connection: close\r\n"
  23803. "\r\n";
  23804. std::string resp2;
  23805. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23806. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23807. EXPECT_EQ(2, delete_count.load());
  23808. }
  23809. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23810. Server svr;
  23811. svr.Post("/ingest", [&](const Request &, Response &res,
  23812. const ContentReader &content_reader) {
  23813. auto consumed = content_reader([](const char *, size_t) { return false; });
  23814. EXPECT_FALSE(consumed);
  23815. res.status = StatusCode::Conflict_409;
  23816. res.set_header("Connection", "close");
  23817. });
  23818. auto port = svr.bind_to_any_port(HOST);
  23819. thread t = thread([&] { svr.listen_after_bind(); });
  23820. auto se = detail::scope_exit([&] {
  23821. svr.stop();
  23822. t.join();
  23823. });
  23824. svr.wait_until_ready();
  23825. auto error = Error::Success;
  23826. auto sock = detail::create_client_socket(
  23827. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23828. /*connection_timeout_sec=*/2, 0,
  23829. /*read_timeout_sec=*/1, 0,
  23830. /*write_timeout_sec=*/2, 0, std::string(), error);
  23831. ASSERT_NE(INVALID_SOCKET, sock);
  23832. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23833. std::string request = "POST /ingest HTTP/1.1\r\n"
  23834. "Host: localhost\r\n"
  23835. "Transfer-Encoding: chunked\r\n"
  23836. "\r\n"
  23837. "4\r\n"
  23838. "data\r\n";
  23839. auto sent = send(sock, request.data(), request.size(), 0);
  23840. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23841. std::string response;
  23842. ssize_t received = 0;
  23843. do {
  23844. char buf[4096];
  23845. received = recv(sock, buf, sizeof(buf), 0);
  23846. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23847. } while (received > 0);
  23848. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23849. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23850. EXPECT_EQ(0, received);
  23851. }
  23852. namespace no_proxy_test {
  23853. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23854. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23855. // calling listen().
  23856. class ScopedServer {
  23857. public:
  23858. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23859. ~ScopedServer() {
  23860. svr_.stop();
  23861. if (th_.joinable()) { th_.join(); }
  23862. }
  23863. Server &svr() { return svr_; }
  23864. int port() const { return port_; }
  23865. void listen() {
  23866. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23867. svr_.wait_until_ready();
  23868. }
  23869. private:
  23870. Server svr_;
  23871. std::thread th_;
  23872. int port_ = 0;
  23873. };
  23874. class ProxyAndTargetServers {
  23875. public:
  23876. ProxyAndTargetServers() {
  23877. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23878. proxy_hits_++;
  23879. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23880. res.set_content("via-proxy", "text/plain");
  23881. });
  23882. target_.Get(".*", [this](const Request &req, Response &res) {
  23883. target_hits_++;
  23884. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23885. res.set_content("direct", "text/plain");
  23886. });
  23887. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23888. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23889. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23890. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23891. proxy_mock_.wait_until_ready();
  23892. target_.wait_until_ready();
  23893. }
  23894. ~ProxyAndTargetServers() {
  23895. proxy_mock_.stop();
  23896. target_.stop();
  23897. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23898. if (target_thread_.joinable()) { target_thread_.join(); }
  23899. }
  23900. Server &proxy_mock() { return proxy_mock_; }
  23901. Server &target() { return target_; }
  23902. int proxy_port() const { return proxy_port_; }
  23903. int target_port() const { return target_port_; }
  23904. int proxy_hits() const { return proxy_hits_.load(); }
  23905. int target_hits() const { return target_hits_.load(); }
  23906. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23907. void reset_counters() {
  23908. proxy_hits_ = 0;
  23909. target_hits_ = 0;
  23910. last_had_proxy_authz_ = false;
  23911. }
  23912. private:
  23913. Server proxy_mock_;
  23914. Server target_;
  23915. std::thread proxy_thread_;
  23916. std::thread target_thread_;
  23917. int proxy_port_ = 0;
  23918. int target_port_ = 0;
  23919. std::atomic<int> proxy_hits_{0};
  23920. std::atomic<int> target_hits_{0};
  23921. std::atomic<bool> last_had_proxy_authz_{false};
  23922. };
  23923. inline std::unique_ptr<Client> make_client(const std::string &host,
  23924. ProxyAndTargetServers &s) {
  23925. auto cli = detail::make_unique<Client>(host, s.target_port());
  23926. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23927. cli->set_proxy("127.0.0.1", s.proxy_port());
  23928. return cli;
  23929. }
  23930. } // namespace no_proxy_test
  23931. using no_proxy_test::make_client;
  23932. using no_proxy_test::ProxyAndTargetServers;
  23933. TEST(NoProxyTest, ExactHostnameBypasses) {
  23934. ProxyAndTargetServers s;
  23935. auto cli = make_client("example.com", s);
  23936. cli->set_no_proxy({"example.com"});
  23937. auto res = cli->Get("/");
  23938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23939. EXPECT_EQ(0, s.proxy_hits());
  23940. EXPECT_EQ(1, s.target_hits());
  23941. }
  23942. TEST(NoProxyTest, SubdomainBypasses) {
  23943. ProxyAndTargetServers s;
  23944. auto cli = make_client("foo.example.com", s);
  23945. cli->set_no_proxy({"example.com"});
  23946. auto res = cli->Get("/");
  23947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23948. EXPECT_EQ(0, s.proxy_hits());
  23949. EXPECT_EQ(1, s.target_hits());
  23950. }
  23951. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23952. // Regression guard: "evilexample.com" must not be considered a subdomain
  23953. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23954. // check would let traffic bypass the proxy and leak credentials direct
  23955. // to the attacker host.
  23956. ProxyAndTargetServers s;
  23957. auto cli = make_client("evilexample.com", s);
  23958. cli->set_no_proxy({"example.com"});
  23959. auto res = cli->Get("/");
  23960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23961. EXPECT_GE(s.proxy_hits(), 1);
  23962. EXPECT_EQ(0, s.target_hits());
  23963. }
  23964. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23965. ProxyAndTargetServers s;
  23966. auto cli = make_client("example.com.evil.com", s);
  23967. cli->set_no_proxy({"example.com"});
  23968. auto res = cli->Get("/");
  23969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23970. EXPECT_GE(s.proxy_hits(), 1);
  23971. EXPECT_EQ(0, s.target_hits());
  23972. }
  23973. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23974. ProxyAndTargetServers s;
  23975. auto cli = make_client("example.com", s);
  23976. cli->set_no_proxy({".example.com"});
  23977. auto res = cli->Get("/");
  23978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23979. EXPECT_EQ(0, s.proxy_hits());
  23980. EXPECT_EQ(1, s.target_hits());
  23981. }
  23982. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23983. ProxyAndTargetServers s;
  23984. auto cli = make_client("Example.COM", s);
  23985. cli->set_no_proxy({"EXAMPLE.com"});
  23986. auto res = cli->Get("/");
  23987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23988. EXPECT_EQ(0, s.proxy_hits());
  23989. EXPECT_EQ(1, s.target_hits());
  23990. }
  23991. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23992. ProxyAndTargetServers s;
  23993. auto cli = make_client("example.com.", s);
  23994. cli->set_no_proxy({"example.com"});
  23995. auto res = cli->Get("/");
  23996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23997. EXPECT_EQ(0, s.proxy_hits());
  23998. EXPECT_EQ(1, s.target_hits());
  23999. }
  24000. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24001. // Trailing dots must be normalized on BOTH sides — host and entry.
  24002. // An implementation that only strips the host-side trailing dot would
  24003. // fail to match host "example.com" against entry "example.com." because
  24004. // a literal substring search would compare 11 chars against 12.
  24005. ProxyAndTargetServers s;
  24006. auto cli = make_client("example.com", s);
  24007. cli->set_no_proxy({"example.com."});
  24008. auto res = cli->Get("/");
  24009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24010. EXPECT_EQ(0, s.proxy_hits());
  24011. EXPECT_EQ(1, s.target_hits());
  24012. }
  24013. TEST(NoProxyTest, WildcardBypassesEverything) {
  24014. ProxyAndTargetServers s;
  24015. auto cli = make_client("anything.invalid.test", s);
  24016. cli->set_no_proxy({"*"});
  24017. auto res = cli->Get("/");
  24018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24019. EXPECT_EQ(0, s.proxy_hits());
  24020. EXPECT_EQ(1, s.target_hits());
  24021. }
  24022. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24023. ProxyAndTargetServers s;
  24024. Client cli("127.0.0.1", s.target_port());
  24025. cli.set_proxy("127.0.0.1", s.proxy_port());
  24026. cli.set_no_proxy({"127.0.0.1"});
  24027. auto res = cli.Get("/");
  24028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24029. EXPECT_EQ(0, s.proxy_hits());
  24030. EXPECT_EQ(1, s.target_hits());
  24031. }
  24032. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24033. ProxyAndTargetServers s;
  24034. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24035. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24036. cli.set_proxy("127.0.0.1", s.proxy_port());
  24037. cli.set_no_proxy({"::1"});
  24038. auto res = cli.Get("/");
  24039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24040. EXPECT_EQ(0, s.proxy_hits());
  24041. EXPECT_EQ(1, s.target_hits());
  24042. }
  24043. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24044. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24045. // must still be recognized as IPv6 for CIDR matching. Implementations
  24046. // that detect IPv6 only when the host begins with '[' would parse the
  24047. // host as a hostname and miss the match.
  24048. ProxyAndTargetServers s;
  24049. Client cli("fe80::1", s.target_port());
  24050. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24051. cli.set_proxy("127.0.0.1", s.proxy_port());
  24052. cli.set_no_proxy({"fe80::/10"});
  24053. auto res = cli.Get("/");
  24054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24055. EXPECT_EQ(0, s.proxy_hits());
  24056. EXPECT_EQ(1, s.target_hits());
  24057. }
  24058. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24059. ProxyAndTargetServers s;
  24060. Client cli("::1", s.target_port());
  24061. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24062. cli.set_proxy("127.0.0.1", s.proxy_port());
  24063. cli.set_no_proxy({"[::1]"});
  24064. auto res = cli.Get("/");
  24065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24066. EXPECT_EQ(0, s.proxy_hits());
  24067. EXPECT_EQ(1, s.target_hits());
  24068. }
  24069. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24070. ProxyAndTargetServers s;
  24071. Client cli("fe80::1", s.target_port());
  24072. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24073. cli.set_proxy("127.0.0.1", s.proxy_port());
  24074. cli.set_no_proxy({"[fe80::]/10"});
  24075. auto res = cli.Get("/");
  24076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24077. EXPECT_EQ(0, s.proxy_hits());
  24078. EXPECT_EQ(1, s.target_hits());
  24079. }
  24080. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24081. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24082. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24083. // tricks via address-family conversion.
  24084. ProxyAndTargetServers s;
  24085. Client cli("::ffff:127.0.0.1", s.target_port());
  24086. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24087. cli.set_proxy("127.0.0.1", s.proxy_port());
  24088. cli.set_no_proxy({"127.0.0.1"});
  24089. auto res = cli.Get("/");
  24090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24091. EXPECT_GE(s.proxy_hits(), 1);
  24092. EXPECT_EQ(0, s.target_hits());
  24093. }
  24094. TEST(NoProxyTest, IPv4CidrMatch) {
  24095. ProxyAndTargetServers s;
  24096. Client cli("127.0.0.1", s.target_port());
  24097. cli.set_proxy("127.0.0.1", s.proxy_port());
  24098. cli.set_no_proxy({"127.0.0.0/8"});
  24099. auto res = cli.Get("/");
  24100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24101. EXPECT_EQ(0, s.proxy_hits());
  24102. EXPECT_EQ(1, s.target_hits());
  24103. }
  24104. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24105. ProxyAndTargetServers s;
  24106. Client cli("127.0.0.1", s.target_port());
  24107. cli.set_proxy("127.0.0.1", s.proxy_port());
  24108. cli.set_no_proxy({"10.0.0.0/8"});
  24109. auto res = cli.Get("/");
  24110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24111. EXPECT_GE(s.proxy_hits(), 1);
  24112. EXPECT_EQ(0, s.target_hits());
  24113. }
  24114. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24115. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24116. // IPv4 target matches.
  24117. ProxyAndTargetServers s;
  24118. Client cli("127.0.0.1", s.target_port());
  24119. cli.set_proxy("127.0.0.1", s.proxy_port());
  24120. cli.set_no_proxy({"0.0.0.0/0"});
  24121. auto res = cli.Get("/");
  24122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24123. EXPECT_EQ(0, s.proxy_hits());
  24124. EXPECT_EQ(1, s.target_hits());
  24125. }
  24126. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24127. ProxyAndTargetServers s;
  24128. Client cli("127.0.0.1", s.target_port());
  24129. cli.set_proxy("127.0.0.1", s.proxy_port());
  24130. cli.set_no_proxy({"127.0.0.1"});
  24131. auto res = cli.Get("/");
  24132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24133. EXPECT_EQ(0, s.proxy_hits());
  24134. EXPECT_EQ(1, s.target_hits());
  24135. }
  24136. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24137. ProxyAndTargetServers s;
  24138. Client cli("127.0.0.1", s.target_port());
  24139. cli.set_proxy("127.0.0.1", s.proxy_port());
  24140. cli.set_no_proxy({"127.0.0.0/33"});
  24141. auto res = cli.Get("/");
  24142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24143. EXPECT_GE(s.proxy_hits(), 1);
  24144. EXPECT_EQ(0, s.target_hits());
  24145. }
  24146. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24147. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24148. ProxyAndTargetServers s;
  24149. Client cli("127.0.0.1", s.target_port());
  24150. cli.set_proxy("127.0.0.1", s.proxy_port());
  24151. cli.set_no_proxy({"127.0.0.1/"});
  24152. auto res = cli.Get("/");
  24153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24154. EXPECT_GE(s.proxy_hits(), 1);
  24155. EXPECT_EQ(0, s.target_hits());
  24156. }
  24157. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24158. ProxyAndTargetServers s;
  24159. auto cli = make_client("internal.corp", s);
  24160. cli->set_proxy_basic_auth("u", "p");
  24161. cli->set_no_proxy({"internal.corp"});
  24162. auto res = cli->Get("/");
  24163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24164. EXPECT_EQ(1, s.target_hits());
  24165. EXPECT_EQ(0, s.proxy_hits());
  24166. EXPECT_FALSE(s.last_had_proxy_authz())
  24167. << "Proxy-Authorization must not be sent direct to the target";
  24168. }
  24169. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24170. ProxyAndTargetServers s;
  24171. auto cli = make_client("public.example", s);
  24172. cli->set_proxy_basic_auth("u", "p");
  24173. cli->set_no_proxy({"internal.corp"}); // does not match
  24174. auto res = cli->Get("/");
  24175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24176. EXPECT_GE(s.proxy_hits(), 1);
  24177. EXPECT_TRUE(s.last_had_proxy_authz());
  24178. }
  24179. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24180. std::atomic<int> hits{0};
  24181. std::atomic<int> hits_with_authz{0};
  24182. no_proxy_test::ScopedServer proxy_mock;
  24183. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24184. hits++;
  24185. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24186. if (req.target.find("/redir") != std::string::npos) {
  24187. res.set_redirect("http://other.example/landed");
  24188. } else {
  24189. res.set_content("via-proxy", "text/plain");
  24190. }
  24191. });
  24192. proxy_mock.listen();
  24193. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24194. hits = 0;
  24195. hits_with_authz = 0;
  24196. Client cli("public.example", 80);
  24197. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24198. cli.set_proxy_basic_auth(c.first, c.second);
  24199. cli.set_follow_location(true);
  24200. // The redirect to another host goes through the proxy as well
  24201. auto res = cli.Get("/redir");
  24202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24203. EXPECT_EQ(2, hits.load());
  24204. EXPECT_EQ(2, hits_with_authz.load());
  24205. }
  24206. }
  24207. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24208. ProxyAndTargetServers s;
  24209. auto cli = make_client("anything.test", s);
  24210. auto res = cli->Get("/");
  24211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24212. EXPECT_GE(s.proxy_hits(), 1);
  24213. EXPECT_EQ(0, s.target_hits());
  24214. }
  24215. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24216. ProxyAndTargetServers s;
  24217. auto cli = make_client("example.com", s);
  24218. cli->set_no_proxy({"example.com:8080"});
  24219. auto res = cli->Get("/");
  24220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24221. EXPECT_GE(s.proxy_hits(), 1);
  24222. EXPECT_EQ(0, s.target_hits());
  24223. }
  24224. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24225. ProxyAndTargetServers s;
  24226. auto cli = make_client("anything.test", s);
  24227. cli->set_no_proxy({"", " ", "\t"});
  24228. auto res = cli->Get("/");
  24229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24230. EXPECT_GE(s.proxy_hits(), 1);
  24231. EXPECT_EQ(0, s.target_hits());
  24232. }
  24233. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24234. // An entry with leading/trailing whitespace must still match — env-style
  24235. // values are commonly pasted with stray spaces and an implementation
  24236. // that feeds the raw token directly to inet_pton would fail to match
  24237. // valid CIDRs because of the spaces.
  24238. ProxyAndTargetServers s;
  24239. Client cli("127.0.0.1", s.target_port());
  24240. cli.set_proxy("127.0.0.1", s.proxy_port());
  24241. cli.set_no_proxy({" 127.0.0.0/8 "});
  24242. auto res = cli.Get("/");
  24243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24244. EXPECT_EQ(0, s.proxy_hits());
  24245. EXPECT_EQ(1, s.target_hits());
  24246. }
  24247. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24248. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24249. // go direct and must NOT carry Proxy-Authorization.
  24250. std::atomic<int> proxy_hits{0};
  24251. std::atomic<int> target_hits{0};
  24252. std::atomic<bool> target_saw_authz{false};
  24253. no_proxy_test::ScopedServer proxy_mock, target;
  24254. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24255. proxy_hits++;
  24256. res.status = 302;
  24257. res.set_header("Location", "http://127.0.0.1:" +
  24258. std::to_string(target.port()) + "/landed");
  24259. });
  24260. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24261. target_hits++;
  24262. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24263. res.set_content("direct", "text/plain");
  24264. });
  24265. proxy_mock.listen();
  24266. target.listen();
  24267. Client cli("public.example", target.port());
  24268. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24269. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24270. cli.set_proxy_basic_auth("u", "p");
  24271. cli.set_no_proxy({"127.0.0.1"});
  24272. cli.set_follow_location(true);
  24273. auto res = cli.Get("/redir");
  24274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24275. EXPECT_GE(proxy_hits.load(), 1);
  24276. EXPECT_GE(target_hits.load(), 1);
  24277. EXPECT_FALSE(target_saw_authz.load());
  24278. }
  24279. #ifdef CPPHTTPLIB_SSL_ENABLED
  24280. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24281. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24282. // proxy creds would be sent to the (possibly hostile) origin.
  24283. std::atomic<int> target_hits{0};
  24284. std::atomic<bool> target_saw_proxy_authz{false};
  24285. no_proxy_test::ScopedServer target;
  24286. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24287. target_hits++;
  24288. if (req.has_header("Proxy-Authorization")) {
  24289. target_saw_proxy_authz = true;
  24290. }
  24291. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24292. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24293. "nonce=\"abc\", algorithm=MD5");
  24294. });
  24295. target.listen();
  24296. // The proxy address is set to the target's port: the bypass MUST kick in;
  24297. // if it doesn't, the test still routes "via proxy" to the same server and
  24298. // the Proxy-Authorization assertion below catches the leak.
  24299. Client cli("evil.example", target.port());
  24300. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24301. cli.set_proxy("127.0.0.1", target.port());
  24302. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24303. cli.set_no_proxy({"evil.example"});
  24304. auto res = cli.Get("/x");
  24305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24306. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24307. EXPECT_EQ(1, target_hits.load());
  24308. EXPECT_FALSE(target_saw_proxy_authz.load());
  24309. }
  24310. #endif
  24311. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24312. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24313. std::atomic<int> proxy_hits{0};
  24314. std::atomic<int> bypass_hits{0};
  24315. std::atomic<bool> proxy_saw_c_url{false};
  24316. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24317. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24318. proxy_hits++;
  24319. if (req.path.find("/start") != std::string::npos) {
  24320. res.status = 302;
  24321. res.set_header("Location", "http://127.0.0.1:" +
  24322. std::to_string(bypass_server.port()) +
  24323. "/middle");
  24324. return;
  24325. }
  24326. if (req.path.find("/end") != std::string::npos) {
  24327. proxy_saw_c_url = true;
  24328. res.set_content("c-via-proxy", "text/plain");
  24329. return;
  24330. }
  24331. res.set_content("unexpected", "text/plain");
  24332. });
  24333. // public.example's "advertised" port is arbitrary (the request never lands
  24334. // there — it goes through the proxy), but use a dynamic value to stay
  24335. // friendly with sharded parallel runs.
  24336. int public_port = bypass_server.port();
  24337. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24338. bypass_hits++;
  24339. res.status = 302;
  24340. res.set_header("Location", "http://public.example:" +
  24341. std::to_string(public_port) + "/end");
  24342. });
  24343. proxy_mock.listen();
  24344. bypass_server.listen();
  24345. Client cli("public.example", public_port);
  24346. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24347. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24348. cli.set_no_proxy({"127.0.0.1"});
  24349. cli.set_follow_location(true);
  24350. auto res = cli.Get("/start");
  24351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24352. EXPECT_EQ(StatusCode::OK_200, res->status);
  24353. EXPECT_EQ("c-via-proxy", res->body);
  24354. EXPECT_GE(proxy_hits.load(), 2);
  24355. EXPECT_GE(bypass_hits.load(), 1);
  24356. EXPECT_TRUE(proxy_saw_c_url.load());
  24357. }
  24358. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24359. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24360. // request reconnects to the correct endpoint.
  24361. std::atomic<int> proxy_hits{0};
  24362. std::atomic<int> target_hits{0};
  24363. no_proxy_test::ScopedServer proxy_mock, target;
  24364. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24365. proxy_hits++;
  24366. res.set_content("via-proxy", "text/plain");
  24367. });
  24368. target.svr().Get(".*", [&](const Request &, Response &res) {
  24369. target_hits++;
  24370. res.set_content("direct", "text/plain");
  24371. });
  24372. proxy_mock.listen();
  24373. target.listen();
  24374. Client cli("public.example", target.port());
  24375. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24376. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24377. cli.set_keep_alive(true);
  24378. auto res1 = cli.Get("/a");
  24379. ASSERT_TRUE(res1);
  24380. EXPECT_EQ("via-proxy", res1->body);
  24381. EXPECT_EQ(1, proxy_hits.load());
  24382. EXPECT_EQ(0, target_hits.load());
  24383. cli.set_no_proxy({"public.example"});
  24384. auto res2 = cli.Get("/b");
  24385. ASSERT_TRUE(res2);
  24386. EXPECT_EQ("direct", res2->body);
  24387. EXPECT_EQ(1, proxy_hits.load());
  24388. EXPECT_EQ(1, target_hits.load());
  24389. }
  24390. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24391. namespace proxy_tunnel_test {
  24392. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24393. class ScopedSSLServer {
  24394. public:
  24395. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24396. port_ = svr_.bind_to_any_port("127.0.0.1");
  24397. }
  24398. ~ScopedSSLServer() {
  24399. svr_.stop();
  24400. if (th_.joinable()) { th_.join(); }
  24401. }
  24402. SSLServer &svr() { return svr_; }
  24403. int port() const { return port_; }
  24404. void listen() {
  24405. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24406. svr_.wait_until_ready();
  24407. }
  24408. private:
  24409. SSLServer svr_;
  24410. std::thread th_;
  24411. int port_ = 0;
  24412. };
  24413. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24414. class ScopedConnectProxy {
  24415. public:
  24416. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24417. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24418. if (listen_fd_ < 0) { return; }
  24419. int yes = 1;
  24420. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24421. sockaddr_in a{};
  24422. a.sin_family = AF_INET;
  24423. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24424. a.sin_port = 0;
  24425. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24426. return;
  24427. }
  24428. socklen_t alen = sizeof(a);
  24429. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24430. 0) {
  24431. return;
  24432. }
  24433. port_ = ntohs(a.sin_port);
  24434. if (::listen(listen_fd_, 1) != 0) { return; }
  24435. th_ = std::thread([this] { run(); });
  24436. }
  24437. ~ScopedConnectProxy() {
  24438. stop_ = true;
  24439. if (listen_fd_ >= 0) {
  24440. ::shutdown(listen_fd_, SHUT_RDWR);
  24441. ::close(listen_fd_);
  24442. }
  24443. if (th_.joinable()) { th_.join(); }
  24444. }
  24445. int port() const { return port_; }
  24446. int connect_hits() const { return connect_hits_.load(); }
  24447. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24448. std::string connect_request() const {
  24449. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24450. return connect_request_;
  24451. }
  24452. private:
  24453. void run() {
  24454. while (!stop_.load()) {
  24455. fd_set rfds;
  24456. FD_ZERO(&rfds);
  24457. FD_SET(listen_fd_, &rfds);
  24458. timeval tv{0, 100 * 1000};
  24459. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24460. if (sel <= 0) { continue; }
  24461. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24462. if (client_fd < 0) { continue; }
  24463. std::string req;
  24464. char buf[2048];
  24465. while (req.find("\r\n\r\n") == std::string::npos) {
  24466. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24467. if (n <= 0) { break; }
  24468. req.append(buf, static_cast<size_t>(n));
  24469. }
  24470. if (req.compare(0, 7, "CONNECT") != 0) {
  24471. ::close(client_fd);
  24472. continue;
  24473. }
  24474. connect_hits_++;
  24475. {
  24476. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24477. connect_request_ = req;
  24478. }
  24479. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24480. ::send(client_fd, ok, std::strlen(ok), 0);
  24481. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24482. sockaddr_in o{};
  24483. o.sin_family = AF_INET;
  24484. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24485. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24486. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24487. 0) {
  24488. ::close(client_fd);
  24489. ::close(origin_fd);
  24490. continue;
  24491. }
  24492. auto forward = [](int from, int to) {
  24493. char b[8192];
  24494. for (;;) {
  24495. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24496. if (n <= 0) { break; }
  24497. ssize_t off = 0;
  24498. while (off < n) {
  24499. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24500. if (s <= 0) {
  24501. off = n;
  24502. break;
  24503. }
  24504. off += s;
  24505. }
  24506. }
  24507. ::shutdown(to, SHUT_WR);
  24508. };
  24509. std::thread t1([&] { forward(client_fd, origin_fd); });
  24510. std::thread t2([&] { forward(origin_fd, client_fd); });
  24511. t1.join();
  24512. t2.join();
  24513. ::close(client_fd);
  24514. ::close(origin_fd);
  24515. }
  24516. }
  24517. int forward_port_ = -1;
  24518. int listen_fd_ = -1;
  24519. int port_ = 0;
  24520. std::thread th_;
  24521. std::atomic<bool> stop_{false};
  24522. std::atomic<int> connect_hits_{0};
  24523. mutable std::mutex connect_request_mutex_;
  24524. std::string connect_request_;
  24525. };
  24526. // Sends one request through the CONNECT proxy to the TLS origin with a
  24527. // credential configured for each hop, and checks that each credential reaches
  24528. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24529. // origin's (every header in origin_headers) on the tunnelled request.
  24530. void CredentialsStayWithTheirHop(
  24531. const std::function<void(SSLClient &)> &set_credentials,
  24532. const std::string &scheme,
  24533. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24534. std::atomic<int> origin_hits{0};
  24535. std::atomic<bool> origin_saw_proxy_authz{false};
  24536. std::atomic<bool> origin_saw_headers{false};
  24537. ScopedSSLServer origin;
  24538. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24539. origin_hits++;
  24540. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24541. origin_saw_headers =
  24542. std::all_of(origin_headers.begin(), origin_headers.end(),
  24543. [&](const std::string &h) { return req.has_header(h); });
  24544. res.set_content("ok", "text/plain");
  24545. });
  24546. origin.listen();
  24547. ScopedConnectProxy proxy(origin.port());
  24548. ASSERT_NE(0, proxy.port());
  24549. // Pinned to 127.0.0.1 for the same reason as the test below.
  24550. SSLClient cli("127.0.0.1", origin.port());
  24551. cli.enable_server_certificate_verification(false);
  24552. cli.set_proxy("127.0.0.1", proxy.port());
  24553. set_credentials(cli);
  24554. auto res = cli.Get("/x");
  24555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24556. EXPECT_EQ(StatusCode::OK_200, res->status);
  24557. EXPECT_EQ(1, origin_hits.load());
  24558. EXPECT_EQ(1, proxy.connect_hits());
  24559. EXPECT_TRUE(origin_saw_headers.load());
  24560. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24561. << "Proxy-Authorization must not be sent inside the tunnel";
  24562. auto connect_req = proxy.connect_request();
  24563. EXPECT_NE(std::string::npos,
  24564. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24565. for (const auto &h : origin_headers) {
  24566. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24567. << h << " must not be sent to the proxy on CONNECT";
  24568. }
  24569. }
  24570. } // namespace proxy_tunnel_test
  24571. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24572. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24573. [](SSLClient &cli) {
  24574. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24575. cli.set_basic_auth("origin-user", "origin-pass");
  24576. },
  24577. "Basic");
  24578. }
  24579. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24580. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24581. [](SSLClient &cli) {
  24582. cli.set_proxy_bearer_token_auth("proxy-token");
  24583. cli.set_bearer_token_auth("origin-token");
  24584. },
  24585. "Bearer");
  24586. }
  24587. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24588. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24589. [](SSLClient &cli) {
  24590. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24591. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24592. {"Cookie", "sid=origin-session"},
  24593. {"X-Api-Key", "origin-key"}});
  24594. },
  24595. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24596. }
  24597. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24598. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24599. // retry; otherwise proxy creds would be sent to the origin.
  24600. std::atomic<int> origin_hits{0};
  24601. std::atomic<bool> origin_saw_proxy_authz{false};
  24602. proxy_tunnel_test::ScopedSSLServer origin;
  24603. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24604. origin_hits++;
  24605. if (req.has_header("Proxy-Authorization")) {
  24606. origin_saw_proxy_authz = true;
  24607. }
  24608. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24609. res.set_header("Proxy-Authenticate",
  24610. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24611. "algorithm=MD5");
  24612. });
  24613. origin.listen();
  24614. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24615. ASSERT_NE(0, proxy.port());
  24616. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24617. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24618. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24619. // and answer with its own status, making this test flaky.
  24620. SSLClient cli("127.0.0.1", origin.port());
  24621. cli.enable_server_certificate_verification(false);
  24622. cli.set_proxy("127.0.0.1", proxy.port());
  24623. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24624. auto res = cli.Get("/x");
  24625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24626. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24627. EXPECT_EQ(1, origin_hits.load());
  24628. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24629. EXPECT_EQ(1, proxy.connect_hits());
  24630. }
  24631. #endif