1
0

test.cc 993 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. } // namespace tls
  69. } // namespace httplib
  70. #endif
  71. using namespace std;
  72. using namespace httplib;
  73. const char *HOST = "localhost";
  74. static int get_base_port() {
  75. const char *shard = getenv("GTEST_SHARD_INDEX");
  76. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  77. }
  78. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  79. // New standalone tests MUST use svr.bind_to_any_port() instead.
  80. const int PORT = get_base_port();
  81. const string LONG_QUERY_VALUE = string(25000, '@');
  82. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  83. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  84. const string TOO_LONG_QUERY_URL =
  85. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  86. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  87. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  88. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  89. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  90. return file.name == key;
  91. });
  92. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  93. return *it;
  94. #else
  95. if (it != items.end()) { return *it; }
  96. throw std::runtime_error("invalid multipart form data name error");
  97. #endif
  98. }
  99. static void read_file(const std::string &path, std::string &out) {
  100. std::ifstream fs(path, std::ios_base::binary);
  101. if (!fs) {
  102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  103. return;
  104. #else
  105. throw std::runtime_error("File not found: " + path);
  106. #endif
  107. }
  108. fs.seekg(0, std::ios_base::end);
  109. auto size = fs.tellg();
  110. fs.seekg(0);
  111. out.resize(static_cast<size_t>(size));
  112. fs.read(&out[0], static_cast<std::streamsize>(size));
  113. }
  114. class UnixSocketTest : public ::testing::Test {
  115. protected:
  116. void TearDown() override { std::remove(pathname_.c_str()); }
  117. void client_GET(const std::string &addr) {
  118. httplib::Client cli{addr};
  119. cli.set_address_family(AF_UNIX);
  120. ASSERT_TRUE(cli.is_valid());
  121. const auto &result = cli.Get(pattern_);
  122. ASSERT_TRUE(result) << "error: " << result.error();
  123. const auto &resp = result.value();
  124. EXPECT_EQ(resp.status, StatusCode::OK_200);
  125. EXPECT_EQ(resp.body, content_);
  126. }
  127. static std::string make_sock_path() {
  128. const char *shard = getenv("GTEST_SHARD_INDEX");
  129. return shard ? std::string("./httplib-server-") + shard + ".sock"
  130. : "./httplib-server.sock";
  131. }
  132. const std::string pathname_{make_sock_path()};
  133. const std::string pattern_{"/hi"};
  134. const std::string content_{"Hello World!"};
  135. };
  136. TEST_F(UnixSocketTest, pathname) {
  137. httplib::Server svr;
  138. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  139. res.set_content(content_, "text/plain");
  140. });
  141. std::thread t{[&] {
  142. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  143. }};
  144. auto se = detail::scope_exit([&] {
  145. svr.stop();
  146. t.join();
  147. ASSERT_FALSE(svr.is_running());
  148. });
  149. svr.wait_until_ready();
  150. ASSERT_TRUE(svr.is_running());
  151. client_GET(pathname_);
  152. // ".//x.sock", which is not taken for a URL
  153. client_GET("./" + pathname_.substr(1));
  154. }
  155. #if defined(__linux__) || \
  156. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  157. TEST_F(UnixSocketTest, PeerPid) {
  158. httplib::Server svr;
  159. std::string remote_port_val;
  160. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  161. res.set_content(content_, "text/plain");
  162. remote_port_val = std::to_string(req.remote_port);
  163. });
  164. std::thread t{[&] {
  165. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  166. }};
  167. auto se = detail::scope_exit([&] {
  168. svr.stop();
  169. t.join();
  170. ASSERT_FALSE(svr.is_running());
  171. });
  172. svr.wait_until_ready();
  173. ASSERT_TRUE(svr.is_running());
  174. client_GET(pathname_);
  175. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  176. }
  177. #endif
  178. #ifdef __linux__
  179. TEST_F(UnixSocketTest, abstract) {
  180. constexpr char svr_path[]{"\x00httplib-server.sock"};
  181. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  182. httplib::Server svr;
  183. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. client_GET(abstract_addr);
  197. }
  198. #endif
  199. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  200. httplib::Server svr;
  201. std::string received_host_header;
  202. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  203. // Capture the Host header sent by the client
  204. auto host_iter = req.headers.find("Host");
  205. if (host_iter != req.headers.end()) {
  206. received_host_header = host_iter->second;
  207. }
  208. res.set_content(content_, "text/plain");
  209. });
  210. std::thread t{[&] {
  211. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  212. }};
  213. auto se = detail::scope_exit([&] {
  214. svr.stop();
  215. t.join();
  216. ASSERT_FALSE(svr.is_running());
  217. });
  218. svr.wait_until_ready();
  219. ASSERT_TRUE(svr.is_running());
  220. // Test that Host header is automatically set to "localhost" for Unix socket
  221. // connections
  222. httplib::Client cli{pathname_};
  223. cli.set_address_family(AF_UNIX);
  224. ASSERT_TRUE(cli.is_valid());
  225. const auto &result = cli.Get(pattern_);
  226. ASSERT_TRUE(result) << "error: " << result.error();
  227. const auto &resp = result.value();
  228. EXPECT_EQ(resp.status, StatusCode::OK_200);
  229. EXPECT_EQ(resp.body, content_);
  230. // Verify that Host header was automatically set to "localhost"
  231. EXPECT_EQ(received_host_header, "localhost");
  232. }
  233. #ifndef _WIN32
  234. TEST(SocketStream, wait_writable_UNIX) {
  235. int fds[2];
  236. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  237. const auto asSocketStream = [&](socket_t fd,
  238. std::function<bool(Stream &)> func) {
  239. return detail::process_client_socket(
  240. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  241. };
  242. asSocketStream(fds[0], [&](Stream &s0) {
  243. EXPECT_EQ(s0.socket(), fds[0]);
  244. EXPECT_TRUE(s0.wait_writable());
  245. EXPECT_TRUE(s0.is_peer_alive());
  246. EXPECT_EQ(0, close(fds[1]));
  247. EXPECT_FALSE(s0.is_peer_alive());
  248. return true;
  249. });
  250. EXPECT_EQ(0, close(fds[0]));
  251. }
  252. TEST(SocketStream, wait_writable_INET) {
  253. sockaddr_in addr;
  254. memset(&addr, 0, sizeof(addr));
  255. addr.sin_family = AF_INET;
  256. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  257. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  258. int disconnected_svr_sock = -1;
  259. std::thread svr{[&] {
  260. const int s = socket(AF_INET, SOCK_STREAM, 0);
  261. ASSERT_LE(0, s);
  262. // PORT + 1 is shared with the SSL redirect tests and with
  263. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  264. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  265. // because that happens on a worker thread the ASSERT does not stop the
  266. // test: it runs on and fails at the disconnected_svr_sock check instead.
  267. default_socket_options(s);
  268. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  269. ASSERT_EQ(0, listen(s, 1));
  270. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  271. ASSERT_EQ(0, close(s));
  272. }};
  273. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  274. std::thread cli{[&] {
  275. const int s = socket(AF_INET, SOCK_STREAM, 0);
  276. ASSERT_LE(0, s);
  277. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  278. ASSERT_EQ(0, close(s));
  279. }};
  280. cli.join();
  281. svr.join();
  282. ASSERT_NE(disconnected_svr_sock, -1);
  283. const auto asSocketStream = [&](socket_t fd,
  284. std::function<bool(Stream &)> func) {
  285. return detail::process_client_socket(
  286. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  287. };
  288. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  289. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  290. // wait_writable() returns true because select_write() only checks if the
  291. // send buffer has space. Peer disconnection is detected later by send().
  292. EXPECT_TRUE(ss.wait_writable());
  293. return true;
  294. });
  295. ASSERT_EQ(0, close(disconnected_svr_sock));
  296. }
  297. #endif // #ifndef _WIN32
  298. TEST(SetSocketOptTest, TcpNoDelay) {
  299. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  300. ASSERT_NE(sock, INVALID_SOCKET);
  301. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  302. int val = 0;
  303. socklen_t len = sizeof(val);
  304. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  305. reinterpret_cast<char *>(&val), &len));
  306. EXPECT_NE(val, 0);
  307. detail::close_socket(sock);
  308. }
  309. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  310. // accept() reports failures through WSAGetLastError() on Windows and through
  311. // errno everywhere else. Asking the wrong one is what made the accept loop
  312. // treat every recoverable failure as fatal on Windows.
  313. struct Classification {
  314. bool resource;
  315. bool transient;
  316. };
  317. auto classify = [](int err) {
  318. #ifdef _WIN32
  319. WSASetLastError(err);
  320. #else
  321. errno = err;
  322. #endif
  323. // Read both before asserting: an assertion may clobber the error slot.
  324. Classification c;
  325. c.resource = detail::is_accept_resource_error();
  326. c.transient = detail::is_accept_transient_error();
  327. return c;
  328. };
  329. #ifdef _WIN32
  330. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  331. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  332. WSAECONNRESET, WSAECONNABORTED};
  333. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  334. #else
  335. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  336. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  337. ECONNABORTED};
  338. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  339. #endif
  340. for (auto err : resource_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.resource) << "error " << err;
  343. EXPECT_FALSE(c.transient) << "error " << err;
  344. }
  345. for (auto err : transient_errors) {
  346. const auto c = classify(err);
  347. EXPECT_TRUE(c.transient) << "error " << err;
  348. EXPECT_FALSE(c.resource) << "error " << err;
  349. }
  350. for (auto err : fatal_errors) {
  351. const auto c = classify(err);
  352. EXPECT_FALSE(c.resource) << "error " << err;
  353. EXPECT_FALSE(c.transient) << "error " << err;
  354. }
  355. #ifdef _WIN32
  356. WSASetLastError(0);
  357. #else
  358. errno = 0;
  359. #endif
  360. }
  361. TEST(ClientTest, MoveConstructible) {
  362. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  363. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  364. }
  365. TEST(ClientTest, MoveAssignable) {
  366. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  367. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  368. }
  369. #ifdef _WIN32
  370. TEST(StartupTest, WSAStartup) {
  371. WSADATA wsaData;
  372. int ret = WSAStartup(0x0002, &wsaData);
  373. ASSERT_EQ(0, ret);
  374. }
  375. #endif
  376. TEST(DecodePathTest, PercentCharacter) {
  377. EXPECT_EQ(
  378. decode_path_component(
  379. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  380. U8("descrip=Gastos áéíóúñÑ 6"));
  381. }
  382. TEST(DecodePathTest, PercentCharacterNUL) {
  383. string expected;
  384. expected.push_back('x');
  385. expected.push_back('\0');
  386. expected.push_back('x');
  387. EXPECT_EQ(decode_path_component("x%00x"), expected);
  388. }
  389. TEST(DecodePathTest, UnicodeEncoding) {
  390. // %u0041 = 'A' (1-byte UTF-8)
  391. EXPECT_EQ("A", decode_path_component("%u0041"));
  392. // %u00E9 = 'é' (2-byte UTF-8)
  393. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  394. // %u3042 = 'あ' (3-byte UTF-8)
  395. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  396. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  397. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  398. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  399. // neighbours)
  400. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  401. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  402. }
  403. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  404. // A sign or whitespace inside the two-character escape window must not be
  405. // accepted as a valid percent-encoding; the sequence is passed through
  406. // literally, matching decode_uri_component / decode_path_component.
  407. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  408. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  409. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  410. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  411. // Well-formed escapes still decode.
  412. EXPECT_EQ("-", decode_query_component("%2D", false));
  413. EXPECT_EQ("A", decode_query_component("%41", false));
  414. }
  415. TEST(SanitizeFilenameTest, VariousPatterns) {
  416. // Path traversal
  417. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  419. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  420. // Normal and edge cases
  421. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  422. EXPECT_EQ("filename.txt",
  423. httplib::sanitize_filename("/path/to/filename.txt"));
  424. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  425. EXPECT_EQ("", httplib::sanitize_filename(".."));
  426. EXPECT_EQ("", httplib::sanitize_filename(""));
  427. // Null bytes stripped
  428. EXPECT_EQ("safe.txt",
  429. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  430. // Whitespace-only rejected
  431. EXPECT_EQ("", httplib::sanitize_filename(" "));
  432. }
  433. // Forward declaration (see the base64_encode note below): split builds move the
  434. // definition into httplib.cc, so re-declaring it here lets the test link.
  435. namespace httplib {
  436. namespace detail {
  437. bool is_chunked_transfer_encoding(const Headers &headers);
  438. } // namespace detail
  439. } // namespace httplib
  440. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  441. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  442. auto make = [](std::initializer_list<const char *> lines) {
  443. Headers h;
  444. for (auto te : lines) {
  445. if (te) { h.emplace("Transfer-Encoding", te); }
  446. }
  447. return h;
  448. };
  449. // Sole coding, matched case-insensitively.
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  453. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  457. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  462. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  463. // were received, into one list. Headers preserves that order, so the answer
  464. // is decided by the last coding of the last line and the order the lines
  465. // arrived in is significant.
  466. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  467. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  469. // The split can fall anywhere in the list.
  470. EXPECT_TRUE(
  471. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  472. EXPECT_FALSE(
  473. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  474. // A trailing line naming no coding leaves the list ending in nothing, so it
  475. // must not inherit the chunked from the line before it.
  476. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  477. }
  478. // Forward declarations (see the base64_encode note below).
  479. namespace httplib {
  480. namespace detail {
  481. bool parse_status_line(const char *line, std::string &version, int &status,
  482. std::string &reason);
  483. std::string file_extension(const std::string &path);
  484. std::string
  485. find_content_type(const std::string &path,
  486. const std::map<std::string, std::string> &user_data,
  487. const std::string &default_content_type);
  488. bool can_compress_content_type(const std::string &content_type);
  489. bool is_prohibited_header_name(const std::string &name);
  490. #ifdef CPPHTTPLIB_SSL_ENABLED
  491. bool match_hostname(const std::string &pattern, const std::string &hostname);
  492. #endif
  493. } // namespace detail
  494. } // namespace httplib
  495. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  496. struct {
  497. const char *line;
  498. const char *version;
  499. int status;
  500. const char *reason;
  501. } cases[] = {
  502. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  503. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  504. // The reason phrase may be empty, or left out along with its space.
  505. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  506. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  507. };
  508. for (const auto &c : cases) {
  509. std::string version;
  510. int status = 0;
  511. std::string reason = "unset";
  512. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  513. << c.line;
  514. EXPECT_EQ(c.version, version);
  515. EXPECT_EQ(c.status, status);
  516. EXPECT_EQ(c.reason, reason);
  517. }
  518. }
  519. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  520. const char *lines[] = {
  521. "HTTP/2 200 OK\r\n",
  522. "HTTP/1.2 200 OK\r\n",
  523. "HTTP/1.1 20 OK\r\n",
  524. "HTTP/1.1 2000 OK\r\n",
  525. "HTTP/1.1 2x0 OK\r\n",
  526. "HTTP/1.1 200 OK\r\n",
  527. "HTTP/1.1 200OK\r\n",
  528. "HTTP/1.1 200 O\rK\r\n",
  529. "HTTP/1.1 200 OK",
  530. "HTTP/1.1 200 OK\r\nX",
  531. "",
  532. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  533. "HTTP/1.1 200 OK\n",
  534. #endif
  535. };
  536. for (auto line : lines) {
  537. std::string version;
  538. int status = 0;
  539. std::string reason;
  540. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  541. << line;
  542. }
  543. }
  544. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  545. // Long enough to overflow the stack when matched with std::regex.
  546. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  547. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  548. std::string version;
  549. int status = 0;
  550. std::string reason;
  551. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  552. EXPECT_EQ(200, status);
  553. EXPECT_EQ(long_reason, reason);
  554. }
  555. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  556. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  557. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  558. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  559. EXPECT_EQ("", detail::file_extension("noext"));
  560. EXPECT_EQ("", detail::file_extension("a."));
  561. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  562. EXPECT_EQ("", detail::file_extension("a.b-c"));
  563. // Long enough to overflow the stack when matched with std::regex.
  564. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  565. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  566. }
  567. #ifdef CPPHTTPLIB_SSL_ENABLED
  568. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  569. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  570. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  572. // A wildcard needs two labels after it, in the leftmost label only
  573. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  574. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  575. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  576. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  577. EXPECT_FALSE(
  578. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  579. // No name may have an empty label
  580. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  581. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  582. }
  583. #endif
  584. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  585. detail::case_ignore::hash hash;
  586. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  587. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  588. // Long enough to overflow the stack if hashed one call per character.
  589. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  590. }
  591. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  592. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  593. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  594. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  595. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  596. // Same 26-bit hash as html, svg and js.
  597. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  598. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  600. }
  601. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  602. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  603. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  604. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  605. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  606. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  607. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  608. // Same 26-bit hash as application/json.
  609. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  610. }
  611. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  612. Request req;
  613. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  614. EXPECT_TRUE(req.is_multipart_form_data());
  615. std::string boundary;
  616. EXPECT_TRUE(detail::parse_multipart_boundary(
  617. req.get_header_value("Content-Type"), boundary));
  618. EXPECT_EQ("x", boundary);
  619. }
  620. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  621. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  622. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  623. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  624. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  625. // Same 26-bit hash as REMOTE_ADDR.
  626. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  627. }
  628. // Forward declaration: in split builds split.py strips `inline` and moves the
  629. // definition into httplib.cc, so detail::base64_encode is not visible from the
  630. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  631. // in both header-only and split builds.
  632. namespace httplib {
  633. namespace detail {
  634. std::string base64_encode(const std::string &in);
  635. } // namespace detail
  636. } // namespace httplib
  637. TEST(Base64EncodeTest, KnownAnswers) {
  638. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  639. // where the accumulator's top bit is already set before the next shift.
  640. EXPECT_EQ("", detail::base64_encode(""));
  641. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  642. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  643. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  644. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  645. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  646. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  647. // High bytes keep the top bit set across several rounds.
  648. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  649. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  650. }
  651. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  652. string unescapedCharacters = "-_.!~*'()";
  653. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  654. }
  655. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  656. string reservedCharacters = ";,/?:@&=+$";
  657. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  658. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  659. }
  660. TEST(ClientQueryOrder, PreserveOrder) {
  661. // This test reproduces Issue #2259: client may reorder query parameters
  662. // when sending a GET request. The expected behavior is that the client
  663. // preserves the original query string order when the caller supplied it
  664. // as part of the path.
  665. Server svr;
  666. svr.Get("/", [&](const Request &req, Response &res) {
  667. // Echo back the raw target so the test can assert ordering
  668. res.set_content(req.target, "text/plain");
  669. });
  670. std::thread t{[&] { svr.listen(HOST, PORT); }};
  671. auto se = detail::scope_exit([&] {
  672. svr.stop();
  673. t.join();
  674. ASSERT_FALSE(svr.is_running());
  675. });
  676. svr.wait_until_ready();
  677. Client cli(HOST, PORT);
  678. ASSERT_TRUE(cli.is_valid());
  679. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  680. auto res = cli.Get(original);
  681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  682. // Expect the echoed target to exactly match the original path (order
  683. // preserved)
  684. EXPECT_EQ(res->body, original);
  685. }
  686. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  687. string chineseCharacters = U8("中国語");
  688. string russianCharacters = U8("дом");
  689. string brazilianCharacters = U8("óculos");
  690. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  691. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  692. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  693. "%D0%B4%D0%BE%D0%BC");
  694. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  695. }
  696. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  697. string unescapedCharacters = "-_.!~*'()";
  698. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  699. }
  700. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  701. string reservedCharacters = ";,/?:@&=+$";
  702. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  703. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  704. }
  705. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  706. string chineseCharacters = U8("中国語");
  707. string russianCharacters = U8("дом");
  708. string brazilianCharacters = U8("óculos");
  709. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  710. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  711. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  712. "%D0%B4%D0%BE%D0%BC");
  713. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  714. }
  715. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  716. // Issue #2082 use case: encoding path component with ampersand
  717. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  718. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  719. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  720. }
  721. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  722. string unescapedCharacters = "-_.!~*'()";
  723. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  724. }
  725. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  726. string reservedCharacters = ";,/?:@&=+$#";
  727. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  728. }
  729. TEST(EncodeUriTest, TestUTF8Characters) {
  730. string chineseCharacters = U8("中国語");
  731. string russianCharacters = U8("дом");
  732. string brazilianCharacters = U8("óculos");
  733. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  734. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  735. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  736. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  737. }
  738. TEST(EncodeUriTest, TestCompleteUri) {
  739. string uri =
  740. "https://example.com/path/to/resource?query=value&param=test#fragment";
  741. EXPECT_EQ(
  742. httplib::encode_uri(uri),
  743. "https://example.com/path/to/resource?query=value&param=test#fragment");
  744. }
  745. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  746. string uri =
  747. "https://example.com/path with spaces/file name.html?q=hello world";
  748. EXPECT_EQ(httplib::encode_uri(uri),
  749. "https://example.com/path%20with%20spaces/"
  750. "file%20name.html?q=hello%20world");
  751. }
  752. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  753. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  754. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  755. }
  756. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  757. string unescapedCharacters = "-_.!~*'()";
  758. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  759. }
  760. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  761. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  762. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  763. string encodedBrazilian = "%C3%B3culos";
  764. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  765. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  767. }
  768. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  769. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  770. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  771. "Piri Tommy Villiers - on & on");
  772. }
  773. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  774. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  775. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  776. }
  777. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  778. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  779. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  780. }
  781. TEST(DecodeUriTest, TestUTF8Characters) {
  782. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  783. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  784. string encodedBrazilian = "%C3%B3culos";
  785. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  786. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  787. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  788. }
  789. TEST(DecodeUriTest, TestCompleteUri) {
  790. string encodedUri = "https://example.com/path%20with%20spaces/"
  791. "file%20name.html?q=hello%20world";
  792. EXPECT_EQ(
  793. httplib::decode_uri(encodedUri),
  794. "https://example.com/path with spaces/file name.html?q=hello world");
  795. }
  796. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  797. string original =
  798. "https://example.com/path with spaces/file name.html?q=hello world";
  799. string encoded = httplib::encode_uri(original);
  800. string decoded = httplib::decode_uri(encoded);
  801. EXPECT_EQ(decoded, original);
  802. }
  803. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  804. // decode_uri is the inverse of encode_uri: an escaped reserved character
  805. // stays encoded so it is not promoted into a real delimiter, while
  806. // non-reserved escapes still decode (like JS decodeURI).
  807. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  808. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  809. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  810. "%3F%3A%40%26%3D%2B%24%2C%3B");
  811. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  812. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  813. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  814. "http://example.com/a%2Fb");
  815. // decode_uri_component still decodes the reserved character.
  816. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  817. }
  818. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  819. string original = "Piri Tommy Villiers - on & on";
  820. string encoded = httplib::encode_uri_component(original);
  821. string decoded = httplib::decode_uri_component(encoded);
  822. EXPECT_EQ(decoded, original);
  823. }
  824. TEST(TrimTests, TrimStringTests) {
  825. EXPECT_EQ("abc", detail::trim_copy("abc"));
  826. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  827. EXPECT_TRUE(detail::trim_copy("").empty());
  828. }
  829. TEST(AsciiTest, LocaleIndependentClassification) {
  830. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  831. // which consult the global C locale: std::isalnum(0xC5) can return true
  832. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  833. // helpers must classify every byte by the ASCII grammar alone.
  834. for (int i = 0; i < 256; i++) {
  835. auto c = static_cast<char>(i);
  836. auto is_digit = i >= '0' && i <= '9';
  837. auto is_upper = i >= 'A' && i <= 'Z';
  838. auto is_lower = i >= 'a' && i <= 'z';
  839. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  840. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  841. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  842. << "byte " << i;
  843. }
  844. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  845. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  846. // Non-ASCII bytes must be percent-encoded, never passed through as
  847. // alphanumeric.
  848. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  849. }
  850. TEST(FromCharsTest, Double) {
  851. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  852. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  853. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  854. auto parse = [](const std::string &s, double &v) {
  855. return detail::from_chars(s.data(), s.data() + s.size(), v);
  856. };
  857. double v = -1.0;
  858. // Representative quality values.
  859. EXPECT_EQ(parse("0", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 0.0);
  861. EXPECT_EQ(parse("1", v).ec, std::errc{});
  862. EXPECT_DOUBLE_EQ(v, 1.0);
  863. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.8);
  865. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 0.001);
  867. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 1.0);
  869. // A missing integer or fractional part is tolerated.
  870. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 0.5);
  872. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 5.0);
  874. // Values outside [0, 1] still parse; the caller range-checks them.
  875. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 123.456);
  877. // Stops at the first byte that is not part of the number and reports where.
  878. std::string trailing = "0.9, text/html";
  879. auto r = parse(trailing, v);
  880. EXPECT_EQ(r.ec, std::errc{});
  881. EXPECT_DOUBLE_EQ(v, 0.9);
  882. EXPECT_EQ(*r.ptr, ',');
  883. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  884. // outright, and an 'e'/'E' simply ends the number.
  885. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  886. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  887. std::string exp_input = "1.5e3";
  888. r = parse(exp_input, v);
  889. EXPECT_EQ(r.ec, std::errc{});
  890. EXPECT_DOUBLE_EQ(v, 1.5);
  891. EXPECT_EQ(*r.ptr, 'e');
  892. // Invalid inputs.
  893. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  898. // Pathological but well-formed inputs must stay bounded (no overflow, no
  899. // out-of-bounds table access) and stay within [0, 1] for the caller.
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  901. std::errc{});
  902. EXPECT_DOUBLE_EQ(v, 0.0);
  903. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  904. std::errc{});
  905. EXPECT_GE(v, 0.0);
  906. EXPECT_LE(v, 1.0);
  907. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  908. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  909. }
  910. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  911. // Simple case without quality values
  912. std::vector<std::string> result1;
  913. EXPECT_TRUE(detail::parse_accept_header(
  914. "text/html,application/json,text/plain", result1));
  915. EXPECT_EQ(result1.size(), 3U);
  916. EXPECT_EQ(result1[0], "text/html");
  917. EXPECT_EQ(result1[1], "application/json");
  918. EXPECT_EQ(result1[2], "text/plain");
  919. // With quality values
  920. std::vector<std::string> result2;
  921. EXPECT_TRUE(detail::parse_accept_header(
  922. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  923. EXPECT_EQ(result2.size(), 3U);
  924. EXPECT_EQ(result2[0], "application/json"); // highest q value
  925. EXPECT_EQ(result2[1], "text/html");
  926. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  927. }
  928. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  929. // Mixed with and without quality values
  930. std::vector<std::string> result;
  931. EXPECT_TRUE(detail::parse_accept_header(
  932. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  933. EXPECT_EQ(result.size(), 3U);
  934. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  935. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  936. EXPECT_EQ(result[2], "application/json"); // q=0.5
  937. }
  938. TEST(ParseAcceptHeaderTest, EdgeCases) {
  939. // Empty header
  940. std::vector<std::string> empty_result;
  941. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  942. EXPECT_TRUE(empty_result.empty());
  943. // Single type
  944. std::vector<std::string> single_result;
  945. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  946. EXPECT_EQ(single_result.size(), 1U);
  947. EXPECT_EQ(single_result[0], "application/json");
  948. // Wildcard types
  949. std::vector<std::string> wildcard_result;
  950. EXPECT_TRUE(detail::parse_accept_header(
  951. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  952. EXPECT_EQ(wildcard_result.size(), 3U);
  953. EXPECT_EQ(wildcard_result[0], "application/json");
  954. EXPECT_EQ(wildcard_result[1], "text/*");
  955. EXPECT_EQ(wildcard_result[2], "*/*");
  956. }
  957. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  958. // Common browser Accept header
  959. std::vector<std::string> browser_result;
  960. EXPECT_TRUE(
  961. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  962. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  963. browser_result));
  964. EXPECT_EQ(browser_result.size(), 6U);
  965. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  970. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  971. // API client header
  972. std::vector<std::string> api_result;
  973. EXPECT_TRUE(detail::parse_accept_header(
  974. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  975. api_result));
  976. EXPECT_EQ(api_result.size(), 3U);
  977. EXPECT_EQ(api_result[0], "application/json");
  978. EXPECT_EQ(api_result[1], "application/xml");
  979. EXPECT_EQ(api_result[2], "text/plain");
  980. }
  981. TEST(ParseAcceptHeaderTest, SpecialCases) {
  982. // Quality value with 3 decimal places
  983. std::vector<std::string> decimal_result;
  984. EXPECT_TRUE(detail::parse_accept_header(
  985. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  986. EXPECT_EQ(decimal_result.size(), 2U);
  987. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  988. EXPECT_EQ(decimal_result[1], "text/html");
  989. // Zero quality (should still be included but with lowest priority)
  990. std::vector<std::string> zero_q_result;
  991. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  992. zero_q_result));
  993. EXPECT_EQ(zero_q_result.size(), 2U);
  994. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  995. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  996. // No spaces around commas
  997. std::vector<std::string> no_space_result;
  998. EXPECT_TRUE(detail::parse_accept_header(
  999. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1000. no_space_result));
  1001. EXPECT_EQ(no_space_result.size(), 3U);
  1002. EXPECT_EQ(no_space_result[0], "text/html");
  1003. EXPECT_EQ(no_space_result[1], "application/json");
  1004. EXPECT_EQ(no_space_result[2], "text/plain");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1007. // Quality values always use '.' as the decimal separator, so parsing must
  1008. // not depend on the process locale. An embedding application may have
  1009. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1010. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1011. std::string saved = cur ? cur : "C";
  1012. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1013. "fr_FR.UTF-8"};
  1014. bool switched = false;
  1015. for (const auto loc : comma_locales) {
  1016. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1017. std::localeconv()->decimal_point[0] == ',') {
  1018. switched = true;
  1019. break;
  1020. }
  1021. }
  1022. if (!switched) {
  1023. std::setlocale(LC_NUMERIC, saved.c_str());
  1024. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1025. }
  1026. // The higher-weighted type appears later in the list, so a correct parse
  1027. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1028. // sensitive parse reads both weights as 0 and leaves the original order.
  1029. std::vector<std::string> result;
  1030. EXPECT_TRUE(detail::parse_accept_header(
  1031. "application/json;q=0.1,text/html;q=0.9", result));
  1032. ASSERT_EQ(result.size(), 2U);
  1033. EXPECT_EQ(result[0], "text/html");
  1034. EXPECT_EQ(result[1], "application/json");
  1035. std::setlocale(LC_NUMERIC, saved.c_str());
  1036. }
  1037. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1038. std::vector<std::string> result;
  1039. // Invalid quality value (> 1.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1042. // Invalid quality value (< 0.0)
  1043. EXPECT_FALSE(
  1044. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1045. // Invalid quality value (not a number)
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=invalid,application/json", result));
  1048. // A valid numeric prefix does not make the entire quality value valid.
  1049. EXPECT_FALSE(detail::parse_accept_header(
  1050. "text/html;q=0.5junk,application/json", result));
  1051. // Empty quality value
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("text/html;q=,application/json", result));
  1054. // Invalid media type format (no slash and not wildcard)
  1055. EXPECT_FALSE(
  1056. detail::parse_accept_header("invalidtype,application/json", result));
  1057. // Valid cases should still work
  1058. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*/*");
  1061. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "*");
  1064. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1065. EXPECT_EQ(result.size(), 1U);
  1066. EXPECT_EQ(result[0], "text/*");
  1067. }
  1068. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1069. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1070. // and must not be answered with 400 Bad Request.
  1071. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1072. struct {
  1073. const char *value;
  1074. std::vector<std::string> expected;
  1075. } cases[] = {
  1076. {",application/json", {"application/json"}},
  1077. {"text/html,", {"text/html"}},
  1078. {"text/html,,*/*", {"text/html", "*/*"}},
  1079. // An empty element may be spelled with whitespace in it
  1080. {"text/html, , application/json", {"text/html", "application/json"}},
  1081. // Nothing but empty elements is an empty list, which means the same
  1082. // thing as no Accept header at all
  1083. {",,,", {}},
  1084. // Quality values still apply across ignored empty elements
  1085. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1086. };
  1087. for (const auto &c : cases) {
  1088. std::vector<std::string> result;
  1089. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1090. << "value: " << c.value;
  1091. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1092. }
  1093. // An invalid entry is still rejected when empty elements surround it
  1094. std::vector<std::string> result;
  1095. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1096. }
  1097. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1098. // or ';' inside one does not end the list element or the parameter. Section
  1099. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1100. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1101. struct {
  1102. const char *value;
  1103. std::vector<std::string> expected;
  1104. } cases[] = {
  1105. {"text/html;profile=\"a,b\",application/json",
  1106. {"text/html", "application/json"}},
  1107. // A "q=" inside a quoted value is not the weight
  1108. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1109. {"text/html", "application/json"}},
  1110. // The weight after a quoted value still applies
  1111. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1112. {"application/json", "text/html"}},
  1113. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1114. {"application/json", "text/html"}},
  1115. {"text/html;profile=\"a\\\"b\",application/json",
  1116. {"text/html", "application/json"}},
  1117. // An escaped backslash does not escape the '"' after it
  1118. {"text/html;profile=\"a\\\\\",application/json",
  1119. {"text/html", "application/json"}},
  1120. };
  1121. for (const auto &c : cases) {
  1122. std::vector<std::string> result;
  1123. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1124. << "value: " << c.value;
  1125. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1126. }
  1127. }
  1128. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1129. Server svr;
  1130. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1131. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1132. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1133. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1134. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1135. res.set_content("ok", "text/plain");
  1136. });
  1137. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1138. EXPECT_TRUE(false);
  1139. res.set_content("bad request", "text/plain");
  1140. });
  1141. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1142. auto se = detail::scope_exit([&] {
  1143. svr.stop();
  1144. listen_thread.join();
  1145. ASSERT_FALSE(svr.is_running());
  1146. });
  1147. svr.wait_until_ready();
  1148. Client cli("localhost", PORT);
  1149. {
  1150. auto res = cli.Get(
  1151. "/accept_ok",
  1152. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1154. EXPECT_EQ(StatusCode::OK_200, res->status);
  1155. }
  1156. {
  1157. auto res = cli.Get("/accept_bad_request",
  1158. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1161. }
  1162. }
  1163. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1164. Server svr;
  1165. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1166. res.set_content("ok", "text/plain");
  1167. });
  1168. std::atomic<int> start_count{0};
  1169. std::atomic<bool> running_when_called{false};
  1170. svr.set_start_handler([&]() {
  1171. running_when_called = svr.is_running();
  1172. start_count++;
  1173. });
  1174. auto port = svr.bind_to_any_port(HOST);
  1175. std::thread t([&]() { svr.listen_after_bind(); });
  1176. auto se = detail::scope_exit([&] {
  1177. svr.stop();
  1178. t.join();
  1179. ASSERT_FALSE(svr.is_running());
  1180. });
  1181. svr.wait_until_ready();
  1182. // A successful request proves the accept loop is running, which the start
  1183. // handler precedes; so by now the handler must have run exactly once.
  1184. Client cli(HOST, port);
  1185. cli.set_connection_timeout(std::chrono::seconds(5));
  1186. auto res = cli.Get("/");
  1187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1188. EXPECT_EQ(StatusCode::OK_200, res->status);
  1189. EXPECT_EQ(1, start_count.load());
  1190. EXPECT_TRUE(running_when_called.load());
  1191. }
  1192. TEST(DivideTest, DivideStringTests) {
  1193. auto divide = [](const std::string &str, char d) {
  1194. std::string lhs;
  1195. std::string rhs;
  1196. detail::divide(str, d,
  1197. [&](const char *lhs_data, std::size_t lhs_size,
  1198. const char *rhs_data, std::size_t rhs_size) {
  1199. lhs.assign(lhs_data, lhs_size);
  1200. rhs.assign(rhs_data, rhs_size);
  1201. });
  1202. return std::make_pair(std::move(lhs), std::move(rhs));
  1203. };
  1204. {
  1205. const auto res = divide("", '=');
  1206. EXPECT_EQ(res.first, "");
  1207. EXPECT_EQ(res.second, "");
  1208. }
  1209. {
  1210. const auto res = divide("=", '=');
  1211. EXPECT_EQ(res.first, "");
  1212. EXPECT_EQ(res.second, "");
  1213. }
  1214. {
  1215. const auto res = divide(" ", '=');
  1216. EXPECT_EQ(res.first, " ");
  1217. EXPECT_EQ(res.second, "");
  1218. }
  1219. {
  1220. const auto res = divide("a", '=');
  1221. EXPECT_EQ(res.first, "a");
  1222. EXPECT_EQ(res.second, "");
  1223. }
  1224. {
  1225. const auto res = divide("a=", '=');
  1226. EXPECT_EQ(res.first, "a");
  1227. EXPECT_EQ(res.second, "");
  1228. }
  1229. {
  1230. const auto res = divide("=b", '=');
  1231. EXPECT_EQ(res.first, "");
  1232. EXPECT_EQ(res.second, "b");
  1233. }
  1234. {
  1235. const auto res = divide("a=b", '=');
  1236. EXPECT_EQ(res.first, "a");
  1237. EXPECT_EQ(res.second, "b");
  1238. }
  1239. {
  1240. const auto res = divide("a=b=", '=');
  1241. EXPECT_EQ(res.first, "a");
  1242. EXPECT_EQ(res.second, "b=");
  1243. }
  1244. {
  1245. const auto res = divide("a=b=c", '=');
  1246. EXPECT_EQ(res.first, "a");
  1247. EXPECT_EQ(res.second, "b=c");
  1248. }
  1249. }
  1250. TEST(SplitTest, ParseQueryString) {
  1251. string s = "key1=val1&key2=val2&key3=val3";
  1252. Params dic;
  1253. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1254. [&](const char *b, const char *e) {
  1255. string key, val;
  1256. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1257. if (key.empty()) {
  1258. key.assign(b2, e2);
  1259. } else {
  1260. val.assign(b2, e2);
  1261. }
  1262. });
  1263. dic.emplace(key, val);
  1264. });
  1265. EXPECT_EQ("val1", dic.find("key1")->second);
  1266. EXPECT_EQ("val2", dic.find("key2")->second);
  1267. EXPECT_EQ("val3", dic.find("key3")->second);
  1268. }
  1269. TEST(SplitTest, ParseInvalidQueryTests) {
  1270. {
  1271. string s = " ";
  1272. Params dict;
  1273. detail::parse_query_text(s, dict);
  1274. EXPECT_TRUE(dict.empty());
  1275. }
  1276. {
  1277. string s = " = =";
  1278. Params dict;
  1279. detail::parse_query_text(s, dict);
  1280. EXPECT_TRUE(dict.empty());
  1281. }
  1282. }
  1283. TEST(ParseQueryTest, ParseQueryString) {
  1284. {
  1285. std::string s = "key1=val1&key2=val2&key3=val3";
  1286. Params dic;
  1287. detail::parse_query_text(s, dic);
  1288. EXPECT_EQ("val1", dic.find("key1")->second);
  1289. EXPECT_EQ("val2", dic.find("key2")->second);
  1290. EXPECT_EQ("val3", dic.find("key3")->second);
  1291. }
  1292. {
  1293. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1294. Params dic;
  1295. detail::parse_query_text(s, dic);
  1296. EXPECT_EQ("", dic.find("key1")->second);
  1297. EXPECT_EQ("val1", dic.find("key2")->second);
  1298. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1299. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1300. }
  1301. }
  1302. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1303. Params dic;
  1304. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1305. dic.emplace("key1", "val1");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1307. dic.emplace("key2", "val2");
  1308. dic.emplace("key3", "val3");
  1309. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1310. }
  1311. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1312. Params params;
  1313. params.emplace("a", "1");
  1314. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1315. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1316. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1317. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1318. // Long enough to overflow the stack when matched with std::regex.
  1319. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1320. EXPECT_EQ("/p?" + long_query + "&a=1",
  1321. append_query_params("/p?" + long_query, params));
  1322. }
  1323. // Joins every entry of a Headers or Params into "key=value " so a whole
  1324. // traversal can be compared in one assertion. Both are instantiations of the
  1325. // same insertion-ordered container, so one helper serves both.
  1326. template <typename Map> static std::string entries_to_string(const Map &m) {
  1327. std::string s;
  1328. for (const auto &entry : m) {
  1329. s += entry.first + "=" + entry.second + " ";
  1330. }
  1331. return s;
  1332. }
  1333. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1334. // Params used to be a std::multimap, which sorted by name and handed the
  1335. // caller's query back alphabetised. A client signing its query string could
  1336. // not reproduce the order it asked for.
  1337. Params dic;
  1338. dic.emplace("zulu", "1");
  1339. dic.emplace("alpha", "2");
  1340. dic.emplace("mike", "3");
  1341. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1342. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1343. }
  1344. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1345. Params dic;
  1346. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1347. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1348. }
  1349. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1350. Request req;
  1351. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1352. req.params);
  1353. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1354. EXPECT_EQ("first", req.get_param_value("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1356. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1357. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1358. EXPECT_EQ("", req.get_param_value("tag", 3));
  1359. }
  1360. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1361. // Params shares its container with Headers, which matches field names
  1362. // case-insensitively. Parameter names must not pick that up.
  1363. Params dic;
  1364. dic.emplace("Key", "upper");
  1365. dic.emplace("key", "lower");
  1366. EXPECT_EQ(2U, dic.size());
  1367. EXPECT_EQ(1U, dic.count("Key"));
  1368. EXPECT_EQ(1U, dic.count("key"));
  1369. EXPECT_EQ("upper", dic.find("Key")->second);
  1370. EXPECT_EQ("lower", dic.find("key")->second);
  1371. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1372. }
  1373. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1374. Server svr;
  1375. std::string order;
  1376. svr.Get("/order", [&](const Request &req, Response &res) {
  1377. order = entries_to_string(req.params);
  1378. res.set_content("ok", "text/plain");
  1379. });
  1380. auto port = svr.bind_to_any_port(HOST);
  1381. thread t = thread([&] { svr.listen_after_bind(); });
  1382. auto se = detail::scope_exit([&] {
  1383. svr.stop();
  1384. t.join();
  1385. ASSERT_FALSE(svr.is_running());
  1386. });
  1387. svr.wait_until_ready();
  1388. Client cli(HOST, port);
  1389. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1390. ASSERT_TRUE(res);
  1391. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1392. }
  1393. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1394. Server svr;
  1395. std::string field_order, file_order;
  1396. svr.Post("/order", [&](const Request &req, Response &res) {
  1397. for (const auto &field : req.form.fields) {
  1398. field_order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. for (const auto &file : req.form.files) {
  1401. file_order += file.first + "=" + file.second.filename + " ";
  1402. }
  1403. res.set_content("ok", "text/plain");
  1404. });
  1405. auto port = svr.bind_to_any_port(HOST);
  1406. thread t = thread([&] { svr.listen_after_bind(); });
  1407. auto se = detail::scope_exit([&] {
  1408. svr.stop();
  1409. t.join();
  1410. ASSERT_FALSE(svr.is_running());
  1411. });
  1412. svr.wait_until_ready();
  1413. UploadFormDataItems items = {
  1414. {"zulu", "1", "", ""},
  1415. {"alpha", "2", "", ""},
  1416. {"mike", "3", "", ""},
  1417. {"zebra", "z", "z.txt", "text/plain"},
  1418. {"apple", "a", "a.txt", "text/plain"},
  1419. };
  1420. Client cli(HOST, port);
  1421. auto res = cli.Post("/order", items);
  1422. ASSERT_TRUE(res);
  1423. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1424. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1425. }
  1426. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1427. Server svr;
  1428. std::vector<std::string> values;
  1429. std::string first, second, out_of_range, order;
  1430. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1431. values = req.form.get_fields("tag");
  1432. first = req.form.get_field("tag", 0);
  1433. second = req.form.get_field("tag", 1);
  1434. out_of_range = req.form.get_field("tag", 2);
  1435. for (const auto &field : req.form.fields) {
  1436. order += field.first + "=" + field.second.content + " ";
  1437. }
  1438. res.set_content("ok", "text/plain");
  1439. });
  1440. auto port = svr.bind_to_any_port(HOST);
  1441. thread t = thread([&] { svr.listen_after_bind(); });
  1442. auto se = detail::scope_exit([&] {
  1443. svr.stop();
  1444. t.join();
  1445. ASSERT_FALSE(svr.is_running());
  1446. });
  1447. svr.wait_until_ready();
  1448. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1449. // not adjacent in the container.
  1450. UploadFormDataItems items = {
  1451. {"tag", "first", "", ""},
  1452. {"other", "x", "", ""},
  1453. {"tag", "second", "", ""},
  1454. };
  1455. Client cli(HOST, port);
  1456. auto res = cli.Post("/repeated", items);
  1457. ASSERT_TRUE(res);
  1458. ASSERT_EQ(2U, values.size());
  1459. EXPECT_EQ("first", values[0]);
  1460. EXPECT_EQ("second", values[1]);
  1461. EXPECT_EQ("first", first);
  1462. EXPECT_EQ("second", second);
  1463. // std::multimap already kept entries sharing a name in insertion order, so
  1464. // everything above passes without this change too. The whole traversal is
  1465. // what tells the two apart: sorting by name would hoist "other" to the front
  1466. // and the two "tag" parts would end up adjacent.
  1467. EXPECT_EQ("tag=first other=x tag=second ", order);
  1468. // Advancing past the last entry of a name used to run off the container;
  1469. // the container's saturating increment makes it return the default instead.
  1470. EXPECT_EQ("", out_of_range);
  1471. }
  1472. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1473. Server svr;
  1474. std::string file_names;
  1475. svr.Post("/upload", [&](const Request &req, Response &res) {
  1476. for (const auto &file : req.form.files) {
  1477. file_names += file.first + "|" + file.second.filename + " ";
  1478. }
  1479. res.set_content("ok", "text/plain");
  1480. });
  1481. auto port = svr.bind_to_any_port(HOST);
  1482. thread t = thread([&] { svr.listen_after_bind(); });
  1483. auto se = detail::scope_exit([&] {
  1484. svr.stop();
  1485. t.join();
  1486. ASSERT_FALSE(svr.is_running());
  1487. });
  1488. svr.wait_until_ready();
  1489. // A trailing backslash would otherwise escape the closing quote.
  1490. UploadFormDataItems items = {
  1491. {"dir\\", "x", "a.txt", "text/plain"},
  1492. {"b", "y", "a\\\\b.txt", "text/plain"},
  1493. };
  1494. Client cli(HOST, port);
  1495. auto res = cli.Post("/upload", items);
  1496. ASSERT_TRUE(res);
  1497. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1498. }
  1499. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1500. // Server::read_content() keeps a FormFields::iterator alive across the
  1501. // content callbacks that fill the part it points at. The container is
  1502. // vector-backed, so a later emplace can reallocate and invalidate an older
  1503. // iterator; 64 parts grow the vector through seven reallocations, which
  1504. // checks that every part's content still lands in its own entry.
  1505. const size_t part_count = 64;
  1506. // One formula for both the parts sent and the values expected back, so the
  1507. // two cannot drift apart.
  1508. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1509. auto content_of = [](size_t i) {
  1510. return std::string(64, static_cast<char>('a' + (i % 26)));
  1511. };
  1512. Server svr;
  1513. std::vector<std::pair<std::string, std::string>> received;
  1514. svr.Post("/many", [&](const Request &req, Response &res) {
  1515. for (const auto &field : req.form.fields) {
  1516. received.emplace_back(field.first, field.second.content);
  1517. }
  1518. res.set_content("ok", "text/plain");
  1519. });
  1520. auto port = svr.bind_to_any_port(HOST);
  1521. thread t = thread([&] { svr.listen_after_bind(); });
  1522. auto se = detail::scope_exit([&] {
  1523. svr.stop();
  1524. t.join();
  1525. ASSERT_FALSE(svr.is_running());
  1526. });
  1527. svr.wait_until_ready();
  1528. UploadFormDataItems items;
  1529. for (size_t i = 0; i < part_count; i++) {
  1530. items.push_back({name_of(i), content_of(i), "", ""});
  1531. }
  1532. Client cli(HOST, port);
  1533. auto res = cli.Post("/many", items);
  1534. ASSERT_TRUE(res);
  1535. ASSERT_EQ(part_count, received.size());
  1536. for (size_t i = 0; i < part_count; i++) {
  1537. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1538. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1539. }
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1542. string content_type = "multipart/form-data; boundary=something";
  1543. string boundary;
  1544. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1545. EXPECT_TRUE(ret);
  1546. EXPECT_EQ(boundary, "something");
  1547. }
  1548. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1549. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1550. string boundary;
  1551. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1552. EXPECT_TRUE(ret);
  1553. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1556. string content_type =
  1557. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1558. string boundary;
  1559. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1562. }
  1563. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1564. string content_type =
  1565. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1566. string boundary;
  1567. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1568. EXPECT_TRUE(ret);
  1569. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1570. }
  1571. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1572. const string boundary(70, 'a');
  1573. string content_type = "multipart/form-data; boundary=" + boundary;
  1574. string parsed;
  1575. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1576. EXPECT_TRUE(ret);
  1577. EXPECT_EQ(parsed, boundary);
  1578. }
  1579. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1580. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1581. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1582. string parsed;
  1583. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1584. EXPECT_FALSE(ret);
  1585. }
  1586. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1587. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1588. // is 72 characters on the wire and still valid.
  1589. const string boundary(70, 'a');
  1590. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1591. string parsed;
  1592. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1593. EXPECT_EQ(parsed, boundary);
  1594. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1595. parsed.clear();
  1596. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1597. }
  1598. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1599. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1600. // The parameter parser must not treat that '=' as the key/value separator.
  1601. string content_type =
  1602. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1603. "charset=UTF-8";
  1604. string parsed;
  1605. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1606. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1607. }
  1608. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1609. // A ';' inside the quoted-string is part of the value, not a parameter
  1610. // separator, so it must not truncate the boundary.
  1611. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1612. string parsed;
  1613. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1614. EXPECT_EQ(parsed, "a;b");
  1615. }
  1616. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1617. string parsed;
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1620. EXPECT_EQ("a\\b", parsed);
  1621. EXPECT_TRUE(detail::parse_multipart_boundary(
  1622. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1623. EXPECT_EQ("a\"b", parsed);
  1624. }
  1625. TEST(ParseDispositionParamsTest, QuotedValues) {
  1626. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1627. // ';' and '=' are ordinary characters inside one.
  1628. struct {
  1629. const char *value;
  1630. std::vector<std::pair<const char *, const char *>> expected;
  1631. } cases[] = {
  1632. {"name=\"file1\"; filename=\"a.txt\"",
  1633. {{"name", "file1"}, {"filename", "a.txt"}}},
  1634. // Whitespace around '=' and ';' is still trimmed
  1635. {"name=\"file2\" ;filename = \"a.html\"",
  1636. {{"name", "file2"}, {"filename", "a.html"}}},
  1637. // '=' inside the value used to leave only the text after the last one
  1638. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1639. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1640. {"name=\"x=y\"", {{"name", "x=y"}}},
  1641. // ';' inside the value used to truncate the pair and leave a bogus one
  1642. {"name=\"file3\"; filename=\"a;b.txt\"",
  1643. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1644. // An unquoted value keeps working, and so does filename*
  1645. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1646. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1647. // A parameter with no key is dropped rather than turned into one whose
  1648. // key is the value
  1649. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1650. // An escaped quote does not end the value
  1651. {"name=\"a\\\"; filename=evil.php\"",
  1652. {{"name", "a\"; filename=evil.php"}}},
  1653. // Other backslashes, as in a Windows path, are kept
  1654. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1655. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1656. };
  1657. for (const auto &c : cases) {
  1658. Params params;
  1659. detail::parse_disposition_params(c.value, params);
  1660. for (const auto &kv : c.expected) {
  1661. auto it = params.find(kv.first);
  1662. ASSERT_NE(it, params.end())
  1663. << "value: " << c.value << ", key: " << kv.first;
  1664. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1665. }
  1666. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1667. }
  1668. }
  1669. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1670. Server svr;
  1671. std::string filename;
  1672. std::string content;
  1673. svr.Post("/upload", [&](const Request &req, Response &) {
  1674. const auto &file = req.form.get_file("file");
  1675. filename = file.filename;
  1676. content = file.content;
  1677. });
  1678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1679. auto se = detail::scope_exit([&] {
  1680. svr.stop();
  1681. thread.join();
  1682. ASSERT_FALSE(svr.is_running());
  1683. });
  1684. svr.wait_until_ready();
  1685. std::string body = "--B\r\n"
  1686. "Content-Disposition: form-data; name=\"file\"; "
  1687. "filename=\"a.txt\"\r\n"
  1688. "Content-Type: text/plain\r\n"
  1689. "\r\n"
  1690. "hello\r\n"
  1691. "--B--\r\n";
  1692. Client cli(HOST, PORT);
  1693. auto res = cli.Post(
  1694. "/upload",
  1695. [&](size_t offset, DataSink &sink) {
  1696. if (offset < body.size()) {
  1697. sink.write(&body[offset], 1);
  1698. } else {
  1699. sink.done();
  1700. }
  1701. return true;
  1702. },
  1703. "multipart/form-data; boundary=B");
  1704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1705. EXPECT_EQ(StatusCode::OK_200, res->status);
  1706. EXPECT_EQ("a.txt", filename);
  1707. EXPECT_EQ("hello", content);
  1708. }
  1709. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1710. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1711. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1712. Server svr;
  1713. std::string field_value, file_name, file_filename;
  1714. bool has_field = false, has_file = false;
  1715. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1716. has_field = req.form.has_field("x=y");
  1717. field_value = req.form.get_field("x=y");
  1718. has_file = req.form.has_file("file1");
  1719. const auto &file = req.form.get_file("file1");
  1720. file_name = file.name;
  1721. file_filename = file.filename;
  1722. res.set_content("ok", "text/plain");
  1723. });
  1724. auto port = svr.bind_to_any_port(HOST);
  1725. thread t = thread([&] { svr.listen_after_bind(); });
  1726. auto se = detail::scope_exit([&] {
  1727. svr.stop();
  1728. t.join();
  1729. ASSERT_FALSE(svr.is_running());
  1730. });
  1731. svr.wait_until_ready();
  1732. UploadFormDataItems items = {
  1733. {"x=y", "field-value", "", ""},
  1734. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1735. };
  1736. Client cli(HOST, port);
  1737. auto res = cli.Post("/quoted", items);
  1738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1739. ASSERT_EQ(StatusCode::OK_200, res->status);
  1740. EXPECT_TRUE(has_field);
  1741. EXPECT_EQ("field-value", field_value);
  1742. EXPECT_TRUE(has_file);
  1743. EXPECT_EQ("file1", file_name);
  1744. EXPECT_EQ("a;b=report.pdf", file_filename);
  1745. }
  1746. TEST(GetHeaderValueTest, DefaultValue) {
  1747. Headers headers = {{"Dummy", "Dummy"}};
  1748. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1749. EXPECT_STREQ("text/plain", val);
  1750. }
  1751. TEST(GetHeaderValueTest, DefaultValueInt) {
  1752. Headers headers = {{"Dummy", "Dummy"}};
  1753. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1754. EXPECT_EQ(100ull, val);
  1755. }
  1756. TEST(GetHeaderValueTest, RegularValue) {
  1757. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1758. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1759. EXPECT_STREQ("text/html", val);
  1760. }
  1761. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1762. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1763. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1764. EXPECT_STREQ("text/html", val);
  1765. }
  1766. TEST(GetHeaderValueTest, SetContent) {
  1767. Response res;
  1768. res.set_content("html", "text/html");
  1769. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1770. res.set_content("text", "text/plain");
  1771. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1772. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1773. }
  1774. TEST(GetHeaderValueTest, RegularValueInt) {
  1775. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1776. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1777. EXPECT_EQ(100ull, val);
  1778. }
  1779. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1780. Headers headers = {{"Content-Length", "x"}};
  1781. auto is_invalid_value = false;
  1782. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1783. is_invalid_value);
  1784. EXPECT_EQ(0ull, val);
  1785. EXPECT_TRUE(is_invalid_value);
  1786. }
  1787. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1788. // An all-digit value that overflows size_t must be reported as invalid, not
  1789. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1790. // a large length to a small one on 32-bit builds, leaving the framing length
  1791. // wrong while is_invalid_value stayed false.
  1792. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1793. auto is_invalid_value = false;
  1794. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1795. is_invalid_value);
  1796. EXPECT_TRUE(is_invalid_value);
  1797. // A well-formed length is unaffected.
  1798. Headers ok = {{"Content-Length", "1234"}};
  1799. is_invalid_value = false;
  1800. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1801. is_invalid_value);
  1802. EXPECT_EQ(1234ull, val);
  1803. EXPECT_FALSE(is_invalid_value);
  1804. }
  1805. TEST(GetHeaderValueTest, Range) {
  1806. {
  1807. Headers headers = {make_range_header({{1, -1}})};
  1808. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1809. EXPECT_STREQ("bytes=1-", val);
  1810. }
  1811. {
  1812. Headers headers = {make_range_header({{-1, 1}})};
  1813. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1814. EXPECT_STREQ("bytes=-1", val);
  1815. }
  1816. {
  1817. Headers headers = {make_range_header({{1, 10}})};
  1818. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1819. EXPECT_STREQ("bytes=1-10", val);
  1820. }
  1821. {
  1822. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1823. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1824. EXPECT_STREQ("bytes=1-10, 100-", val);
  1825. }
  1826. {
  1827. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1828. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1829. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1830. }
  1831. {
  1832. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1833. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1834. EXPECT_STREQ("bytes=0-0, -1", val);
  1835. }
  1836. }
  1837. TEST(BearerTokenAuthTest, SchemeValidation) {
  1838. // A value shorter than "Bearer " must not throw from the fixed-length
  1839. // substr, and a non-Bearer scheme must not be reported as a token.
  1840. struct {
  1841. const char *value;
  1842. const char *expected;
  1843. } cases[] = {
  1844. {"x", ""},
  1845. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1846. {"Bearer abc123", "abc123"},
  1847. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1848. };
  1849. for (const auto &c : cases) {
  1850. Request req;
  1851. req.set_header("Authorization", c.value);
  1852. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1853. }
  1854. }
  1855. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1856. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1857. // to depend on the standard library (libstdc++ handed back duplicates in
  1858. // reverse insertion order, libc++ in insertion order).
  1859. Request req;
  1860. req.set_header("Accept-Encoding", "gzip");
  1861. req.set_header("Accept-Encoding", "deflate");
  1862. req.set_header("Accept-Encoding", "br");
  1863. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1864. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1866. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1867. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1868. }
  1869. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1870. Request req;
  1871. req.set_header("X-Test", "only");
  1872. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1873. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1875. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1876. }
  1877. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1878. Request req;
  1879. req.set_header("X-First", "1");
  1880. req.set_header("X-Test", "2");
  1881. req.params.emplace("first", "1");
  1882. req.params.emplace("test", "2");
  1883. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1884. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1885. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1886. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1887. // The second one is negative when read as a signed value
  1888. const auto max_id = (std::numeric_limits<size_t>::max)();
  1889. for (auto id : {max_id / 2, max_id}) {
  1890. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1891. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1892. EXPECT_EQ("", req.get_param_value("test", id));
  1893. EXPECT_EQ("", req.form.get_field("test", id));
  1894. EXPECT_EQ("", req.form.get_file("test", id).content);
  1895. }
  1896. }
  1897. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1898. Headers headers;
  1899. headers.emplace("Host", "example.com");
  1900. headers.emplace("Accept-Encoding", "gzip");
  1901. headers.emplace("User-Agent", "test");
  1902. headers.emplace("Accept-Encoding", "deflate");
  1903. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1904. "Accept-Encoding=deflate ",
  1905. entries_to_string(headers));
  1906. }
  1907. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1908. Headers headers = {{"Content-Type", "text/html"},
  1909. {"CONTENT-TYPE", "text/xml"}};
  1910. EXPECT_EQ(2U, headers.count("content-type"));
  1911. auto it = headers.find("content-type");
  1912. ASSERT_TRUE(it != headers.end());
  1913. EXPECT_EQ("text/html", it->second);
  1914. }
  1915. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1916. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1917. // drop only those fields and leave everything positioned between them.
  1918. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1919. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1920. auto rng = headers.equal_range("a");
  1921. headers.erase(rng.first, rng.second);
  1922. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1923. }
  1924. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1925. Headers headers = {
  1926. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1927. EXPECT_EQ(3U, headers.erase("A"));
  1928. EXPECT_EQ(0U, headers.count("A"));
  1929. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1930. }
  1931. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1932. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1933. headers.emplace_front("Host", "example.com");
  1934. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1935. entries_to_string(headers));
  1936. }
  1937. TEST(ParseHeaderValueTest, Range) {
  1938. {
  1939. Ranges ranges;
  1940. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1941. EXPECT_TRUE(ret);
  1942. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1943. }
  1944. {
  1945. Ranges ranges;
  1946. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1947. EXPECT_TRUE(ret);
  1948. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1949. }
  1950. {
  1951. Ranges ranges;
  1952. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1953. EXPECT_TRUE(ret);
  1954. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1955. }
  1956. {
  1957. Ranges ranges;
  1958. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1959. EXPECT_FALSE(ret);
  1960. }
  1961. {
  1962. Ranges ranges;
  1963. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1964. EXPECT_TRUE(ret);
  1965. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1966. }
  1967. {
  1968. Ranges ranges;
  1969. auto ret =
  1970. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1971. EXPECT_TRUE(ret);
  1972. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1973. }
  1974. {
  1975. Ranges ranges;
  1976. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1977. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1978. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1979. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1980. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1981. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1982. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1983. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1989. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1990. EXPECT_FALSE(
  1991. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1992. EXPECT_TRUE(ranges.empty());
  1993. }
  1994. {
  1995. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1996. // remainder of the representation, so it stays accepted.
  1997. Ranges ranges;
  1998. auto ret =
  1999. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2000. EXPECT_TRUE(ret);
  2001. ASSERT_EQ(1u, ranges.size());
  2002. EXPECT_EQ(0, ranges[0].first);
  2003. EXPECT_EQ(-1, ranges[0].second);
  2004. }
  2005. // RFC 9110 14.1: range unit names are case-insensitive.
  2006. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2007. Ranges ranges;
  2008. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2009. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2010. }
  2011. }
  2012. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2013. Request req;
  2014. req.set_header("Accept-Encoding", "gzip");
  2015. Response res;
  2016. res.set_header("Content-Type", "text/plain");
  2017. auto ret = detail::encoding_type(req, res);
  2018. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2019. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2020. #else
  2021. EXPECT_TRUE(ret == detail::EncodingType::None);
  2022. #endif
  2023. }
  2024. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2025. Request req;
  2026. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2027. Response res;
  2028. res.set_header("Content-Type", "text/plain");
  2029. auto ret = detail::encoding_type(req, res);
  2030. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2031. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2032. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2033. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2034. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2035. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2036. #else
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. #endif
  2039. }
  2040. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2041. Request req;
  2042. req.set_header("Accept-Encoding",
  2043. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2044. Response res;
  2045. res.set_header("Content-Type", "text/plain");
  2046. auto ret = detail::encoding_type(req, res);
  2047. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2048. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2049. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2050. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2051. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2052. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2053. #else
  2054. EXPECT_TRUE(ret == detail::EncodingType::None);
  2055. #endif
  2056. }
  2057. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2058. // All supported encodings rejected with q=0 should return None
  2059. Request req;
  2060. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2061. Response res;
  2062. res.set_header("Content-Type", "text/plain");
  2063. auto ret = detail::encoding_type(req, res);
  2064. EXPECT_TRUE(ret == detail::EncodingType::None);
  2065. }
  2066. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2067. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2068. Request req;
  2069. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2070. Response res;
  2071. res.set_header("Content-Type", "text/plain");
  2072. auto ret = detail::encoding_type(req, res);
  2073. EXPECT_TRUE(ret == detail::EncodingType::None);
  2074. }
  2075. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2076. Request req;
  2077. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2078. Response res;
  2079. res.set_header("Content-Type", "text/plain");
  2080. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2081. }
  2082. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2083. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2084. Request req;
  2085. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2086. Response res;
  2087. res.set_header("Content-Type", "text/plain");
  2088. auto ret = detail::encoding_type(req, res);
  2089. EXPECT_TRUE(ret == detail::EncodingType::None);
  2090. }
  2091. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2092. // RFC 7231: Accept-Encoding values are case-insensitive
  2093. Request req;
  2094. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2095. Response res;
  2096. res.set_header("Content-Type", "text/plain");
  2097. auto ret = detail::encoding_type(req, res);
  2098. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2100. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2101. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2102. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2103. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2104. #else
  2105. EXPECT_TRUE(ret == detail::EncodingType::None);
  2106. #endif
  2107. }
  2108. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2109. // q value should determine priority, not hardcoded order
  2110. Request req;
  2111. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2112. Response res;
  2113. res.set_header("Content-Type", "text/plain");
  2114. auto ret = detail::encoding_type(req, res);
  2115. // gzip has highest q=1.0, so it should be selected even though
  2116. // br and zstd are also supported
  2117. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2118. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2119. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2120. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2121. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2122. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2123. #else
  2124. EXPECT_TRUE(ret == detail::EncodingType::None);
  2125. #endif
  2126. }
  2127. TEST(BufferStreamTest, read) {
  2128. detail::BufferStream strm1;
  2129. Stream &strm = strm1;
  2130. EXPECT_EQ(5, strm.write("hello"));
  2131. char buf[512];
  2132. EXPECT_EQ(2, strm.read(buf, 2));
  2133. EXPECT_EQ('h', buf[0]);
  2134. EXPECT_EQ('e', buf[1]);
  2135. EXPECT_EQ(2, strm.read(buf, 2));
  2136. EXPECT_EQ('l', buf[0]);
  2137. EXPECT_EQ('l', buf[1]);
  2138. EXPECT_EQ(1, strm.read(buf, 1));
  2139. EXPECT_EQ('o', buf[0]);
  2140. EXPECT_EQ(0, strm.read(buf, 1));
  2141. }
  2142. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2143. auto host = "www.httpwatch.com";
  2144. auto ip = hosted_at(host);
  2145. EXPECT_EQ("23.96.13.243", ip);
  2146. std::vector<std::string> addrs;
  2147. hosted_at(host, addrs);
  2148. EXPECT_EQ(1u, addrs.size());
  2149. }
  2150. #if 0 // It depends on each test environment...
  2151. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2152. auto host = "www.youtube.com";
  2153. std::vector<std::string> addrs;
  2154. hosted_at(host, addrs);
  2155. EXPECT_EQ(20u, addrs.size());
  2156. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2157. EXPECT_TRUE(it != addrs.end());
  2158. }
  2159. #endif
  2160. class ChunkedEncodingTest : public ::testing::Test {
  2161. protected:
  2162. ChunkedEncodingTest()
  2163. : cli_(HOST, PORT)
  2164. #ifdef CPPHTTPLIB_SSL_ENABLED
  2165. ,
  2166. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2167. #endif
  2168. {
  2169. cli_.set_connection_timeout(2);
  2170. #ifdef CPPHTTPLIB_SSL_ENABLED
  2171. cli_.enable_server_certificate_verification(false);
  2172. #endif
  2173. }
  2174. virtual void SetUp() {
  2175. read_file("./image.jpg", image_data_);
  2176. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2177. res.set_content("Hello World!", "text/plain");
  2178. });
  2179. svr_.Get(
  2180. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2181. res.set_chunked_content_provider(
  2182. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2183. size_t remaining = image_data_.size() - offset;
  2184. if (remaining == 0) {
  2185. sink.done();
  2186. } else {
  2187. constexpr size_t CHUNK_SIZE = 1024;
  2188. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2189. sink.write(&image_data_[offset], send_size);
  2190. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2191. }
  2192. return true;
  2193. });
  2194. });
  2195. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2196. svr_.wait_until_ready();
  2197. }
  2198. virtual void TearDown() {
  2199. svr_.stop();
  2200. if (!request_threads_.empty()) {
  2201. std::this_thread::sleep_for(std::chrono::seconds(1));
  2202. for (auto &t : request_threads_) {
  2203. t.join();
  2204. }
  2205. }
  2206. t_.join();
  2207. }
  2208. #ifdef CPPHTTPLIB_SSL_ENABLED
  2209. SSLClient cli_;
  2210. SSLServer svr_;
  2211. #else
  2212. Client cli_;
  2213. Server svr_;
  2214. #endif
  2215. thread t_;
  2216. std::vector<thread> request_threads_;
  2217. std::string image_data_;
  2218. };
  2219. TEST_F(ChunkedEncodingTest, NormalGet) {
  2220. auto res = cli_.Get("/chunked");
  2221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2222. std::string out;
  2223. read_file("./image.jpg", out);
  2224. EXPECT_EQ(StatusCode::OK_200, res->status);
  2225. EXPECT_EQ(out, res->body);
  2226. }
  2227. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2228. std::string body;
  2229. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2230. body.append(data, data_length);
  2231. return true;
  2232. });
  2233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2234. std::string out;
  2235. read_file("./image.jpg", out);
  2236. EXPECT_EQ(StatusCode::OK_200, res->status);
  2237. EXPECT_EQ(out, body);
  2238. }
  2239. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2240. std::string body;
  2241. auto res = cli_.Get(
  2242. "/chunked",
  2243. [&](const Response &response) {
  2244. EXPECT_EQ(StatusCode::OK_200, response.status);
  2245. return true;
  2246. },
  2247. [&](const char *data, size_t data_length) {
  2248. body.append(data, data_length);
  2249. return true;
  2250. });
  2251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2252. std::string out;
  2253. read_file("./image.jpg", out);
  2254. EXPECT_EQ(StatusCode::OK_200, res->status);
  2255. EXPECT_EQ(out, body);
  2256. }
  2257. TEST(RangeTest, FromHTTPBin_Online) {
  2258. auto host = "httpbingo.org";
  2259. auto path = std::string{"/range/32"};
  2260. #ifdef CPPHTTPLIB_SSL_ENABLED
  2261. auto port = 443;
  2262. SSLClient cli(host, port);
  2263. #else
  2264. auto port = 80;
  2265. Client cli(host, port);
  2266. #endif
  2267. cli.set_connection_timeout(5);
  2268. {
  2269. auto res = cli.Get(path);
  2270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2271. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2272. EXPECT_EQ(StatusCode::OK_200, res->status);
  2273. }
  2274. {
  2275. Headers headers = {make_range_header({{1, -1}})};
  2276. auto res = cli.Get(path, headers);
  2277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2278. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2279. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2280. }
  2281. {
  2282. Headers headers = {make_range_header({{1, 10}})};
  2283. auto res = cli.Get(path, headers);
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ("bcdefghijk", res->body);
  2286. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2287. }
  2288. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2289. // entire resource, while the original httpbin returned 200. Both are
  2290. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2291. {
  2292. Headers headers = {make_range_header({{0, 31}})};
  2293. auto res = cli.Get(path, headers);
  2294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2295. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2296. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2297. res->status == StatusCode::PartialContent_206);
  2298. }
  2299. {
  2300. Headers headers = {make_range_header({{0, -1}})};
  2301. auto res = cli.Get(path, headers);
  2302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2303. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2304. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2305. res->status == StatusCode::PartialContent_206);
  2306. }
  2307. // go-httpbin returns 206 with clamped range for over-range requests,
  2308. // while the original httpbin returned 416. Both behaviors are observed
  2309. // in real servers, so we only verify the request succeeds.
  2310. {
  2311. Headers headers = {make_range_header({{0, 32}})};
  2312. auto res = cli.Get(path, headers);
  2313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2314. }
  2315. }
  2316. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2317. auto host = "unresolvableaddress.local";
  2318. auto path = std::string{"/"};
  2319. #ifdef CPPHTTPLIB_SSL_ENABLED
  2320. auto port = 443;
  2321. SSLClient cli(host, port);
  2322. #else
  2323. auto port = 80;
  2324. Client cli(host, port);
  2325. #endif
  2326. cli.set_connection_timeout(1);
  2327. {
  2328. auto res = cli.Get(path);
  2329. ASSERT_FALSE(res);
  2330. }
  2331. std::this_thread::sleep_for(std::chrono::seconds(8));
  2332. }
  2333. #if defined(__linux__) && defined(__GLIBC__) && \
  2334. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2335. // Forward declaration: in split builds split.py strips `inline` and moves the
  2336. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2337. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2338. // against the symbol in both header-only and split builds.
  2339. namespace httplib {
  2340. namespace detail {
  2341. int getaddrinfo_with_timeout(const char *node, const char *service,
  2342. const struct addrinfo *hints,
  2343. struct addrinfo **res, time_t timeout_sec);
  2344. } // namespace detail
  2345. } // namespace httplib
  2346. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2347. //
  2348. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2349. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2350. // gai_suspend() call hits the connection timeout the function calls
  2351. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2352. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2353. // still alive and still references the now-destroyed stack frame.
  2354. //
  2355. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2356. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2357. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2358. // and runs them in a container.
  2359. namespace {
  2360. bool should_run_issue_2431_tests() {
  2361. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2362. return v && *v && std::string(v) != "0";
  2363. }
  2364. std::string unique_unresolvable_host(int n) {
  2365. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2366. // glibc still asks the configured nameserver — which is exactly the path
  2367. // we want to exercise. A unique label per call avoids the resolver cache.
  2368. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2369. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2370. std::to_string(n) + ".invalid";
  2371. }
  2372. } // namespace
  2373. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2374. if (!should_run_issue_2431_tests()) {
  2375. GTEST_SKIP()
  2376. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2377. }
  2378. for (int i = 0; i < 8; ++i) {
  2379. struct addrinfo hints;
  2380. memset(&hints, 0, sizeof(hints));
  2381. hints.ai_family = AF_UNSPEC;
  2382. hints.ai_socktype = SOCK_STREAM;
  2383. auto host = unique_unresolvable_host(i);
  2384. struct addrinfo *result = nullptr;
  2385. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2386. &result, /*timeout_sec=*/1);
  2387. if (rc == 0 && result) { freeaddrinfo(result); }
  2388. }
  2389. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2390. // stack region they still believe holds their gaicb.
  2391. std::this_thread::sleep_for(std::chrono::seconds(3));
  2392. }
  2393. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2394. if (!should_run_issue_2431_tests()) {
  2395. GTEST_SKIP()
  2396. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2397. }
  2398. std::atomic<bool> stop{false};
  2399. std::vector<std::thread> threads;
  2400. for (int t = 0; t < 8; ++t) {
  2401. threads.emplace_back([t, &stop] {
  2402. int i = 0;
  2403. while (!stop.load(std::memory_order_relaxed)) {
  2404. struct addrinfo hints;
  2405. memset(&hints, 0, sizeof(hints));
  2406. hints.ai_family = AF_UNSPEC;
  2407. hints.ai_socktype = SOCK_STREAM;
  2408. auto host = unique_unresolvable_host(t * 100000 + i++);
  2409. struct addrinfo *result = nullptr;
  2410. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2411. &result, /*timeout_sec=*/1);
  2412. if (rc == 0 && result) { freeaddrinfo(result); }
  2413. }
  2414. });
  2415. }
  2416. std::this_thread::sleep_for(std::chrono::seconds(8));
  2417. stop.store(true, std::memory_order_relaxed);
  2418. for (auto &th : threads) {
  2419. th.join();
  2420. }
  2421. std::this_thread::sleep_for(std::chrono::seconds(3));
  2422. }
  2423. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2424. if (!should_run_issue_2431_tests()) {
  2425. GTEST_SKIP()
  2426. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2427. }
  2428. std::atomic<bool> stop{false};
  2429. std::vector<std::thread> threads;
  2430. for (int t = 0; t < 8; ++t) {
  2431. threads.emplace_back([t, &stop] {
  2432. int i = 0;
  2433. while (!stop.load(std::memory_order_relaxed)) {
  2434. auto host = unique_unresolvable_host(t * 100000 + i++);
  2435. Client cli(host, 80);
  2436. cli.set_connection_timeout(1, 0);
  2437. cli.set_read_timeout(1, 0);
  2438. cli.set_write_timeout(1, 0);
  2439. (void)cli.Get("/");
  2440. }
  2441. });
  2442. }
  2443. std::this_thread::sleep_for(std::chrono::seconds(8));
  2444. stop.store(true, std::memory_order_relaxed);
  2445. for (auto &th : threads) {
  2446. th.join();
  2447. }
  2448. std::this_thread::sleep_for(std::chrono::seconds(3));
  2449. }
  2450. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2451. TEST(ConnectionErrorTest, InvalidHost) {
  2452. auto host = "-abcde.com";
  2453. #ifdef CPPHTTPLIB_SSL_ENABLED
  2454. auto port = 443;
  2455. SSLClient cli(host, port);
  2456. #else
  2457. auto port = 80;
  2458. Client cli(host, port);
  2459. #endif
  2460. cli.set_connection_timeout(std::chrono::seconds(2));
  2461. auto res = cli.Get("/");
  2462. ASSERT_TRUE(!res);
  2463. EXPECT_EQ(Error::Connection, res.error());
  2464. }
  2465. TEST(ConnectionErrorTest, InvalidHost2) {
  2466. auto host = "httpcan.org/";
  2467. #ifdef CPPHTTPLIB_SSL_ENABLED
  2468. SSLClient cli(host);
  2469. #else
  2470. Client cli(host);
  2471. #endif
  2472. cli.set_connection_timeout(std::chrono::seconds(2));
  2473. auto res = cli.Get("/");
  2474. ASSERT_TRUE(!res);
  2475. EXPECT_EQ(Error::Connection, res.error());
  2476. }
  2477. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2478. auto host = "httpcan.org/";
  2479. #ifdef CPPHTTPLIB_SSL_ENABLED
  2480. SSLClient cli(host);
  2481. #else
  2482. Client cli(host);
  2483. #endif
  2484. cli.set_connection_timeout(std::chrono::seconds(2));
  2485. auto res = cli.Get("/");
  2486. ASSERT_TRUE(!res);
  2487. stringstream s;
  2488. s << "error code: " << res.error();
  2489. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2490. }
  2491. TEST(ConnectionErrorTest, InvalidPort) {
  2492. auto host = "localhost";
  2493. auto port = 44380;
  2494. #ifdef CPPHTTPLIB_SSL_ENABLED
  2495. SSLClient cli(host, port);
  2496. #else
  2497. Client cli(host, port);
  2498. #endif
  2499. cli.set_connection_timeout(std::chrono::seconds(2));
  2500. auto res = cli.Get("/");
  2501. ASSERT_TRUE(!res);
  2502. EXPECT_TRUE(Error::Connection == res.error() ||
  2503. Error::ConnectionTimeout == res.error());
  2504. }
  2505. TEST(ConnectionErrorTest, Timeout_Online) {
  2506. auto host = "google.com";
  2507. #ifdef CPPHTTPLIB_SSL_ENABLED
  2508. auto port = 44380;
  2509. SSLClient cli(host, port);
  2510. #else
  2511. auto port = 8080;
  2512. Client cli(host, port);
  2513. #endif
  2514. cli.set_connection_timeout(std::chrono::seconds(2));
  2515. // only probe one address type so that the error reason
  2516. // correlates to the timed-out IPv4, not the unsupported
  2517. // IPv6 connection attempt
  2518. cli.set_address_family(AF_INET);
  2519. auto res = cli.Get("/");
  2520. ASSERT_TRUE(!res);
  2521. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2522. }
  2523. TEST(CancelTest, NoCancel_Online) {
  2524. auto host = "httpbingo.org";
  2525. auto path = std::string{"/range/32"};
  2526. #ifdef CPPHTTPLIB_SSL_ENABLED
  2527. auto port = 443;
  2528. SSLClient cli(host, port);
  2529. #else
  2530. auto port = 80;
  2531. Client cli(host, port);
  2532. #endif
  2533. cli.set_connection_timeout(std::chrono::seconds(5));
  2534. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2536. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. }
  2539. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2540. // Use /bytes with a large payload so that the DownloadProgress callback
  2541. // (which only fires for Content-Length responses) is invoked before the
  2542. // entire body is received, giving cancellation a chance to fire.
  2543. auto host = "httpbingo.org";
  2544. auto path = std::string{"/bytes/524288"};
  2545. #ifdef CPPHTTPLIB_SSL_ENABLED
  2546. auto port = 443;
  2547. SSLClient cli(host, port);
  2548. #else
  2549. auto port = 80;
  2550. Client cli(host, port);
  2551. #endif
  2552. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2553. cli.set_connection_timeout(std::chrono::seconds(5));
  2554. ASSERT_TRUE(!res);
  2555. EXPECT_EQ(Error::Canceled, res.error());
  2556. }
  2557. TEST(CancelTest, WithCancelLargePayload_Online) {
  2558. auto host = "httpbingo.org";
  2559. auto path = std::string{"/bytes/524288"};
  2560. #ifdef CPPHTTPLIB_SSL_ENABLED
  2561. auto port = 443;
  2562. SSLClient cli(host, port);
  2563. #else
  2564. auto port = 80;
  2565. Client cli(host, port);
  2566. #endif
  2567. cli.set_connection_timeout(std::chrono::seconds(5));
  2568. uint32_t count = 0;
  2569. auto res =
  2570. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2571. ASSERT_TRUE(!res);
  2572. EXPECT_EQ(Error::Canceled, res.error());
  2573. }
  2574. TEST(CancelTest, NoCancelPost) {
  2575. Server svr;
  2576. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2577. res.set_content("Hello World!", "text/plain");
  2578. });
  2579. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2580. auto se = detail::scope_exit([&] {
  2581. svr.stop();
  2582. thread.join();
  2583. ASSERT_FALSE(svr.is_running());
  2584. });
  2585. svr.wait_until_ready();
  2586. Client cli(HOST, PORT);
  2587. cli.set_connection_timeout(std::chrono::seconds(5));
  2588. auto res =
  2589. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2590. "application/json", [](uint64_t, uint64_t) { return true; });
  2591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2592. EXPECT_EQ("Hello World!", res->body);
  2593. EXPECT_EQ(StatusCode::OK_200, res->status);
  2594. }
  2595. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2596. Server svr;
  2597. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2598. res.set_content("Hello World!", "text/plain");
  2599. });
  2600. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2601. auto se = detail::scope_exit([&] {
  2602. svr.stop();
  2603. thread.join();
  2604. ASSERT_FALSE(svr.is_running());
  2605. });
  2606. svr.wait_until_ready();
  2607. Client cli(HOST, PORT);
  2608. cli.set_connection_timeout(std::chrono::seconds(5));
  2609. auto res =
  2610. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2611. "application/json", [](uint64_t, uint64_t) { return false; });
  2612. ASSERT_TRUE(!res);
  2613. EXPECT_EQ(Error::Canceled, res.error());
  2614. }
  2615. TEST(CancelTest, WithCancelLargePayloadPost) {
  2616. Server svr;
  2617. svr.set_payload_max_length(200 * 1024 * 1024);
  2618. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2619. res.set_content(LARGE_DATA, "text/plain");
  2620. });
  2621. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2622. auto se = detail::scope_exit([&] {
  2623. svr.stop();
  2624. thread.join();
  2625. ASSERT_FALSE(svr.is_running());
  2626. });
  2627. svr.wait_until_ready();
  2628. Client cli(HOST, PORT);
  2629. cli.set_payload_max_length(200 * 1024 * 1024);
  2630. cli.set_connection_timeout(std::chrono::seconds(5));
  2631. auto res =
  2632. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2633. "application/json", [](uint64_t, uint64_t) { return false; });
  2634. ASSERT_TRUE(!res);
  2635. EXPECT_EQ(Error::Canceled, res.error());
  2636. }
  2637. TEST(CancelTest, NoCancelPut) {
  2638. Server svr;
  2639. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2640. res.set_content("Hello World!", "text/plain");
  2641. });
  2642. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2643. auto se = detail::scope_exit([&] {
  2644. svr.stop();
  2645. thread.join();
  2646. ASSERT_FALSE(svr.is_running());
  2647. });
  2648. svr.wait_until_ready();
  2649. Client cli(HOST, PORT);
  2650. cli.set_connection_timeout(std::chrono::seconds(5));
  2651. auto res =
  2652. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2653. "application/json", [](uint64_t, uint64_t) { return true; });
  2654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2655. EXPECT_EQ("Hello World!", res->body);
  2656. EXPECT_EQ(StatusCode::OK_200, res->status);
  2657. }
  2658. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2659. Server svr;
  2660. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2661. res.set_content("Hello World!", "text/plain");
  2662. });
  2663. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2664. auto se = detail::scope_exit([&] {
  2665. svr.stop();
  2666. thread.join();
  2667. ASSERT_FALSE(svr.is_running());
  2668. });
  2669. svr.wait_until_ready();
  2670. Client cli(HOST, PORT);
  2671. cli.set_connection_timeout(std::chrono::seconds(5));
  2672. auto res =
  2673. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2674. "application/json", [](uint64_t, uint64_t) { return false; });
  2675. ASSERT_TRUE(!res);
  2676. EXPECT_EQ(Error::Canceled, res.error());
  2677. }
  2678. TEST(CancelTest, WithCancelLargePayloadPut) {
  2679. Server svr;
  2680. svr.set_payload_max_length(200 * 1024 * 1024);
  2681. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2682. res.set_content(LARGE_DATA, "text/plain");
  2683. });
  2684. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2685. auto se = detail::scope_exit([&] {
  2686. svr.stop();
  2687. thread.join();
  2688. ASSERT_FALSE(svr.is_running());
  2689. });
  2690. svr.wait_until_ready();
  2691. Client cli(HOST, PORT);
  2692. cli.set_payload_max_length(200 * 1024 * 1024);
  2693. cli.set_connection_timeout(std::chrono::seconds(5));
  2694. auto res =
  2695. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2696. "application/json", [](uint64_t, uint64_t) { return false; });
  2697. ASSERT_TRUE(!res);
  2698. EXPECT_EQ(Error::Canceled, res.error());
  2699. }
  2700. TEST(CancelTest, NoCancelPatch) {
  2701. Server svr;
  2702. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2703. res.set_content("Hello World!", "text/plain");
  2704. });
  2705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2706. auto se = detail::scope_exit([&] {
  2707. svr.stop();
  2708. thread.join();
  2709. ASSERT_FALSE(svr.is_running());
  2710. });
  2711. svr.wait_until_ready();
  2712. Client cli(HOST, PORT);
  2713. cli.set_connection_timeout(std::chrono::seconds(5));
  2714. auto res =
  2715. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2716. "application/json", [](uint64_t, uint64_t) { return true; });
  2717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2718. EXPECT_EQ("Hello World!", res->body);
  2719. EXPECT_EQ(StatusCode::OK_200, res->status);
  2720. }
  2721. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2722. Server svr;
  2723. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2724. res.set_content("Hello World!", "text/plain");
  2725. });
  2726. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2727. auto se = detail::scope_exit([&] {
  2728. svr.stop();
  2729. thread.join();
  2730. ASSERT_FALSE(svr.is_running());
  2731. });
  2732. svr.wait_until_ready();
  2733. Client cli(HOST, PORT);
  2734. cli.set_connection_timeout(std::chrono::seconds(5));
  2735. auto res =
  2736. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2737. "application/json", [](uint64_t, uint64_t) { return false; });
  2738. ASSERT_TRUE(!res);
  2739. EXPECT_EQ(Error::Canceled, res.error());
  2740. }
  2741. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2742. Server svr;
  2743. svr.set_payload_max_length(200 * 1024 * 1024);
  2744. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2745. res.set_content(LARGE_DATA, "text/plain");
  2746. });
  2747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2748. auto se = detail::scope_exit([&] {
  2749. svr.stop();
  2750. thread.join();
  2751. ASSERT_FALSE(svr.is_running());
  2752. });
  2753. svr.wait_until_ready();
  2754. Client cli(HOST, PORT);
  2755. cli.set_payload_max_length(200 * 1024 * 1024);
  2756. cli.set_connection_timeout(std::chrono::seconds(5));
  2757. auto res =
  2758. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2759. "application/json", [](uint64_t, uint64_t) { return false; });
  2760. ASSERT_TRUE(!res);
  2761. EXPECT_EQ(Error::Canceled, res.error());
  2762. }
  2763. TEST(CancelTest, NoCancelDelete) {
  2764. Server svr;
  2765. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2766. res.set_content("Hello World!", "text/plain");
  2767. });
  2768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2769. auto se = detail::scope_exit([&] {
  2770. svr.stop();
  2771. thread.join();
  2772. ASSERT_FALSE(svr.is_running());
  2773. });
  2774. svr.wait_until_ready();
  2775. Client cli(HOST, PORT);
  2776. cli.set_connection_timeout(std::chrono::seconds(5));
  2777. auto res =
  2778. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2779. "application/json", [](uint64_t, uint64_t) { return true; });
  2780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2781. EXPECT_EQ("Hello World!", res->body);
  2782. EXPECT_EQ(StatusCode::OK_200, res->status);
  2783. }
  2784. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2785. Server svr;
  2786. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2787. res.set_content("Hello World!", "text/plain");
  2788. });
  2789. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2790. auto se = detail::scope_exit([&] {
  2791. svr.stop();
  2792. thread.join();
  2793. ASSERT_FALSE(svr.is_running());
  2794. });
  2795. svr.wait_until_ready();
  2796. Client cli(HOST, PORT);
  2797. cli.set_connection_timeout(std::chrono::seconds(5));
  2798. auto res =
  2799. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2800. "application/json", [](uint64_t, uint64_t) { return false; });
  2801. ASSERT_TRUE(!res);
  2802. EXPECT_EQ(Error::Canceled, res.error());
  2803. }
  2804. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2805. Server svr;
  2806. svr.set_payload_max_length(200 * 1024 * 1024);
  2807. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2808. res.set_content(LARGE_DATA, "text/plain");
  2809. });
  2810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2811. auto se = detail::scope_exit([&] {
  2812. svr.stop();
  2813. thread.join();
  2814. ASSERT_FALSE(svr.is_running());
  2815. });
  2816. svr.wait_until_ready();
  2817. Client cli(HOST, PORT);
  2818. cli.set_payload_max_length(200 * 1024 * 1024);
  2819. cli.set_connection_timeout(std::chrono::seconds(5));
  2820. auto res =
  2821. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2822. "application/json", [](uint64_t, uint64_t) { return false; });
  2823. ASSERT_TRUE(!res);
  2824. EXPECT_EQ(Error::Canceled, res.error());
  2825. }
  2826. static std::string remove_whitespace(const std::string &input) {
  2827. std::string output;
  2828. output.reserve(input.size());
  2829. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2830. [](unsigned char c) { return !std::isspace(c); });
  2831. return output;
  2832. }
  2833. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2834. auto host = "httpbingo.org";
  2835. auto path = std::string{"/basic-auth/hello/world"};
  2836. #ifdef CPPHTTPLIB_SSL_ENABLED
  2837. auto port = 443;
  2838. SSLClient cli(host, port);
  2839. #else
  2840. auto port = 80;
  2841. Client cli(host, port);
  2842. #endif
  2843. {
  2844. auto res = cli.Get(path);
  2845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2846. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2847. }
  2848. {
  2849. auto res = cli.Get(
  2850. path, Headers{make_basic_authentication_header("hello", "world")});
  2851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2852. auto body = remove_whitespace(res->body);
  2853. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2854. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2855. EXPECT_EQ(StatusCode::OK_200, res->status);
  2856. }
  2857. {
  2858. cli.set_basic_auth("hello", "world");
  2859. auto res = cli.Get(path);
  2860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2861. auto body = remove_whitespace(res->body);
  2862. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2863. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2864. EXPECT_EQ(StatusCode::OK_200, res->status);
  2865. }
  2866. {
  2867. cli.set_basic_auth("hello", "bad");
  2868. auto res = cli.Get(path);
  2869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2870. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2871. }
  2872. {
  2873. cli.set_basic_auth("bad", "world");
  2874. auto res = cli.Get(path);
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2877. }
  2878. }
  2879. #ifdef CPPHTTPLIB_SSL_ENABLED
  2880. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2881. auto host = "httpbingo.org";
  2882. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2883. auto paths = std::vector<std::string>{
  2884. "/digest-auth/auth/hello/world/MD5",
  2885. "/digest-auth/auth/hello/world/SHA-256",
  2886. };
  2887. auto port = 443;
  2888. SSLClient cli(host, port);
  2889. {
  2890. auto res = cli.Get(unauth_path);
  2891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2892. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2893. }
  2894. {
  2895. cli.set_digest_auth("hello", "world");
  2896. for (const auto &path : paths) {
  2897. auto res = cli.Get(path.c_str());
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. auto body = remove_whitespace(res->body);
  2900. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2901. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2902. EXPECT_EQ(StatusCode::OK_200, res->status);
  2903. }
  2904. cli.set_digest_auth("hello", "bad");
  2905. for (const auto &path : paths) {
  2906. auto res = cli.Get(path.c_str());
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2909. }
  2910. }
  2911. }
  2912. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2913. // comma-separated list of challenges, and each challenge may itself carry a
  2914. // comma-separated auth-param list, so a server can legally offer Basic
  2915. // before Digest, either as two field lines or packed into one. Runs one 401
  2916. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2917. // value() joins them in receipt order) and checks that the retry carries a
  2918. // well-formed Digest Authorization header naming expected_realm.
  2919. static void
  2920. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2921. const std::string &expected_realm) {
  2922. std::atomic<int> hits{0};
  2923. Server svr;
  2924. svr.Get("/x", [&](const Request &req, Response &res) {
  2925. if (++hits == 1) {
  2926. res.status = StatusCode::Unauthorized_401;
  2927. for (const auto &challenge : challenges) {
  2928. res.set_header("WWW-Authenticate", challenge);
  2929. }
  2930. } else {
  2931. auto authorization = req.get_header_value("Authorization");
  2932. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2933. EXPECT_NE(std::string::npos,
  2934. authorization.find("realm=\"" + expected_realm + "\""));
  2935. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2936. res.set_content("ok", "text/plain");
  2937. }
  2938. });
  2939. auto port = svr.bind_to_any_port(HOST);
  2940. std::thread t([&]() { svr.listen_after_bind(); });
  2941. auto se = detail::scope_exit([&] {
  2942. svr.stop();
  2943. t.join();
  2944. });
  2945. svr.wait_until_ready();
  2946. Client cli(HOST, port);
  2947. cli.set_digest_auth("hello", "world");
  2948. auto res = cli.Get("/x");
  2949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2950. EXPECT_EQ(2, hits.load());
  2951. }
  2952. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2953. static const char *kDigestChallenge =
  2954. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2955. "algorithm=MD5";
  2956. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2957. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2958. "testrealm");
  2959. }
  2960. // Same challenge list with the schemes in the opposite order, to make sure
  2961. // the fix above didn't just special-case "Basic first".
  2962. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2963. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2964. "testrealm");
  2965. }
  2966. // A comma inside a quoted auth-param value must not be mistaken for the
  2967. // separator between two challenges (or two auth-params).
  2968. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2969. run_digest_challenge_list_test(
  2970. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2971. "algorithm=MD5"},
  2972. "test,realm");
  2973. }
  2974. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2975. // the params and leaves out the fragment.
  2976. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2977. Server svr;
  2978. std::string uri, target;
  2979. svr.Get("/a b", [&](const Request &req, Response &res) {
  2980. auto auth = req.get_header_value("Authorization");
  2981. if (auth.empty()) {
  2982. res.status = StatusCode::Unauthorized_401;
  2983. res.set_header("WWW-Authenticate",
  2984. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2985. return;
  2986. }
  2987. auto b = auth.find("uri=\"") + 5;
  2988. uri = auth.substr(b, auth.find('"', b) - b);
  2989. target = req.target;
  2990. });
  2991. auto port = svr.bind_to_any_port(HOST);
  2992. std::thread t([&]() { svr.listen_after_bind(); });
  2993. auto se = detail::scope_exit([&] {
  2994. svr.stop();
  2995. t.join();
  2996. });
  2997. svr.wait_until_ready();
  2998. Client cli(HOST, port);
  2999. cli.set_digest_auth("hello", "world");
  3000. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3002. EXPECT_EQ("/a%20b?x=1", target);
  3003. EXPECT_EQ(target, uri);
  3004. }
  3005. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3006. // make_digest_authentication_header() dereferences both unconditionally, so
  3007. // a server sending a challenge missing either one must not be treated as
  3008. // usable -- doing so used to crash the client with std::out_of_range.
  3009. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3010. Server svr;
  3011. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3012. res.status = StatusCode::Unauthorized_401;
  3013. res.set_header("WWW-Authenticate", challenge);
  3014. });
  3015. auto port = svr.bind_to_any_port(HOST);
  3016. std::thread t([&]() { svr.listen_after_bind(); });
  3017. auto se = detail::scope_exit([&] {
  3018. svr.stop();
  3019. t.join();
  3020. });
  3021. svr.wait_until_ready();
  3022. Client cli(HOST, port);
  3023. cli.set_digest_auth("hello", "world");
  3024. auto res = cli.Get("/x");
  3025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3026. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3027. }
  3028. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3029. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3030. }
  3031. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3032. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3033. }
  3034. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3035. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3036. }
  3037. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3038. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3039. // when storing the values, so the header builder has to re-escape them (and
  3040. // keep algorithm a bare token); otherwise the value breaks out of its
  3041. // quoted-string and injects extra auth-params into the client's Authorization.
  3042. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3043. std::atomic<int> hits{0};
  3044. std::string authorization;
  3045. Server svr;
  3046. svr.Get("/x", [&](const Request &req, Response &res) {
  3047. if (++hits == 1) {
  3048. res.status = StatusCode::Unauthorized_401;
  3049. // On the wire the quotes embedded in the values are backslash-escaped.
  3050. res.set_header("WWW-Authenticate",
  3051. "Digest realm=\"testrealm\", "
  3052. "nonce=\"n\\\"; injected=\\\"x\", "
  3053. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3054. } else {
  3055. authorization = req.get_header_value("Authorization");
  3056. res.set_content("ok", "text/plain");
  3057. }
  3058. });
  3059. auto port = svr.bind_to_any_port(HOST);
  3060. std::thread t([&]() { svr.listen_after_bind(); });
  3061. auto se = detail::scope_exit([&] {
  3062. svr.stop();
  3063. t.join();
  3064. });
  3065. svr.wait_until_ready();
  3066. Client cli(HOST, port);
  3067. cli.set_digest_auth("hello", "world");
  3068. auto res = cli.Get("/x");
  3069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3070. EXPECT_EQ(2, hits.load());
  3071. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3072. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3073. // inside its quoted-string rather than starting an "injected" auth-param.
  3074. EXPECT_NE(std::string::npos,
  3075. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3076. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3077. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3078. }
  3079. #endif
  3080. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3081. auto host = "google.com";
  3082. auto another_host = "example.com";
  3083. auto wrong_ip = "0.0.0.0";
  3084. #ifdef CPPHTTPLIB_SSL_ENABLED
  3085. SSLClient cli(host);
  3086. #else
  3087. Client cli(host);
  3088. #endif
  3089. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3090. auto res = cli.Get("/");
  3091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3092. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3093. }
  3094. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3095. auto host = "google.com";
  3096. auto wrong_ip = "0.0.0.0";
  3097. #ifdef CPPHTTPLIB_SSL_ENABLED
  3098. SSLClient cli(host);
  3099. #else
  3100. Client cli(host);
  3101. #endif
  3102. cli.set_hostname_addr_map({{host, wrong_ip}});
  3103. auto res = cli.Get("/");
  3104. ASSERT_TRUE(!res);
  3105. EXPECT_EQ(Error::Connection, res.error());
  3106. }
  3107. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3108. // A mapped value that is not an IP literal must be resolved. "localhost"
  3109. // resolves from the hosts file, so this test needs no external DNS.
  3110. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3111. auto host = "target.invalid";
  3112. Server svr;
  3113. std::string received_host;
  3114. svr.Get("/hi", [&](const Request &req, Response &res) {
  3115. received_host = req.get_header_value("Host");
  3116. res.set_content("Hello World!", "text/plain");
  3117. });
  3118. auto port = svr.bind_to_any_port(HOST);
  3119. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3120. auto se = detail::scope_exit([&] {
  3121. svr.stop();
  3122. thread.join();
  3123. ASSERT_FALSE(svr.is_running());
  3124. });
  3125. svr.wait_until_ready();
  3126. Client cli(host, port);
  3127. cli.set_hostname_addr_map({{host, HOST}});
  3128. auto res = cli.Get("/hi");
  3129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3130. EXPECT_EQ(StatusCode::OK_200, res->status);
  3131. // The mapping only redirects the connection; the identity stays host_.
  3132. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3133. }
  3134. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3135. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3136. auto host = "target.invalid";
  3137. Server svr;
  3138. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3139. res.set_content("Hello World!", "text/plain");
  3140. });
  3141. auto port = svr.bind_to_any_port("127.0.0.1");
  3142. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3143. auto se = detail::scope_exit([&] {
  3144. svr.stop();
  3145. thread.join();
  3146. ASSERT_FALSE(svr.is_running());
  3147. });
  3148. svr.wait_until_ready();
  3149. Client cli(host, port);
  3150. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3151. auto res = cli.Get("/hi");
  3152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. }
  3155. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3156. // An empty mapped value must leave host_ as the connection target. Without
  3157. // that guard the empty value would become the host argument, getaddrinfo
  3158. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3159. // loopback - silently connecting somewhere the caller never asked for.
  3160. // The server listens on loopback, so such a fallback would succeed and is
  3161. // therefore observable as a failure of this test.
  3162. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3163. Server svr;
  3164. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3165. res.set_content("Hello World!", "text/plain");
  3166. });
  3167. auto port = svr.bind_to_any_port(HOST);
  3168. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3169. auto se = detail::scope_exit([&] {
  3170. svr.stop();
  3171. thread.join();
  3172. ASSERT_FALSE(svr.is_running());
  3173. });
  3174. svr.wait_until_ready();
  3175. Client cli(blackhole, port);
  3176. cli.set_hostname_addr_map({{blackhole, ""}});
  3177. cli.set_connection_timeout(1);
  3178. auto res = cli.Get("/hi");
  3179. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3180. }
  3181. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3182. auto host = "httpbingo.org";
  3183. auto path = std::string{"/absolute-redirect/3"};
  3184. #ifdef CPPHTTPLIB_SSL_ENABLED
  3185. SSLClient cli(host);
  3186. #else
  3187. Client cli(host);
  3188. #endif
  3189. cli.set_follow_location(true);
  3190. auto res = cli.Get(path);
  3191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3192. EXPECT_EQ(StatusCode::OK_200, res->status);
  3193. }
  3194. TEST(RedirectTest, Redirect_Online) {
  3195. auto host = "httpbingo.org";
  3196. auto path = std::string{"/redirect/3"};
  3197. #ifdef CPPHTTPLIB_SSL_ENABLED
  3198. SSLClient cli(host);
  3199. #else
  3200. Client cli(host);
  3201. #endif
  3202. cli.set_follow_location(true);
  3203. auto res = cli.Get(path);
  3204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3205. EXPECT_EQ(StatusCode::OK_200, res->status);
  3206. }
  3207. TEST(RelativeRedirectTest, Redirect_Online) {
  3208. auto host = "httpbingo.org";
  3209. auto path = std::string{"/relative-redirect/3"};
  3210. #ifdef CPPHTTPLIB_SSL_ENABLED
  3211. SSLClient cli(host);
  3212. #else
  3213. Client cli(host);
  3214. #endif
  3215. cli.set_follow_location(true);
  3216. auto res = cli.Get(path);
  3217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3218. EXPECT_EQ(StatusCode::OK_200, res->status);
  3219. }
  3220. TEST(TooManyRedirectTest, Redirect_Online) {
  3221. auto host = "httpbingo.org";
  3222. auto path = std::string{"/redirect/21"};
  3223. #ifdef CPPHTTPLIB_SSL_ENABLED
  3224. SSLClient cli(host);
  3225. #else
  3226. Client cli(host);
  3227. #endif
  3228. cli.set_follow_location(true);
  3229. auto res = cli.Get(path);
  3230. ASSERT_TRUE(!res);
  3231. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3232. }
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. TEST(YahooRedirectTest, Redirect_Online) {
  3235. Client cli("yahoo.com");
  3236. auto res = cli.Get("/");
  3237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3238. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3239. cli.set_follow_location(true);
  3240. res = cli.Get("/");
  3241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3242. EXPECT_EQ(StatusCode::OK_200, res->status);
  3243. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3244. }
  3245. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3246. #define REDIR_HOST "httpbingo.org"
  3247. #define REDIR_PATH "/redirect-to"
  3248. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3249. SSLClient cli(REDIR_HOST);
  3250. cli.set_follow_location(true);
  3251. auto res =
  3252. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::OK_200, res->status);
  3255. }
  3256. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3257. SSLClient cli(REDIR_HOST);
  3258. cli.set_follow_location(true);
  3259. Params params;
  3260. params.emplace("url", "http://example.com");
  3261. params.emplace("status_code", "302");
  3262. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3264. EXPECT_EQ(StatusCode::OK_200, res->status);
  3265. }
  3266. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3267. SSLClient cli(REDIR_HOST);
  3268. cli.set_follow_location(true);
  3269. Params params;
  3270. params.emplace("url", "http://example.com");
  3271. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3273. EXPECT_EQ(StatusCode::OK_200, res->status);
  3274. }
  3275. TEST(UrlWithSpace, Redirect_Online) {
  3276. SSLClient cli("edge.forgecdn.net");
  3277. cli.set_follow_location(true);
  3278. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3282. }
  3283. #endif
  3284. #if !defined(_WIN32) && !defined(_WIN64)
  3285. TEST(ReceiveSignals, Signal) {
  3286. auto setupSignalHandlers = []() {
  3287. struct sigaction act;
  3288. sigemptyset(&act.sa_mask);
  3289. act.sa_flags = SA_SIGINFO;
  3290. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3291. switch (sig) {
  3292. case SIGINT:
  3293. default: break;
  3294. }
  3295. };
  3296. ::sigaction(SIGINT, &act, nullptr);
  3297. };
  3298. Server svr;
  3299. int port = 0;
  3300. auto thread = std::thread([&]() {
  3301. setupSignalHandlers();
  3302. port = svr.bind_to_any_port(HOST);
  3303. svr.listen_after_bind();
  3304. });
  3305. auto se = detail::scope_exit([&] {
  3306. svr.stop();
  3307. thread.join();
  3308. ASSERT_FALSE(svr.is_running());
  3309. });
  3310. svr.wait_until_ready();
  3311. ASSERT_TRUE(svr.is_running());
  3312. pthread_kill(thread.native_handle(), SIGINT);
  3313. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3314. ASSERT_TRUE(svr.is_running());
  3315. }
  3316. #endif
  3317. TEST(RedirectToDifferentPort, Redirect) {
  3318. Server svr1;
  3319. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3320. res.set_content("Hello World!", "text/plain");
  3321. });
  3322. int svr1_port = 0;
  3323. auto thread1 = std::thread([&]() {
  3324. svr1_port = svr1.bind_to_any_port(HOST);
  3325. svr1.listen_after_bind();
  3326. });
  3327. Server svr2;
  3328. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3329. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3330. });
  3331. int svr2_port = 0;
  3332. auto thread2 = std::thread([&]() {
  3333. svr2_port = svr2.bind_to_any_port(HOST);
  3334. svr2.listen_after_bind();
  3335. });
  3336. auto se = detail::scope_exit([&] {
  3337. svr2.stop();
  3338. thread2.join();
  3339. svr1.stop();
  3340. thread1.join();
  3341. ASSERT_FALSE(svr2.is_running());
  3342. ASSERT_FALSE(svr1.is_running());
  3343. });
  3344. svr1.wait_until_ready();
  3345. svr2.wait_until_ready();
  3346. Client cli("localhost", svr2_port);
  3347. cli.set_follow_location(true);
  3348. auto res = cli.Get("/2");
  3349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3350. EXPECT_EQ(StatusCode::OK_200, res->status);
  3351. EXPECT_EQ("Hello World!", res->body);
  3352. }
  3353. // GET /redir on one server redirects to /target on another port, so the
  3354. // client follows it with a new client.
  3355. static Result
  3356. GetThroughRedirectToDifferentPort(Server::Handler target,
  3357. const std::function<void(Client &)> &setup,
  3358. const Headers &headers = Headers()) {
  3359. Server target_svr;
  3360. target_svr.Get("/target", target);
  3361. int target_port = 0;
  3362. auto target_thread = std::thread([&]() {
  3363. target_port = target_svr.bind_to_any_port(HOST);
  3364. target_svr.listen_after_bind();
  3365. });
  3366. Server origin_svr;
  3367. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3368. res.set_redirect(
  3369. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3370. });
  3371. int origin_port = 0;
  3372. auto origin_thread = std::thread([&]() {
  3373. origin_port = origin_svr.bind_to_any_port(HOST);
  3374. origin_svr.listen_after_bind();
  3375. });
  3376. auto se = detail::scope_exit([&] {
  3377. origin_svr.stop();
  3378. origin_thread.join();
  3379. target_svr.stop();
  3380. target_thread.join();
  3381. });
  3382. target_svr.wait_until_ready();
  3383. origin_svr.wait_until_ready();
  3384. Client cli("localhost", origin_port);
  3385. cli.set_follow_location(true);
  3386. setup(cli);
  3387. return cli.Get("/redir", headers);
  3388. }
  3389. static void
  3390. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3391. std::string captured_authorization;
  3392. auto result = GetThroughRedirectToDifferentPort(
  3393. [&](const Request &req, Response &res) {
  3394. captured_authorization = req.get_header_value("Authorization");
  3395. res.set_content("OK", "text/plain");
  3396. },
  3397. set_auth);
  3398. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3399. EXPECT_EQ(StatusCode::OK_200, result->status);
  3400. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3401. EXPECT_TRUE(captured_authorization.empty());
  3402. }
  3403. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3404. TestDoNotForwardCredentialsOnRedirect(
  3405. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3406. }
  3407. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3408. TestDoNotForwardCredentialsOnRedirect(
  3409. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3410. }
  3411. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3412. std::string captured_cookie;
  3413. auto result = GetThroughRedirectToDifferentPort(
  3414. [&](const Request &req, Response &res) {
  3415. captured_cookie = req.get_header_value("Cookie");
  3416. res.set_content("OK", "text/plain");
  3417. },
  3418. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3419. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3420. EXPECT_EQ(StatusCode::OK_200, result->status);
  3421. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3422. EXPECT_TRUE(captured_cookie.empty());
  3423. }
  3424. TEST(RedirectToSamePort, ForwardCookie) {
  3425. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3426. // header so that ordinary session flows keep working.
  3427. Server svr;
  3428. std::string captured_cookie;
  3429. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3430. res.set_redirect("/target", 302);
  3431. });
  3432. svr.Get("/target", [&](const Request &req, Response &res) {
  3433. captured_cookie = req.get_header_value("Cookie");
  3434. res.set_content("OK", "text/plain");
  3435. });
  3436. auto port = svr.bind_to_any_port(HOST);
  3437. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3438. auto se = detail::scope_exit([&] {
  3439. svr.stop();
  3440. thread.join();
  3441. ASSERT_FALSE(svr.is_running());
  3442. });
  3443. svr.wait_until_ready();
  3444. Client cli(HOST, port);
  3445. cli.set_follow_location(true);
  3446. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3447. auto res = cli.Get("/redir", headers);
  3448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3449. EXPECT_EQ(StatusCode::OK_200, res->status);
  3450. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3451. }
  3452. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3453. std::string authorization;
  3454. std::string trace_id;
  3455. auto result = GetThroughRedirectToDifferentPort(
  3456. [&](const Request &req, Response &res) {
  3457. authorization = req.get_header_value("Authorization");
  3458. trace_id = req.get_header_value("X-Trace-Id");
  3459. res.set_content("OK", "text/plain");
  3460. },
  3461. [](Client &cli) {
  3462. cli.set_default_headers(
  3463. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3464. });
  3465. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3466. EXPECT_EQ(StatusCode::OK_200, result->status);
  3467. // Like a header given with the request, a default one goes along unless it
  3468. // carries credentials (RFC 9110 15.4).
  3469. EXPECT_TRUE(authorization.empty());
  3470. EXPECT_EQ("42", trace_id);
  3471. }
  3472. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3473. auto result = GetThroughRedirectToDifferentPort(
  3474. [](const Request &, Response &res) {
  3475. res.set_content(std::string(2048, 'x'), "text/plain");
  3476. },
  3477. [](Client &cli) { cli.set_payload_max_length(1024); });
  3478. EXPECT_FALSE(result);
  3479. }
  3480. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3481. auto result = GetThroughRedirectToDifferentPort(
  3482. [](const Request &req, Response &res) {
  3483. // Answer after a second, or once the client gives up.
  3484. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3485. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3486. }
  3487. res.set_content("late", "text/plain");
  3488. },
  3489. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3490. ASSERT_FALSE(result);
  3491. EXPECT_EQ(Error::Read, result.error());
  3492. }
  3493. #ifdef CPPHTTPLIB_SSL_ENABLED
  3494. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3495. auto result = GetThroughRedirectToDifferentPort(
  3496. [](const Request &, Response &res) {
  3497. res.status = StatusCode::Unauthorized_401;
  3498. res.set_header("WWW-Authenticate",
  3499. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3500. },
  3501. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3502. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3503. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3504. }
  3505. #endif
  3506. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3507. Server svr;
  3508. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3509. // Port number that overflows int — should not crash
  3510. res.set_redirect("http://localhost:99999999999999999999/target");
  3511. });
  3512. auto port = svr.bind_to_any_port(HOST);
  3513. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3514. auto se = detail::scope_exit([&] {
  3515. svr.stop();
  3516. thread.join();
  3517. ASSERT_FALSE(svr.is_running());
  3518. });
  3519. svr.wait_until_ready();
  3520. Client cli(HOST, port);
  3521. cli.set_follow_location(true);
  3522. auto res = cli.Get("/redir");
  3523. // Should fail gracefully, not crash (no valid response due to bad port)
  3524. EXPECT_FALSE(res);
  3525. }
  3526. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3527. Server svr;
  3528. auto port = svr.bind_to_any_port(HOST);
  3529. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3530. // The server's own port followed by junk must not be followed
  3531. res.set_redirect("http://" + std::string(HOST) + ":" +
  3532. std::to_string(port) + "junk/target");
  3533. });
  3534. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3535. res.set_content("target", "text/plain");
  3536. });
  3537. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3538. auto se = detail::scope_exit([&] {
  3539. svr.stop();
  3540. thread.join();
  3541. ASSERT_FALSE(svr.is_running());
  3542. });
  3543. svr.wait_until_ready();
  3544. Client cli(HOST, port);
  3545. cli.set_follow_location(true);
  3546. auto res = cli.Get("/redir");
  3547. EXPECT_FALSE(res);
  3548. }
  3549. TEST(RedirectFromPageWithContent, Redirect) {
  3550. Server svr;
  3551. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3552. res.set_content("___", "text/plain");
  3553. res.set_redirect("/2");
  3554. });
  3555. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3556. res.set_content("Hello World!", "text/plain");
  3557. });
  3558. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3559. auto se = detail::scope_exit([&] {
  3560. svr.stop();
  3561. th.join();
  3562. ASSERT_FALSE(svr.is_running());
  3563. });
  3564. svr.wait_until_ready();
  3565. {
  3566. Client cli("localhost", PORT);
  3567. cli.set_follow_location(true);
  3568. std::string body;
  3569. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3570. body.append(data, data_length);
  3571. return true;
  3572. });
  3573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3574. EXPECT_EQ(StatusCode::OK_200, res->status);
  3575. EXPECT_EQ("Hello World!", body);
  3576. }
  3577. {
  3578. Client cli("localhost", PORT);
  3579. std::string body;
  3580. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3581. body.append(data, data_length);
  3582. return true;
  3583. });
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ(StatusCode::Found_302, res->status);
  3586. EXPECT_EQ("___", body);
  3587. }
  3588. }
  3589. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3590. Server svr;
  3591. auto port_str = std::to_string(PORT);
  3592. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3593. auto expected_host = "[::1]:" + port_str;
  3594. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3595. res.set_content("___", "text/plain");
  3596. // res.set_redirect("/2");
  3597. res.set_redirect(redirect_url);
  3598. });
  3599. svr.Get("/2", [&](const Request &req, Response &res) {
  3600. auto host_header = req.headers.find("Host");
  3601. ASSERT_TRUE(host_header != req.headers.end());
  3602. EXPECT_EQ(expected_host, host_header->second);
  3603. res.set_content("Hello World!", "text/plain");
  3604. });
  3605. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3606. auto se = detail::scope_exit([&] {
  3607. svr.stop();
  3608. th.join();
  3609. ASSERT_FALSE(svr.is_running());
  3610. });
  3611. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3612. // actually starts anything, so the condition !svr.is_running() will
  3613. // always remain true, and the loop never stops.
  3614. // This basically counts how many milliseconds have passed since the
  3615. // call to svr.listen(), and if after 5 seconds nothing started yet
  3616. // aborts the test.
  3617. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3618. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3619. ASSERT_LT(milliseconds, 5000U);
  3620. }
  3621. {
  3622. Client cli("::1", PORT);
  3623. cli.set_follow_location(true);
  3624. std::string body;
  3625. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3626. body.append(data, data_length);
  3627. return true;
  3628. });
  3629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3630. EXPECT_EQ(StatusCode::OK_200, res->status);
  3631. EXPECT_EQ("Hello World!", body);
  3632. }
  3633. {
  3634. Client cli("::1", PORT);
  3635. std::string body;
  3636. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3637. body.append(data, data_length);
  3638. return true;
  3639. });
  3640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3641. EXPECT_EQ(StatusCode::Found_302, res->status);
  3642. EXPECT_EQ("___", body);
  3643. }
  3644. }
  3645. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3646. Server svr;
  3647. svr.Get("/foo", [](const Request &req, Response &res) {
  3648. auto a = req.params.find("a");
  3649. if (a != req.params.end()) {
  3650. res.set_content((*a).second, "text/plain");
  3651. res.status = StatusCode::OK_200;
  3652. } else {
  3653. res.status = StatusCode::BadRequest_400;
  3654. }
  3655. });
  3656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3657. auto se = detail::scope_exit([&] {
  3658. svr.stop();
  3659. thread.join();
  3660. ASSERT_FALSE(svr.is_running());
  3661. });
  3662. svr.wait_until_ready();
  3663. {
  3664. Client cli(HOST, PORT);
  3665. cli.set_path_encode(false);
  3666. auto res = cli.Get("/foo?a=explicitly+encoded");
  3667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3668. EXPECT_EQ(StatusCode::OK_200, res->status);
  3669. // This expects it back with a space, as the `+` won't have been
  3670. // url-encoded, and server-side the params get decoded turning `+`
  3671. // into spaces.
  3672. EXPECT_EQ("explicitly encoded", res->body);
  3673. }
  3674. }
  3675. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3676. // When path encoding is disabled the client must transmit the supplied
  3677. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3678. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3679. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3680. // than a space (0x20). Assert on the raw wire target to catch this.
  3681. Server svr;
  3682. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3683. svr.Get("/foo", [&](const Request &req, Response &res) {
  3684. EXPECT_EQ(expected_target, req.target);
  3685. res.status = StatusCode::OK_200;
  3686. });
  3687. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3688. auto se = detail::scope_exit([&] {
  3689. svr.stop();
  3690. thread.join();
  3691. ASSERT_FALSE(svr.is_running());
  3692. });
  3693. svr.wait_until_ready();
  3694. {
  3695. Client cli(HOST, PORT);
  3696. cli.set_path_encode(false);
  3697. auto res = cli.Get(expected_target.c_str());
  3698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3699. EXPECT_EQ(StatusCode::OK_200, res->status);
  3700. }
  3701. }
  3702. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3703. // `open_stream()` used to skip the path encoding that the buffered send
  3704. // path applies, so the same `path` produced different bytes in the request
  3705. // line depending on which API was used. Assert the two agree.
  3706. Server svr;
  3707. std::string target;
  3708. svr.Get(".*", [&](const Request &req, Response &res) {
  3709. target = req.target;
  3710. res.status = StatusCode::OK_200;
  3711. });
  3712. auto port = svr.bind_to_any_port(HOST);
  3713. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3714. auto se = detail::scope_exit([&] {
  3715. svr.stop();
  3716. thread.join();
  3717. ASSERT_FALSE(svr.is_running());
  3718. });
  3719. svr.wait_until_ready();
  3720. struct {
  3721. const char *path;
  3722. const char *expected;
  3723. } cases[] = {
  3724. {"/a b?x=1", "/a%20b?x=1"},
  3725. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3726. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3727. };
  3728. for (const auto &c : cases) {
  3729. Client cli(HOST, port);
  3730. target.clear();
  3731. auto res = cli.Get(c.path);
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3734. auto buffered_target = target;
  3735. target.clear();
  3736. auto handle = cli.open_stream("GET", c.path);
  3737. EXPECT_TRUE(handle.is_valid())
  3738. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3739. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3740. }
  3741. }
  3742. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3743. // The `set_path_encode(false)` contract — transmit the supplied target
  3744. // verbatim — must hold for the streaming API too.
  3745. Server svr;
  3746. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3747. std::string target;
  3748. svr.Get("/foo", [&](const Request &req, Response &res) {
  3749. target = req.target;
  3750. res.status = StatusCode::OK_200;
  3751. });
  3752. auto port = svr.bind_to_any_port(HOST);
  3753. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3754. auto se = detail::scope_exit([&] {
  3755. svr.stop();
  3756. thread.join();
  3757. ASSERT_FALSE(svr.is_running());
  3758. });
  3759. svr.wait_until_ready();
  3760. {
  3761. Client cli(HOST, port);
  3762. cli.set_path_encode(false);
  3763. auto handle = cli.open_stream("GET", expected_target);
  3764. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3765. EXPECT_EQ(expected_target, target);
  3766. }
  3767. }
  3768. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3769. // With path encoding enabled a CR/LF in the target is percent-encoded
  3770. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3771. // write_request_line still backstops `set_path_encode(false)`, which is
  3772. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3773. Server svr;
  3774. // Captured before routing: the decoded path contains a newline, which a
  3775. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3776. std::string target;
  3777. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3778. target = req.target;
  3779. res.status = StatusCode::OK_200;
  3780. return Server::HandlerResponse::Handled;
  3781. });
  3782. auto port = svr.bind_to_any_port(HOST);
  3783. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3784. auto se = detail::scope_exit([&] {
  3785. svr.stop();
  3786. thread.join();
  3787. ASSERT_FALSE(svr.is_running());
  3788. });
  3789. svr.wait_until_ready();
  3790. {
  3791. Client cli(HOST, port);
  3792. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3793. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3794. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3795. }
  3796. }
  3797. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3798. // Every control character is percent-encoded, not just CR/LF, so the target
  3799. // passes the request-target check in write_request_line.
  3800. Server svr;
  3801. std::string target;
  3802. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3803. target = req.target;
  3804. res.status = StatusCode::OK_200;
  3805. return Server::HandlerResponse::Handled;
  3806. });
  3807. auto port = svr.bind_to_any_port(HOST);
  3808. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3809. auto se = detail::scope_exit([&] {
  3810. svr.stop();
  3811. thread.join();
  3812. ASSERT_FALSE(svr.is_running());
  3813. });
  3814. svr.wait_until_ready();
  3815. {
  3816. Client cli(HOST, port);
  3817. auto res = cli.Get("/a\tb\x1b\x7f");
  3818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3819. EXPECT_EQ("/a%09b%1B%7F", target);
  3820. }
  3821. }
  3822. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3823. // Nothing may reach the wire: a raw CR/LF target would split the request
  3824. // line and inject headers.
  3825. Server svr;
  3826. // Pre-routing so that "not called" means nothing reached the server at all,
  3827. // rather than merely failing to match a handler pattern.
  3828. auto handler_called = false;
  3829. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3830. handler_called = true;
  3831. res.status = StatusCode::OK_200;
  3832. return Server::HandlerResponse::Handled;
  3833. });
  3834. auto port = svr.bind_to_any_port(HOST);
  3835. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3836. auto se = detail::scope_exit([&] {
  3837. svr.stop();
  3838. thread.join();
  3839. ASSERT_FALSE(svr.is_running());
  3840. });
  3841. svr.wait_until_ready();
  3842. {
  3843. Client cli(HOST, port);
  3844. cli.set_path_encode(false);
  3845. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3846. EXPECT_FALSE(handle.is_valid());
  3847. EXPECT_EQ(Error::Write, handle.error);
  3848. EXPECT_FALSE(handler_called);
  3849. }
  3850. }
  3851. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3852. // Which of the two branches runs is decided by whether the query component
  3853. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3854. // an empty query and must still fall back to building one from
  3855. // `req.params`, while a non-empty query must win over `req.params`.
  3856. Server svr;
  3857. std::string target;
  3858. svr.Get("/foo", [&](const Request &req, Response &res) {
  3859. target = req.target;
  3860. res.status = StatusCode::OK_200;
  3861. });
  3862. auto port = svr.bind_to_any_port(HOST);
  3863. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3864. auto se = detail::scope_exit([&] {
  3865. svr.stop();
  3866. thread.join();
  3867. ASSERT_FALSE(svr.is_running());
  3868. });
  3869. svr.wait_until_ready();
  3870. {
  3871. // Trailing `?` -> empty query component -> `req.params` is used.
  3872. Client cli(HOST, port);
  3873. Request req;
  3874. req.method = "GET";
  3875. req.path = "/foo?";
  3876. req.params.emplace("a", "1");
  3877. target.clear();
  3878. auto res = cli.send(req);
  3879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3880. EXPECT_EQ("/foo?a=1", target);
  3881. }
  3882. {
  3883. // Non-empty query in `req.path` -> `req.params` is not appended.
  3884. Client cli(HOST, port);
  3885. Request req;
  3886. req.method = "GET";
  3887. req.path = "/foo?b=2";
  3888. req.params.emplace("a", "1");
  3889. target.clear();
  3890. auto res = cli.send(req);
  3891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3892. EXPECT_EQ("/foo?b=2", target);
  3893. }
  3894. }
  3895. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3896. Server svr;
  3897. svr.Get("/", [](const Request &req, Response &) {
  3898. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3899. });
  3900. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3901. auto se = detail::scope_exit([&] {
  3902. svr.stop();
  3903. thread.join();
  3904. ASSERT_FALSE(svr.is_running());
  3905. });
  3906. svr.wait_until_ready();
  3907. {
  3908. Client cli(HOST, PORT);
  3909. cli.set_path_encode(false);
  3910. auto res = cli.Get("/?something=%0A");
  3911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3912. EXPECT_EQ(StatusCode::OK_200, res->status);
  3913. }
  3914. }
  3915. TEST(BindServerTest, BindDualStack) {
  3916. Server svr;
  3917. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3918. res.set_content("Hello World!", "text/plain");
  3919. });
  3920. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3921. auto se = detail::scope_exit([&] {
  3922. svr.stop();
  3923. thread.join();
  3924. ASSERT_FALSE(svr.is_running());
  3925. });
  3926. svr.wait_until_ready();
  3927. {
  3928. Client cli("127.0.0.1", PORT);
  3929. auto res = cli.Get("/1");
  3930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3931. EXPECT_EQ(StatusCode::OK_200, res->status);
  3932. EXPECT_EQ("Hello World!", res->body);
  3933. }
  3934. {
  3935. Client cli("::1", PORT);
  3936. auto res = cli.Get("/1");
  3937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3938. EXPECT_EQ(StatusCode::OK_200, res->status);
  3939. EXPECT_EQ("Hello World!", res->body);
  3940. }
  3941. }
  3942. TEST(BindServerTest, BindAndListenSeparately) {
  3943. Server svr;
  3944. int port = svr.bind_to_any_port("0.0.0.0");
  3945. ASSERT_TRUE(svr.is_valid());
  3946. ASSERT_TRUE(port > 0);
  3947. svr.stop();
  3948. }
  3949. // Reports whether anything is still listening on a loopback port. A plain
  3950. // connect() is used instead of a Client request because a socket left bound by
  3951. // mistake accepts the connection into its backlog and never answers, which
  3952. // would hang the test instead of failing it.
  3953. static bool is_loopback_port_accepting(int port) {
  3954. sockaddr_in addr{};
  3955. addr.sin_family = AF_INET;
  3956. addr.sin_port = htons(static_cast<uint16_t>(port));
  3957. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3958. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3959. EXPECT_NE(sock, INVALID_SOCKET);
  3960. if (sock == INVALID_SOCKET) { return false; }
  3961. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3962. static_cast<socklen_t>(sizeof(addr)));
  3963. detail::close_socket(sock);
  3964. return ret == 0;
  3965. }
  3966. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3967. Server svr;
  3968. auto port = svr.bind_to_any_port("127.0.0.1");
  3969. ASSERT_TRUE(port > 0);
  3970. svr.stop();
  3971. // bind_to_any_port() already called listen(2), so until stop() closed the
  3972. // descriptor the port kept accepting connections into the backlog. ASSERT
  3973. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3974. // below blocks forever in the accept loop.
  3975. ASSERT_FALSE(is_loopback_port_accepting(port));
  3976. // Nothing is left to accept on, so listen_after_bind() must report failure
  3977. // instead of returning success without ever serving.
  3978. EXPECT_FALSE(svr.listen_after_bind());
  3979. // The failed listen marks the server decommissioned, so a waiter returns
  3980. // instead of spinning forever.
  3981. svr.wait_until_ready();
  3982. }
  3983. #ifdef CPPHTTPLIB_SSL_ENABLED
  3984. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3985. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3986. CLIENT_CA_CERT_DIR);
  3987. int port = svr.bind_to_any_port("0.0.0.0");
  3988. ASSERT_TRUE(svr.is_valid());
  3989. ASSERT_TRUE(port > 0);
  3990. svr.stop();
  3991. }
  3992. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3993. // or a rejected CustomRoute() registration would not stop the server binding.
  3994. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3996. CLIENT_CA_CERT_DIR);
  3997. ASSERT_TRUE(svr.is_valid());
  3998. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3999. EXPECT_FALSE(svr.is_valid());
  4000. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4001. }
  4002. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4003. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4004. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4005. int port = svr.bind_to_any_port("0.0.0.0");
  4006. ASSERT_TRUE(svr.is_valid());
  4007. ASSERT_TRUE(port > 0);
  4008. svr.stop();
  4009. }
  4010. TEST(BindServerTest, UpdateCertsPem) {
  4011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4012. int port = svr.bind_to_any_port("0.0.0.0");
  4013. ASSERT_TRUE(svr.is_valid());
  4014. ASSERT_TRUE(port > 0);
  4015. // Read PEM files
  4016. std::string cert_pem, key_pem, ca_pem;
  4017. read_file(SERVER_CERT_FILE, cert_pem);
  4018. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4019. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4020. // Update server certificates using PEM API
  4021. ASSERT_TRUE(
  4022. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4023. ASSERT_TRUE(svr.is_valid());
  4024. svr.stop();
  4025. }
  4026. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4027. // Start server with client CA (enables client auth)
  4028. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4029. ASSERT_TRUE(svr.is_valid());
  4030. bool handler_called = false;
  4031. svr.Get("/test", [&](const Request &req, Response &res) {
  4032. handler_called = true;
  4033. // Verify client certificate is present
  4034. auto cert = req.peer_cert();
  4035. EXPECT_TRUE(static_cast<bool>(cert));
  4036. res.set_content("ok", "text/plain");
  4037. });
  4038. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4039. auto se = detail::scope_exit([&] {
  4040. svr.stop();
  4041. t.join();
  4042. ASSERT_FALSE(svr.is_running());
  4043. });
  4044. svr.wait_until_ready();
  4045. // Read PEM files
  4046. std::string cert_pem, key_pem, ca_pem;
  4047. read_file(SERVER_CERT_FILE, cert_pem);
  4048. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4049. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4050. // Update server certificates and client CA using PEM API while server running
  4051. ASSERT_TRUE(
  4052. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4053. // Connect with client certificate
  4054. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4055. cli.enable_server_certificate_verification(false);
  4056. cli.set_connection_timeout(30);
  4057. auto res = cli.Get("/test");
  4058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4059. ASSERT_EQ(StatusCode::OK_200, res->status);
  4060. ASSERT_TRUE(handler_called);
  4061. EXPECT_EQ("ok", res->body);
  4062. }
  4063. // Puts a CA that did not sign the client's certificate in the old one's place.
  4064. static bool replace_client_ca(SSLServer &svr) {
  4065. std::string cert_pem, key_pem, ca_pem;
  4066. read_file(SERVER_CERT_FILE, cert_pem);
  4067. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4068. read_file(SERVER_CERT2_FILE, ca_pem);
  4069. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4070. ca_pem.c_str());
  4071. }
  4072. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4074. ASSERT_TRUE(svr.is_valid());
  4075. svr.Get("/test", [](const Request &, Response &res) {
  4076. res.set_content("ok", "text/plain");
  4077. });
  4078. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4079. auto se = detail::scope_exit([&] {
  4080. svr.stop();
  4081. t.join();
  4082. ASSERT_FALSE(svr.is_running());
  4083. });
  4084. svr.wait_until_ready();
  4085. auto get = [] {
  4086. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4087. cli.enable_server_certificate_verification(false);
  4088. return cli.Get("/test");
  4089. };
  4090. ASSERT_TRUE(get());
  4091. ASSERT_TRUE(replace_client_ca(svr));
  4092. EXPECT_FALSE(get());
  4093. }
  4094. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4095. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4097. ASSERT_TRUE(svr.is_valid());
  4098. tls::set_verify_callback(svr.tls_context(),
  4099. [](const tls::VerifyContext &) -> bool {
  4100. throw std::runtime_error("verify");
  4101. });
  4102. svr.Get("/test", [](const Request &, Response &res) {
  4103. res.set_content("ok", "text/plain");
  4104. });
  4105. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4106. auto se = detail::scope_exit([&] {
  4107. svr.stop();
  4108. t.join();
  4109. ASSERT_FALSE(svr.is_running());
  4110. });
  4111. svr.wait_until_ready();
  4112. auto get = [] {
  4113. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4114. cli.enable_server_certificate_verification(false);
  4115. return cli.Get("/test");
  4116. };
  4117. EXPECT_FALSE(get());
  4118. // The handshake is over, so an update does not wait for it.
  4119. std::string cert_pem, key_pem;
  4120. read_file(SERVER_CERT_FILE, cert_pem);
  4121. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4122. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4123. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4124. return v.preverify_ok;
  4125. });
  4126. auto res = get();
  4127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4128. EXPECT_EQ("ok", res->body);
  4129. }
  4130. #endif
  4131. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4132. // Sends each request over a new connection with a client certificate,
  4133. // resuming the session of the one before when there is one.
  4134. class ResumingClient {
  4135. public:
  4136. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4137. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4138. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4139. SSL_FILETYPE_PEM);
  4140. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4141. // callback, not through SSL_get1_session().
  4142. SSL_CTX_set_app_data(ctx_, this);
  4143. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4144. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4145. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4146. auto self = static_cast<ResumingClient *>(
  4147. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4148. SSL_SESSION_free(self->session_);
  4149. self->session_ = session;
  4150. return 1; // Keeps the reference
  4151. });
  4152. }
  4153. ~ResumingClient() {
  4154. SSL_SESSION_free(session_);
  4155. SSL_CTX_free(ctx_);
  4156. }
  4157. // Tells whether the request was answered.
  4158. bool get() {
  4159. auto error = Error::Success;
  4160. auto sock = detail::create_client_socket(
  4161. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4162. /*connection_timeout_sec=*/5, 0,
  4163. /*read_timeout_sec=*/5, 0,
  4164. /*write_timeout_sec=*/5, 0, std::string(), error);
  4165. if (sock == INVALID_SOCKET) { return false; }
  4166. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4167. auto ssl = SSL_new(ctx_);
  4168. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4169. SSL_set_fd(ssl, static_cast<int>(sock));
  4170. if (session_) { SSL_set_session(ssl, session_); }
  4171. if (SSL_connect(ssl) != 1) { return false; }
  4172. reused_ = SSL_session_reused(ssl) == 1;
  4173. // Reading the response also takes in a TLS 1.3 session ticket.
  4174. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4175. "Connection: close\r\n\r\n";
  4176. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4177. std::string res;
  4178. char buf[256];
  4179. int n;
  4180. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4181. res.append(buf, static_cast<size_t>(n));
  4182. }
  4183. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4184. SSL_shutdown(ssl);
  4185. return res.find("200 OK") != std::string::npos;
  4186. }
  4187. // Whether the last connection resumed a session
  4188. bool reused() const { return reused_; }
  4189. private:
  4190. SSL_CTX *ctx_;
  4191. SSL_SESSION *session_ = nullptr;
  4192. bool reused_ = false;
  4193. };
  4194. // A client that resumes its session gets through, but not once the client CA
  4195. // has changed, as a resumed session does not show the certificate again.
  4196. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4198. ASSERT_TRUE(svr.is_valid());
  4199. svr.Get("/test", [](const Request &, Response &res) {
  4200. res.set_content("ok", "text/plain");
  4201. });
  4202. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4203. auto se = detail::scope_exit([&] {
  4204. svr.stop();
  4205. t.join();
  4206. ASSERT_FALSE(svr.is_running());
  4207. });
  4208. svr.wait_until_ready();
  4209. ResumingClient cli;
  4210. ASSERT_TRUE(cli.get());
  4211. ASSERT_TRUE(cli.get());
  4212. EXPECT_TRUE(cli.reused());
  4213. ASSERT_TRUE(replace_client_ca(svr));
  4214. EXPECT_FALSE(cli.get());
  4215. }
  4216. // A resumed session does not show the certificate again, so the server does
  4217. // not resume one with a verify callback to run on it.
  4218. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4219. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4220. ASSERT_TRUE(svr.is_valid());
  4221. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4222. return v.preverify_ok;
  4223. });
  4224. svr.Get("/test", [](const Request &, Response &res) {
  4225. res.set_content("ok", "text/plain");
  4226. });
  4227. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4228. auto se = detail::scope_exit([&] {
  4229. svr.stop();
  4230. t.join();
  4231. ASSERT_FALSE(svr.is_running());
  4232. });
  4233. svr.wait_until_ready();
  4234. ResumingClient cli;
  4235. ASSERT_TRUE(cli.get());
  4236. ASSERT_TRUE(cli.get());
  4237. EXPECT_FALSE(cli.reused());
  4238. }
  4239. #endif
  4240. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4241. // wolfSSL shares its session cache between contexts, so a resumed session
  4242. // could carry a client certificate checked against another server's CA, or
  4243. // against a client CA since replaced.
  4244. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4246. ASSERT_TRUE(svr.is_valid());
  4247. // Trusts a CA that did not sign the client's certificate.
  4248. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4249. ASSERT_TRUE(other.is_valid());
  4250. for (auto s : {&svr, &other}) {
  4251. s->Get("/test", [](const Request &, Response &res) {
  4252. res.set_content("ok", "text/plain");
  4253. });
  4254. }
  4255. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4256. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4257. auto se = detail::scope_exit([&] {
  4258. other.stop();
  4259. svr.stop();
  4260. t2.join();
  4261. t.join();
  4262. });
  4263. svr.wait_until_ready();
  4264. other.wait_until_ready();
  4265. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4266. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4267. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4268. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4269. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4270. ASSERT_EQ(WOLFSSL_SUCCESS,
  4271. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4272. WOLFSSL_FILETYPE_PEM));
  4273. WOLFSSL_SESSION *session = nullptr;
  4274. auto session_se = detail::scope_exit([&] {
  4275. if (session) { wolfSSL_SESSION_free(session); }
  4276. });
  4277. // A request over a new connection, resuming `session` when there is one and
  4278. // keeping the connection's own in its place. Tells whether it was answered.
  4279. auto get = [&](int port) {
  4280. auto error = Error::Success;
  4281. auto sock = detail::create_client_socket(
  4282. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4283. /*connection_timeout_sec=*/5, 0,
  4284. /*read_timeout_sec=*/5, 0,
  4285. /*write_timeout_sec=*/5, 0, std::string(), error);
  4286. if (sock == INVALID_SOCKET) { return false; }
  4287. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4288. auto ssl = wolfSSL_new(ctx);
  4289. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4290. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4291. if (session) { wolfSSL_set_session(ssl, session); }
  4292. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4293. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4294. "Connection: close\r\n\r\n";
  4295. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4296. std::string res;
  4297. char buf[256];
  4298. int n;
  4299. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4300. res.append(buf, static_cast<size_t>(n));
  4301. }
  4302. wolfSSL_shutdown(ssl);
  4303. if (session) { wolfSSL_SESSION_free(session); }
  4304. session = wolfSSL_get1_session(ssl);
  4305. return res.find("200 OK") != std::string::npos;
  4306. };
  4307. ASSERT_TRUE(get(PORT));
  4308. EXPECT_FALSE(get(PORT + 1));
  4309. ASSERT_TRUE(get(PORT));
  4310. ASSERT_TRUE(replace_client_ca(svr));
  4311. EXPECT_FALSE(get(PORT));
  4312. }
  4313. #endif
  4314. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4315. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4316. ASSERT_TRUE(svr.is_valid());
  4317. svr.Get("/test", [](const Request &, Response &res) {
  4318. res.set_content("ok", "text/plain");
  4319. });
  4320. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4321. auto se = detail::scope_exit([&] {
  4322. svr.stop();
  4323. t.join();
  4324. ASSERT_FALSE(svr.is_running());
  4325. });
  4326. svr.wait_until_ready();
  4327. // A connection that sends no ClientHello keeps its handshake in progress,
  4328. // once the server has had a moment to start it.
  4329. auto error = Error::Success;
  4330. auto sock = detail::create_client_socket(
  4331. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4332. /*connection_timeout_sec=*/5, 0,
  4333. /*read_timeout_sec=*/5, 0,
  4334. /*write_timeout_sec=*/5, 0, std::string(), error);
  4335. ASSERT_NE(INVALID_SOCKET, sock);
  4336. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4337. std::string cert_pem, key_pem;
  4338. read_file(SERVER_CERT_FILE, cert_pem);
  4339. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4340. auto update = std::async(std::launch::async, [&]() {
  4341. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4342. });
  4343. EXPECT_EQ(std::future_status::timeout,
  4344. update.wait_for(std::chrono::milliseconds(200)));
  4345. detail::close_socket(sock);
  4346. EXPECT_TRUE(update.get());
  4347. SSLClient cli(HOST, PORT);
  4348. cli.enable_server_certificate_verification(false);
  4349. auto res = cli.Get("/test");
  4350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4351. EXPECT_EQ(StatusCode::OK_200, res->status);
  4352. }
  4353. #endif
  4354. TEST(ErrorHandlerTest, ContentLength) {
  4355. Server svr;
  4356. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4357. res.status = StatusCode::OK_200;
  4358. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4359. "text/html"); // <= Content-Length still 13
  4360. });
  4361. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4362. res.set_content("Hello World!\n", "text/plain");
  4363. res.status = 524;
  4364. });
  4365. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4366. auto se = detail::scope_exit([&] {
  4367. svr.stop();
  4368. thread.join();
  4369. ASSERT_FALSE(svr.is_running());
  4370. });
  4371. svr.wait_until_ready();
  4372. {
  4373. Client cli(HOST, PORT);
  4374. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4376. EXPECT_EQ(StatusCode::OK_200, res->status);
  4377. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4378. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4379. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4380. }
  4381. }
  4382. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4383. TEST(ExceptionTest, WithoutExceptionHandler) {
  4384. Server svr;
  4385. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4386. throw std::runtime_error("exception...");
  4387. });
  4388. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4389. throw std::runtime_error("exception\r\n...");
  4390. });
  4391. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4392. auto se = detail::scope_exit([&] {
  4393. svr.stop();
  4394. listen_thread.join();
  4395. ASSERT_FALSE(svr.is_running());
  4396. });
  4397. svr.wait_until_ready();
  4398. Client cli("localhost", PORT);
  4399. {
  4400. auto res = cli.Get("/exception");
  4401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4402. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4403. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4404. }
  4405. {
  4406. auto res = cli.Get("/unknown");
  4407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4408. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4409. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4410. }
  4411. }
  4412. TEST(ExceptionTest, WithExceptionHandler) {
  4413. Server svr;
  4414. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4415. std::exception_ptr ep) {
  4416. EXPECT_FALSE(ep == nullptr);
  4417. try {
  4418. std::rethrow_exception(ep);
  4419. } catch (std::exception &e) {
  4420. EXPECT_EQ("abc", std::string(e.what()));
  4421. } catch (...) {}
  4422. res.status = StatusCode::InternalServerError_500;
  4423. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4424. "text/html"); // <= Content-Length still 13 at this point
  4425. });
  4426. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4427. res.set_content("Hello World!\n", "text/plain");
  4428. throw std::runtime_error("abc");
  4429. });
  4430. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4431. auto se = detail::scope_exit([&] {
  4432. svr.stop();
  4433. thread.join();
  4434. ASSERT_FALSE(svr.is_running());
  4435. });
  4436. svr.wait_until_ready();
  4437. for (size_t i = 0; i < 10; i++) {
  4438. Client cli(HOST, PORT);
  4439. for (size_t j = 0; j < 100; j++) {
  4440. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4442. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4443. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4444. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4445. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4446. }
  4447. cli.set_keep_alive(true);
  4448. for (size_t j = 0; j < 100; j++) {
  4449. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4451. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4452. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4453. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4454. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4455. }
  4456. }
  4457. }
  4458. TEST(ExceptionTest, AndErrorHandler) {
  4459. Server svr;
  4460. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4461. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4462. });
  4463. svr.set_exception_handler(
  4464. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4465. EXPECT_FALSE(ep == nullptr);
  4466. try {
  4467. std::rethrow_exception(ep);
  4468. } catch (std::exception &e) {
  4469. res.set_content(e.what(), "text/html");
  4470. } catch (...) {}
  4471. res.status = StatusCode::InternalServerError_500;
  4472. });
  4473. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4474. throw std::runtime_error("EXCEPTION");
  4475. });
  4476. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4477. res.set_content("ERROR", "text/html");
  4478. res.status = StatusCode::InternalServerError_500;
  4479. });
  4480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4481. auto se = detail::scope_exit([&] {
  4482. svr.stop();
  4483. thread.join();
  4484. ASSERT_FALSE(svr.is_running());
  4485. });
  4486. svr.wait_until_ready();
  4487. Client cli(HOST, PORT);
  4488. {
  4489. auto res = cli.Get("/exception");
  4490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4491. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4492. EXPECT_EQ("EXCEPTION", res->body);
  4493. }
  4494. {
  4495. auto res = cli.Get("/error");
  4496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4497. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4498. EXPECT_EQ("ERROR", res->body);
  4499. }
  4500. {
  4501. auto res = cli.Get("/invalid");
  4502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4504. EXPECT_EQ("NOT_FOUND", res->body);
  4505. }
  4506. }
  4507. #endif
  4508. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4509. // process_request() wraps only routing() in a try/catch, so an exception from
  4510. // any other user callback used to unwind into the task queue - which does not
  4511. // catch - and terminate the process. Each test below runs the server on a
  4512. // single worker thread: a guard that catches the exception but still loses the
  4513. // thread would otherwise be hidden by a spare worker serving the follow-up
  4514. // request. Note that a regression here aborts the whole test binary rather
  4515. // than failing one test.
  4516. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4517. Server svr;
  4518. svr.new_task_queue = [] { return new ThreadPool(1); };
  4519. std::atomic<int> reported{0};
  4520. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4521. if (err == Error::UserCallbackException) { reported++; }
  4522. });
  4523. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4524. res.set_content_provider(
  4525. 1024, "text/plain",
  4526. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4527. sink.write("hello", 5);
  4528. throw std::runtime_error("from the content provider");
  4529. });
  4530. });
  4531. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4532. res.set_content("ok", "text/plain");
  4533. });
  4534. auto port = svr.bind_to_any_port(HOST);
  4535. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4536. auto se = detail::scope_exit([&] {
  4537. svr.stop();
  4538. listen_thread.join();
  4539. ASSERT_FALSE(svr.is_running());
  4540. });
  4541. svr.wait_until_ready();
  4542. {
  4543. Client cli(HOST, port);
  4544. cli.set_read_timeout(5, 0);
  4545. EXPECT_FALSE(cli.Get("/throw"));
  4546. }
  4547. EXPECT_TRUE(svr.is_running());
  4548. EXPECT_EQ(1, reported.load());
  4549. // A request on a fresh connection is still served.
  4550. {
  4551. Client cli(HOST, port);
  4552. auto res = cli.Get("/ok");
  4553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4554. EXPECT_EQ(StatusCode::OK_200, res->status);
  4555. EXPECT_EQ("ok", res->body);
  4556. }
  4557. }
  4558. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4559. Server svr;
  4560. svr.new_task_queue = [] { return new ThreadPool(1); };
  4561. std::atomic<bool> should_throw{true};
  4562. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4563. res.set_content("hi", "text/plain");
  4564. });
  4565. svr.set_post_routing_handler(
  4566. [&](const Request & /*req*/, Response & /*res*/) {
  4567. if (should_throw) {
  4568. throw std::runtime_error("from the post-routing handler");
  4569. }
  4570. });
  4571. auto port = svr.bind_to_any_port(HOST);
  4572. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4573. auto se = detail::scope_exit([&] {
  4574. svr.stop();
  4575. listen_thread.join();
  4576. ASSERT_FALSE(svr.is_running());
  4577. });
  4578. svr.wait_until_ready();
  4579. {
  4580. Client cli(HOST, port);
  4581. cli.set_read_timeout(5, 0);
  4582. EXPECT_FALSE(cli.Get("/hi"));
  4583. }
  4584. EXPECT_TRUE(svr.is_running());
  4585. should_throw = false;
  4586. {
  4587. Client cli(HOST, port);
  4588. auto res = cli.Get("/hi");
  4589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4590. EXPECT_EQ(StatusCode::OK_200, res->status);
  4591. EXPECT_EQ("hi", res->body);
  4592. }
  4593. }
  4594. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4595. // The guard reports the caught exception through the error logger, which is
  4596. // a user callback too. A logger that throws has to be contained as well, or
  4597. // the process would terminate from inside the catch.
  4598. Server svr;
  4599. svr.new_task_queue = [] { return new ThreadPool(1); };
  4600. std::atomic<int> reported{0};
  4601. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4602. if (err == Error::UserCallbackException) {
  4603. reported++;
  4604. throw std::runtime_error("from the error logger");
  4605. }
  4606. });
  4607. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4608. res.set_content_provider(
  4609. 1024, "text/plain",
  4610. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4611. sink.write("hello", 5);
  4612. throw std::runtime_error("from the content provider");
  4613. });
  4614. });
  4615. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4616. res.set_content("ok", "text/plain");
  4617. });
  4618. auto port = svr.bind_to_any_port(HOST);
  4619. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4620. auto se = detail::scope_exit([&] {
  4621. svr.stop();
  4622. listen_thread.join();
  4623. ASSERT_FALSE(svr.is_running());
  4624. });
  4625. svr.wait_until_ready();
  4626. {
  4627. Client cli(HOST, port);
  4628. cli.set_read_timeout(5, 0);
  4629. EXPECT_FALSE(cli.Get("/throw"));
  4630. }
  4631. EXPECT_TRUE(svr.is_running());
  4632. EXPECT_EQ(1, reported.load());
  4633. {
  4634. Client cli(HOST, port);
  4635. auto res = cli.Get("/ok");
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. EXPECT_EQ("ok", res->body);
  4639. }
  4640. }
  4641. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4642. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4643. // so the exception unwinds through the ws::WebSocket object on its way to
  4644. // the guard. None of the HTTP cases above cross that.
  4645. Server svr;
  4646. svr.new_task_queue = [] { return new ThreadPool(1); };
  4647. std::atomic<int> reported{0};
  4648. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4649. if (err == Error::UserCallbackException) { reported++; }
  4650. });
  4651. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4652. throw std::runtime_error("from the WebSocket handler");
  4653. });
  4654. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4655. res.set_content("ok", "text/plain");
  4656. });
  4657. auto port = svr.bind_to_any_port(HOST);
  4658. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4659. auto se = detail::scope_exit([&] {
  4660. svr.stop();
  4661. listen_thread.join();
  4662. ASSERT_FALSE(svr.is_running());
  4663. });
  4664. svr.wait_until_ready();
  4665. {
  4666. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4667. "/ws");
  4668. auto res = client.connect();
  4669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4670. // The server dropped the connection instead of dying.
  4671. std::string msg;
  4672. EXPECT_FALSE(client.read(msg));
  4673. client.close();
  4674. }
  4675. EXPECT_TRUE(svr.is_running());
  4676. EXPECT_EQ(1, reported.load());
  4677. {
  4678. Client cli(HOST, port);
  4679. auto res = cli.Get("/ok");
  4680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4681. EXPECT_EQ(StatusCode::OK_200, res->status);
  4682. EXPECT_EQ("ok", res->body);
  4683. }
  4684. }
  4685. #ifdef CPPHTTPLIB_SSL_ENABLED
  4686. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4687. // SSLServer::process_and_close_socket() is a separate overload with its own
  4688. // guard, so it is exercised on its own.
  4689. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4690. ASSERT_TRUE(svr.is_valid());
  4691. svr.new_task_queue = [] { return new ThreadPool(1); };
  4692. std::atomic<int> reported{0};
  4693. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4694. if (err == Error::UserCallbackException) { reported++; }
  4695. });
  4696. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4697. res.set_content_provider(
  4698. 1024, "text/plain",
  4699. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4700. sink.write("hello", 5);
  4701. throw std::runtime_error("from the content provider");
  4702. });
  4703. });
  4704. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4705. res.set_content("ok", "text/plain");
  4706. });
  4707. auto port = svr.bind_to_any_port(HOST);
  4708. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4709. auto se = detail::scope_exit([&] {
  4710. svr.stop();
  4711. listen_thread.join();
  4712. ASSERT_FALSE(svr.is_running());
  4713. });
  4714. svr.wait_until_ready();
  4715. {
  4716. SSLClient cli(HOST, port);
  4717. cli.enable_server_certificate_verification(false);
  4718. cli.set_read_timeout(5, 0);
  4719. EXPECT_FALSE(cli.Get("/throw"));
  4720. }
  4721. EXPECT_TRUE(svr.is_running());
  4722. EXPECT_EQ(1, reported.load());
  4723. {
  4724. SSLClient cli(HOST, port);
  4725. cli.enable_server_certificate_verification(false);
  4726. auto res = cli.Get("/ok");
  4727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4728. EXPECT_EQ(StatusCode::OK_200, res->status);
  4729. EXPECT_EQ("ok", res->body);
  4730. }
  4731. }
  4732. #endif
  4733. #endif
  4734. TEST(NoContentTest, ContentLength) {
  4735. Server svr;
  4736. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4737. res.status = StatusCode::NoContent_204;
  4738. });
  4739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4740. auto se = detail::scope_exit([&] {
  4741. svr.stop();
  4742. thread.join();
  4743. ASSERT_FALSE(svr.is_running());
  4744. });
  4745. svr.wait_until_ready();
  4746. {
  4747. Client cli(HOST, PORT);
  4748. auto res = cli.Get("/hi");
  4749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4750. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4751. // RFC 9110 8.6: none in a 204 response
  4752. EXPECT_FALSE(res->has_header("Content-Length"));
  4753. }
  4754. }
  4755. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4756. Server svr;
  4757. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4758. res.set_header("Content-Length", "5");
  4759. res.set_content("hello world", "text/plain");
  4760. });
  4761. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4762. // A body that reads as the last chunk, were it taken as chunked
  4763. res.set_header("Transfer-Encoding", "chunked");
  4764. res.set_content("0\r\n\r\n", "text/plain");
  4765. });
  4766. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4767. res.set_header("Content-Length", "2");
  4768. res.set_content_provider(5, "text/plain",
  4769. [](size_t offset, size_t length, DataSink &sink) {
  4770. sink.write(&"hello"[offset], length);
  4771. return true;
  4772. });
  4773. });
  4774. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4775. res.set_header("Content-Length", "1234");
  4776. });
  4777. thread t = thread([&] { svr.listen(HOST, PORT); });
  4778. auto se = detail::scope_exit([&] {
  4779. svr.stop();
  4780. t.join();
  4781. ASSERT_FALSE(svr.is_running());
  4782. });
  4783. svr.wait_until_ready();
  4784. Client cli(HOST, PORT);
  4785. cli.set_read_timeout(1, 0);
  4786. auto expect_body = [&](const Result &res, const std::string &body) {
  4787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4788. EXPECT_EQ(body, res->body);
  4789. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4790. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4791. };
  4792. Headers identity{{"Accept-Encoding", ""}};
  4793. expect_body(cli.Get("/body", identity), "hello world");
  4794. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4795. expect_body(cli.Get("/body",
  4796. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4797. "he");
  4798. expect_body(cli.Get("/provider", identity), "hello");
  4799. expect_body(cli.Get("/empty", identity), "");
  4800. // A HEAD response may give the length of the body a GET would get.
  4801. auto res = cli.Head("/empty");
  4802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4803. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4804. }
  4805. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4806. Server svr;
  4807. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4808. res.set_content("short", "text/plain");
  4809. });
  4810. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4811. res.body += " with a footer";
  4812. res.set_header("Transfer-Encoding", "chunked");
  4813. });
  4814. thread t = thread([&] { svr.listen(HOST, PORT); });
  4815. auto se = detail::scope_exit([&] {
  4816. svr.stop();
  4817. t.join();
  4818. ASSERT_FALSE(svr.is_running());
  4819. });
  4820. svr.wait_until_ready();
  4821. Client cli(HOST, PORT);
  4822. cli.set_read_timeout(1, 0);
  4823. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4825. EXPECT_EQ("short with a footer", res->body);
  4826. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4827. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4828. }
  4829. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4830. Server svr;
  4831. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4832. res.set_header("Content-Length", "3");
  4833. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4834. sink.write("abc", 3);
  4835. sink.done();
  4836. return true;
  4837. });
  4838. });
  4839. thread t = thread([&] { svr.listen(HOST, PORT); });
  4840. auto se = detail::scope_exit([&] {
  4841. svr.stop();
  4842. t.join();
  4843. ASSERT_FALSE(svr.is_running());
  4844. });
  4845. svr.wait_until_ready();
  4846. Client cli(HOST, PORT);
  4847. cli.set_keep_alive(true);
  4848. auto res = cli.Get("/");
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. EXPECT_EQ("abc", res->body);
  4851. EXPECT_FALSE(res->has_header("Content-Length"));
  4852. EXPECT_EQ("close", res->get_header_value("Connection"));
  4853. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4854. // No body to delimit
  4855. auto head = cli.Head("/");
  4856. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4857. EXPECT_FALSE(head->has_header("Connection"));
  4858. }
  4859. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4860. #ifdef CPPHTTPLIB_SSL_ENABLED
  4861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4862. ASSERT_TRUE(svr.is_valid());
  4863. #else
  4864. Server svr;
  4865. #endif
  4866. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4867. if (req.path == "/routing_handler") {
  4868. res.set_header("PRE_ROUTING", "on");
  4869. res.set_content("Routing Handler", "text/plain");
  4870. return httplib::Server::HandlerResponse::Handled;
  4871. }
  4872. return httplib::Server::HandlerResponse::Unhandled;
  4873. });
  4874. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4875. res.set_content("Error", "text/html");
  4876. });
  4877. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4878. if (req.path == "/routing_handler") {
  4879. res.set_header("POST_ROUTING", "on");
  4880. }
  4881. });
  4882. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4883. res.set_content("Hello World!\n", "text/plain");
  4884. });
  4885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4886. auto se = detail::scope_exit([&] {
  4887. svr.stop();
  4888. thread.join();
  4889. ASSERT_FALSE(svr.is_running());
  4890. });
  4891. svr.wait_until_ready();
  4892. {
  4893. #ifdef CPPHTTPLIB_SSL_ENABLED
  4894. SSLClient cli(HOST, PORT);
  4895. cli.enable_server_certificate_verification(false);
  4896. #else
  4897. Client cli(HOST, PORT);
  4898. #endif
  4899. auto res = cli.Get("/routing_handler");
  4900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4901. EXPECT_EQ(StatusCode::OK_200, res->status);
  4902. EXPECT_EQ("Routing Handler", res->body);
  4903. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4904. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4905. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4906. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4907. }
  4908. {
  4909. #ifdef CPPHTTPLIB_SSL_ENABLED
  4910. SSLClient cli(HOST, PORT);
  4911. cli.enable_server_certificate_verification(false);
  4912. #else
  4913. Client cli(HOST, PORT);
  4914. #endif
  4915. auto res = cli.Get("/hi");
  4916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4917. EXPECT_EQ(StatusCode::OK_200, res->status);
  4918. EXPECT_EQ("Hello World!\n", res->body);
  4919. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4920. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4921. }
  4922. {
  4923. #ifdef CPPHTTPLIB_SSL_ENABLED
  4924. SSLClient cli(HOST, PORT);
  4925. cli.enable_server_certificate_verification(false);
  4926. #else
  4927. Client cli(HOST, PORT);
  4928. #endif
  4929. auto res = cli.Get("/aaa");
  4930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4931. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4932. EXPECT_EQ("Error", res->body);
  4933. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4934. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4935. }
  4936. }
  4937. TEST(RequestHandlerTest, PreRequestHandler) {
  4938. auto route_path = "/user/:user";
  4939. Server svr;
  4940. svr.Get("/hi", [](const Request &, Response &res) {
  4941. res.set_content("hi", "text/plain");
  4942. });
  4943. svr.Get(route_path, [](const Request &req, Response &res) {
  4944. res.set_content(req.path_params.at("user"), "text/plain");
  4945. });
  4946. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4947. if (req.matched_route == route_path) {
  4948. auto user = req.path_params.at("user");
  4949. if (user != "john") {
  4950. res.status = StatusCode::Forbidden_403;
  4951. res.set_content("error", "text/html");
  4952. return Server::HandlerResponse::Handled;
  4953. }
  4954. }
  4955. return Server::HandlerResponse::Unhandled;
  4956. });
  4957. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4958. auto se = detail::scope_exit([&] {
  4959. svr.stop();
  4960. thread.join();
  4961. ASSERT_FALSE(svr.is_running());
  4962. });
  4963. svr.wait_until_ready();
  4964. Client cli(HOST, PORT);
  4965. {
  4966. auto res = cli.Get("/hi");
  4967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4968. EXPECT_EQ(StatusCode::OK_200, res->status);
  4969. EXPECT_EQ("hi", res->body);
  4970. }
  4971. {
  4972. auto res = cli.Get("/user/john");
  4973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4974. EXPECT_EQ(StatusCode::OK_200, res->status);
  4975. EXPECT_EQ("john", res->body);
  4976. }
  4977. {
  4978. auto res = cli.Get("/user/invalid-user");
  4979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4980. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4981. EXPECT_EQ("error", res->body);
  4982. }
  4983. }
  4984. // The pre-request handler must run before the request body is read, so a
  4985. // rejected request never forces the server to buffer a (potentially large)
  4986. // body. Here the posted body is larger than the payload limit: if the body
  4987. // were read first the server would answer 413, but because the pre-request
  4988. // handler runs first it answers 403 and the body is never read.
  4989. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4990. Server svr;
  4991. svr.set_payload_max_length(8);
  4992. auto handler_ran = false;
  4993. svr.Post("/reject", [&](const Request &req, Response &res) {
  4994. handler_ran = true;
  4995. res.set_content(req.body, "text/plain");
  4996. });
  4997. svr.Post("/accept", [](const Request &req, Response &res) {
  4998. res.set_content(req.body, "text/plain");
  4999. });
  5000. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5001. if (req.matched_route == "/reject") {
  5002. res.status = StatusCode::Forbidden_403;
  5003. res.set_content("denied", "text/plain");
  5004. return Server::HandlerResponse::Handled;
  5005. }
  5006. return Server::HandlerResponse::Unhandled;
  5007. });
  5008. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5009. auto se = detail::scope_exit([&] {
  5010. svr.stop();
  5011. thread.join();
  5012. ASSERT_FALSE(svr.is_running());
  5013. });
  5014. svr.wait_until_ready();
  5015. Client cli(HOST, PORT);
  5016. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5017. // rejects with 403 before the body is read, so 413 is never reached.
  5018. {
  5019. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5021. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5022. EXPECT_EQ("denied", res->body);
  5023. EXPECT_FALSE(handler_ran);
  5024. }
  5025. // An approved route still reads the body and enforces the payload limit.
  5026. {
  5027. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5029. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5030. }
  5031. }
  5032. TEST(UserDataTest, BasicOperations) {
  5033. httplib::UserData ud;
  5034. // Initially empty
  5035. EXPECT_FALSE(ud.has("key"));
  5036. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5037. // set and get
  5038. ud.set("key", 42);
  5039. EXPECT_TRUE(ud.has("key"));
  5040. auto *p = ud.get<int>("key");
  5041. ASSERT_NE(nullptr, p);
  5042. EXPECT_EQ(42, *p);
  5043. // Type mismatch → nullptr
  5044. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5045. // Overwrite with different type
  5046. ud.set("key", std::string("hello"));
  5047. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5048. auto *s = ud.get<std::string>("key");
  5049. ASSERT_NE(nullptr, s);
  5050. EXPECT_EQ("hello", *s);
  5051. // erase
  5052. ud.erase("key");
  5053. EXPECT_FALSE(ud.has("key"));
  5054. // clear
  5055. ud.set("a", 1);
  5056. ud.set("b", 2);
  5057. ud.clear();
  5058. EXPECT_FALSE(ud.has("a"));
  5059. EXPECT_FALSE(ud.has("b"));
  5060. }
  5061. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5062. struct AuthCtx {
  5063. std::string user_id;
  5064. };
  5065. Server svr;
  5066. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5067. res.user_data.set("auth", AuthCtx{"alice"});
  5068. return Server::HandlerResponse::Unhandled;
  5069. });
  5070. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5071. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5072. ASSERT_NE(nullptr, ctx);
  5073. res.set_content("Hello " + ctx->user_id, "text/plain");
  5074. });
  5075. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5076. auto se = detail::scope_exit([&] {
  5077. svr.stop();
  5078. thread.join();
  5079. ASSERT_FALSE(svr.is_running());
  5080. });
  5081. svr.wait_until_ready();
  5082. Client cli(HOST, PORT);
  5083. auto res = cli.Get("/me");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. EXPECT_EQ(StatusCode::OK_200, res->status);
  5086. EXPECT_EQ("Hello alice", res->body);
  5087. }
  5088. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5089. struct RoleCtx {
  5090. std::string role;
  5091. };
  5092. Server svr;
  5093. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5094. res.user_data.set("role", RoleCtx{"admin"});
  5095. return Server::HandlerResponse::Unhandled;
  5096. });
  5097. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5098. auto *ctx = res.user_data.get<RoleCtx>("role");
  5099. ASSERT_NE(nullptr, ctx);
  5100. res.set_content(ctx->role, "text/plain");
  5101. });
  5102. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5103. auto se = detail::scope_exit([&] {
  5104. svr.stop();
  5105. thread.join();
  5106. ASSERT_FALSE(svr.is_running());
  5107. });
  5108. svr.wait_until_ready();
  5109. Client cli(HOST, PORT);
  5110. auto res = cli.Get("/role");
  5111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5112. EXPECT_EQ(StatusCode::OK_200, res->status);
  5113. EXPECT_EQ("admin", res->body);
  5114. }
  5115. TEST(InvalidFormatTest, StatusCode) {
  5116. Server svr;
  5117. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5118. res.set_content("Hello World!\n", "text/plain");
  5119. res.status = 9999; // Status should be a three-digit code...
  5120. });
  5121. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5122. auto se = detail::scope_exit([&] {
  5123. svr.stop();
  5124. thread.join();
  5125. ASSERT_FALSE(svr.is_running());
  5126. });
  5127. svr.wait_until_ready();
  5128. {
  5129. Client cli(HOST, PORT);
  5130. auto res = cli.Get("/hi");
  5131. ASSERT_FALSE(res);
  5132. }
  5133. }
  5134. TEST(URLFragmentTest, WithFragment) {
  5135. Server svr;
  5136. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5137. EXPECT_TRUE(req.target == "/hi");
  5138. });
  5139. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5140. auto se = detail::scope_exit([&] {
  5141. svr.stop();
  5142. thread.join();
  5143. ASSERT_FALSE(svr.is_running());
  5144. });
  5145. svr.wait_until_ready();
  5146. {
  5147. Client cli(HOST, PORT);
  5148. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5149. EXPECT_TRUE(res);
  5150. EXPECT_EQ(StatusCode::OK_200, res->status);
  5151. res = cli.Get("/hi%23key1=val1=key2=val2");
  5152. EXPECT_TRUE(res);
  5153. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5154. }
  5155. }
  5156. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5157. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5158. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5159. Server svr;
  5160. std::vector<std::string> targets;
  5161. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5162. targets.push_back(req.target);
  5163. });
  5164. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5165. auto se = detail::scope_exit([&] {
  5166. svr.stop();
  5167. thread.join();
  5168. ASSERT_FALSE(svr.is_running());
  5169. });
  5170. svr.wait_until_ready();
  5171. Client cli(HOST, PORT);
  5172. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5173. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5174. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5175. // A '?' after the '#' belongs to the fragment, not to the query.
  5176. Request req;
  5177. req.method = "GET";
  5178. req.path = "/hi#f?x=1";
  5179. req.params.emplace("a", "1");
  5180. Response res;
  5181. auto error = Error::Success;
  5182. EXPECT_TRUE(cli.send(req, res, error));
  5183. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5184. "/hi?a=1"}),
  5185. targets);
  5186. }
  5187. TEST(HeaderWriter, SetHeaderWriter) {
  5188. Server svr;
  5189. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5190. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5191. return detail::write_headers(strm, hdrs);
  5192. });
  5193. svr.Get("/hi", [](const Request &req, Response &res) {
  5194. auto it = req.headers.find("CustomClientHeader");
  5195. EXPECT_TRUE(it != req.headers.end());
  5196. EXPECT_EQ(it->second, "CustomClientValue");
  5197. res.set_content("Hello World!\n", "text/plain");
  5198. });
  5199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5200. auto se = detail::scope_exit([&] {
  5201. svr.stop();
  5202. thread.join();
  5203. ASSERT_FALSE(svr.is_running());
  5204. });
  5205. svr.wait_until_ready();
  5206. {
  5207. Client cli(HOST, PORT);
  5208. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5209. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5210. return detail::write_headers(strm, hdrs);
  5211. });
  5212. auto res = cli.Get("/hi");
  5213. EXPECT_TRUE(res);
  5214. EXPECT_EQ(StatusCode::OK_200, res->status);
  5215. auto it = res->headers.find("CustomServerHeader");
  5216. EXPECT_TRUE(it != res->headers.end());
  5217. EXPECT_EQ(it->second, "CustomServerValue");
  5218. }
  5219. }
  5220. class ServerTest : public ::testing::Test {
  5221. protected:
  5222. ServerTest()
  5223. : cli_(HOST, PORT)
  5224. #ifdef CPPHTTPLIB_SSL_ENABLED
  5225. ,
  5226. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5227. #endif
  5228. {
  5229. #ifdef CPPHTTPLIB_SSL_ENABLED
  5230. cli_.enable_server_certificate_verification(false);
  5231. #endif
  5232. // Allow LARGE_DATA (100MB) responses
  5233. cli_.set_payload_max_length(200 * 1024 * 1024);
  5234. }
  5235. virtual void SetUp() {
  5236. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5237. svr_.set_payload_max_length(200 * 1024 * 1024);
  5238. svr_.set_mount_point("/", "./www");
  5239. svr_.set_mount_point("/mount", "./www2");
  5240. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5241. svr_.Get("/hi",
  5242. [&](const Request & /*req*/, Response &res) {
  5243. res.set_content("Hello World!", "text/plain");
  5244. })
  5245. .Get("/file_content",
  5246. [&](const Request & /*req*/, Response &res) {
  5247. res.set_file_content("./www/dir/test.html");
  5248. })
  5249. .Get("/file_content_with_content_type",
  5250. [&](const Request & /*req*/, Response &res) {
  5251. res.set_file_content("./www/file", "text/plain");
  5252. })
  5253. .Get("/invalid_file_content",
  5254. [&](const Request & /*req*/, Response &res) {
  5255. res.set_file_content("./www/dir/invalid_file_path");
  5256. })
  5257. .Get("/http_response_splitting",
  5258. [&](const Request & /*req*/, Response &res) {
  5259. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5260. EXPECT_EQ(0U, res.headers.size());
  5261. EXPECT_FALSE(res.has_header("a"));
  5262. res.set_header("a", "1\nSet-Cookie: a=1");
  5263. EXPECT_EQ(0U, res.headers.size());
  5264. EXPECT_FALSE(res.has_header("a"));
  5265. res.set_header("a", "1\rSet-Cookie: a=1");
  5266. EXPECT_EQ(0U, res.headers.size());
  5267. EXPECT_FALSE(res.has_header("a"));
  5268. res.set_header("a\r\nb", "0");
  5269. EXPECT_EQ(0U, res.headers.size());
  5270. EXPECT_FALSE(res.has_header("a"));
  5271. res.set_header("a\rb", "0");
  5272. EXPECT_EQ(0U, res.headers.size());
  5273. EXPECT_FALSE(res.has_header("a"));
  5274. res.set_header("a\nb", "0");
  5275. EXPECT_EQ(0U, res.headers.size());
  5276. EXPECT_FALSE(res.has_header("a"));
  5277. res.set_redirect("1\r\nSet-Cookie: a=1");
  5278. EXPECT_EQ(0U, res.headers.size());
  5279. EXPECT_FALSE(res.has_header("Location"));
  5280. })
  5281. .Get("/slow",
  5282. [&](const Request & /*req*/, Response &res) {
  5283. std::this_thread::sleep_for(std::chrono::seconds(4));
  5284. res.set_content("slow", "text/plain");
  5285. })
  5286. #if 0
  5287. .Post("/slowpost",
  5288. [&](const Request & /*req*/, Response &res) {
  5289. std::this_thread::sleep_for(std::chrono::seconds(2));
  5290. res.set_content("slow", "text/plain");
  5291. })
  5292. #endif
  5293. .Get("/remote_addr",
  5294. [&](const Request &req, Response &res) {
  5295. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5296. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5297. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5298. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5299. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5300. #endif
  5301. res.set_content(req.remote_addr, "text/plain");
  5302. })
  5303. .Get("/local_addr",
  5304. [&](const Request &req, Response &res) {
  5305. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5306. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5307. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5308. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5309. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5310. #endif
  5311. auto local_addr = req.local_addr;
  5312. auto local_port = std::to_string(req.local_port);
  5313. res.set_content(local_addr.append(":").append(local_port),
  5314. "text/plain");
  5315. })
  5316. .Get("/endwith%",
  5317. [&](const Request & /*req*/, Response &res) {
  5318. res.set_content("Hello World!", "text/plain");
  5319. })
  5320. .Get("/a\\+\\+b",
  5321. [&](const Request &req, Response &res) {
  5322. ASSERT_TRUE(req.has_param("a +b"));
  5323. auto val = req.get_param_value("a +b");
  5324. res.set_content(val, "text/plain");
  5325. })
  5326. .Get("/", [&](const Request & /*req*/,
  5327. Response &res) { res.set_redirect("/hi"); })
  5328. .Post("/1",
  5329. [](const Request & /*req*/, Response &res) {
  5330. res.set_redirect("/2", StatusCode::SeeOther_303);
  5331. })
  5332. .Get("/2",
  5333. [](const Request & /*req*/, Response &res) {
  5334. res.set_content("redirected.", "text/plain");
  5335. res.status = StatusCode::OK_200;
  5336. })
  5337. .Post("/person",
  5338. [&](const Request &req, Response &res) {
  5339. if (req.has_param("name") && req.has_param("note")) {
  5340. persons_[req.get_param_value("name")] =
  5341. req.get_param_value("note");
  5342. } else {
  5343. res.status = StatusCode::BadRequest_400;
  5344. }
  5345. })
  5346. .Put("/person",
  5347. [&](const Request &req, Response &res) {
  5348. if (req.has_param("name") && req.has_param("note")) {
  5349. persons_[req.get_param_value("name")] =
  5350. req.get_param_value("note");
  5351. } else {
  5352. res.status = StatusCode::BadRequest_400;
  5353. }
  5354. })
  5355. .Get("/person/(.*)",
  5356. [&](const Request &req, Response &res) {
  5357. string name = req.matches[1];
  5358. if (persons_.find(name) != persons_.end()) {
  5359. auto note = persons_[name];
  5360. res.set_content(note, "text/plain");
  5361. } else {
  5362. res.status = StatusCode::NotFound_404;
  5363. }
  5364. })
  5365. .Delete("/person",
  5366. [&](const Request &req, Response &res) {
  5367. if (req.has_param("name")) {
  5368. string name = req.get_param_value("name");
  5369. if (persons_.find(name) != persons_.end()) {
  5370. persons_.erase(name);
  5371. res.set_content("DELETED", "text/plain");
  5372. } else {
  5373. res.status = StatusCode::NotFound_404;
  5374. }
  5375. } else {
  5376. res.status = StatusCode::BadRequest_400;
  5377. }
  5378. })
  5379. .Post("/x-www-form-urlencoded-json",
  5380. [&](const Request &req, Response &res) {
  5381. auto json = req.get_param_value("json");
  5382. ASSERT_EQ(JSON_DATA, json);
  5383. res.set_content(json, "appliation/json");
  5384. res.status = StatusCode::OK_200;
  5385. })
  5386. .Get("/streamed-chunked",
  5387. [&](const Request & /*req*/, Response &res) {
  5388. res.set_chunked_content_provider(
  5389. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5390. sink.os << "123";
  5391. sink.os << "456";
  5392. sink.os << "789";
  5393. sink.done();
  5394. return true;
  5395. });
  5396. })
  5397. .Get("/streamed-chunked-with-prohibited-trailer",
  5398. [&](const Request & /*req*/, Response &res) {
  5399. auto i = new int(0);
  5400. // Declare both a prohibited trailer (Content-Length) and an
  5401. // allowed one
  5402. res.set_header("Trailer", "Content-Length, X-Allowed");
  5403. res.set_chunked_content_provider(
  5404. "text/plain",
  5405. [i](size_t /*offset*/, DataSink &sink) {
  5406. switch (*i) {
  5407. case 0: sink.os << "123"; break;
  5408. case 1: sink.os << "456"; break;
  5409. case 2: sink.os << "789"; break;
  5410. case 3: {
  5411. sink.done_with_trailer(
  5412. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5413. } break;
  5414. }
  5415. (*i)++;
  5416. return true;
  5417. },
  5418. [i](bool success) {
  5419. EXPECT_TRUE(success);
  5420. delete i;
  5421. });
  5422. })
  5423. .Get("/streamed-chunked2",
  5424. [&](const Request & /*req*/, Response &res) {
  5425. auto i = new int(0);
  5426. res.set_chunked_content_provider(
  5427. "text/plain",
  5428. [i](size_t /*offset*/, DataSink &sink) {
  5429. switch (*i) {
  5430. case 0: sink.os << "123"; break;
  5431. case 1: sink.os << "456"; break;
  5432. case 2: sink.os << "789"; break;
  5433. case 3: sink.done(); break;
  5434. }
  5435. (*i)++;
  5436. return true;
  5437. },
  5438. [i](bool success) {
  5439. EXPECT_TRUE(success);
  5440. delete i;
  5441. });
  5442. })
  5443. .Get("/streamed-chunked-with-trailer",
  5444. [&](const Request & /*req*/, Response &res) {
  5445. auto i = new int(0);
  5446. res.set_header("Trailer", "Dummy1, Dummy2");
  5447. res.set_chunked_content_provider(
  5448. "text/plain",
  5449. [i](size_t /*offset*/, DataSink &sink) {
  5450. switch (*i) {
  5451. case 0: sink.os << "123"; break;
  5452. case 1: sink.os << "456"; break;
  5453. case 2: sink.os << "789"; break;
  5454. case 3: {
  5455. sink.done_with_trailer(
  5456. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5457. } break;
  5458. }
  5459. (*i)++;
  5460. return true;
  5461. },
  5462. [i](bool success) {
  5463. EXPECT_TRUE(success);
  5464. delete i;
  5465. });
  5466. })
  5467. .Get("/streamed",
  5468. [&](const Request & /*req*/, Response &res) {
  5469. res.set_content_provider(
  5470. 6, "text/plain",
  5471. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5472. sink.os << (offset < 3 ? "a" : "b");
  5473. return true;
  5474. });
  5475. })
  5476. .Get("/streamed-without-length",
  5477. [&](const Request & /*req*/, Response &res) {
  5478. auto data = new std::string("abcdefg");
  5479. res.set_content_provider(
  5480. "text/plain",
  5481. [data](size_t offset, DataSink &sink) {
  5482. if (offset < data->size()) {
  5483. sink.os << data->substr(offset);
  5484. }
  5485. sink.done();
  5486. return true;
  5487. },
  5488. [data](bool success) {
  5489. EXPECT_TRUE(success);
  5490. delete data;
  5491. });
  5492. })
  5493. .Get("/streamed-with-range",
  5494. [&](const Request &req, Response &res) {
  5495. auto data = new std::string("abcdefg");
  5496. // An explicit status keeps the server from picking the 206 it
  5497. // would otherwise choose for a ranged request, so the response
  5498. // is not a partial representation.
  5499. auto status = req.get_param_value("status");
  5500. if (status == "200") {
  5501. res.status = StatusCode::OK_200;
  5502. } else if (status == "403") {
  5503. res.status = StatusCode::Forbidden_403;
  5504. }
  5505. res.set_content_provider(
  5506. data->size(), "text/plain",
  5507. [data](size_t offset, size_t length, DataSink &sink) {
  5508. size_t DATA_CHUNK_SIZE = 4;
  5509. const auto &d = *data;
  5510. auto out_len =
  5511. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5512. auto ret =
  5513. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5514. EXPECT_TRUE(ret);
  5515. return true;
  5516. },
  5517. [data, &req](bool success) {
  5518. EXPECT_EQ(success, !req.has_param("error"));
  5519. delete data;
  5520. });
  5521. })
  5522. .Get("/streamed-cancel",
  5523. [&](const Request & /*req*/, Response &res) {
  5524. res.set_content_provider(
  5525. size_t(-1), "text/plain",
  5526. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5527. sink.os << "data_chunk";
  5528. return true;
  5529. });
  5530. })
  5531. .Get("/regex-with-delimiter",
  5532. [&](const Request &req, Response & /*res*/) {
  5533. ASSERT_TRUE(req.has_param("key"));
  5534. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5535. })
  5536. .Get("/with-range",
  5537. [&](const Request & /*req*/, Response &res) {
  5538. res.set_content("abcdefg", "text/plain");
  5539. })
  5540. .Get("/test-start-time",
  5541. [&](const Request &req, Response & /*res*/) {
  5542. EXPECT_NE(req.start_time_,
  5543. std::chrono::steady_clock::time_point::min());
  5544. })
  5545. .Get("/with-range-customized-response",
  5546. [&](const Request & /*req*/, Response &res) {
  5547. res.status = StatusCode::BadRequest_400;
  5548. res.set_content(JSON_DATA, "application/json");
  5549. })
  5550. .Post("/chunked",
  5551. [&](const Request &req, Response & /*res*/) {
  5552. EXPECT_EQ(req.body, "dechunked post body");
  5553. })
  5554. .Post("/large-chunked",
  5555. [&](const Request &req, Response & /*res*/) {
  5556. std::string expected(6 * 30 * 1024u, 'a');
  5557. EXPECT_EQ(req.body, expected);
  5558. })
  5559. .Post("/multipart",
  5560. [&](const Request &req, Response & /*res*/) {
  5561. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5562. req.form.get_field_count("text2") +
  5563. req.form.get_field_count("file3") +
  5564. req.form.get_field_count("file4"));
  5565. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5566. req.form.get_file_count("file2"));
  5567. ASSERT_TRUE(!req.form.has_file("???"));
  5568. ASSERT_TRUE(!req.form.has_field("???"));
  5569. ASSERT_TRUE(req.body.empty());
  5570. {
  5571. const auto &text = req.form.get_field("text1");
  5572. EXPECT_EQ("text default", text);
  5573. }
  5574. {
  5575. const auto &text = req.form.get_field("text2");
  5576. EXPECT_EQ("aωb", text);
  5577. }
  5578. {
  5579. const auto &file = req.form.get_file("file1");
  5580. EXPECT_EQ("hello.txt", file.filename);
  5581. EXPECT_EQ("text/plain", file.content_type);
  5582. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5583. }
  5584. {
  5585. const auto &file = req.form.get_file("file2");
  5586. EXPECT_EQ("world.json", file.filename);
  5587. EXPECT_EQ("application/json", file.content_type);
  5588. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5589. }
  5590. {
  5591. const auto &text = req.form.get_field("file3");
  5592. EXPECT_EQ(0u, text.size());
  5593. }
  5594. {
  5595. const auto &text = req.form.get_field("file4");
  5596. EXPECT_EQ(0u, text.size());
  5597. }
  5598. })
  5599. .Post("/multipart/multi_file_values",
  5600. [&](const Request &req, Response & /*res*/) {
  5601. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5602. req.form.get_field_count("multi_text1"));
  5603. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5604. ASSERT_TRUE(!req.form.has_file("???"));
  5605. ASSERT_TRUE(!req.form.has_field("???"));
  5606. ASSERT_TRUE(req.body.empty());
  5607. {
  5608. const auto &text = req.form.get_field("text");
  5609. EXPECT_EQ("default text", text);
  5610. }
  5611. {
  5612. const auto &text1_values = req.form.get_fields("multi_text1");
  5613. EXPECT_EQ(2u, text1_values.size());
  5614. EXPECT_EQ("aaaaa", text1_values[0]);
  5615. EXPECT_EQ("bbbbb", text1_values[1]);
  5616. }
  5617. {
  5618. const auto &file1_values = req.form.get_files("multi_file1");
  5619. EXPECT_EQ(2u, file1_values.size());
  5620. auto file1 = file1_values[0];
  5621. EXPECT_EQ(file1.filename, "hello.txt");
  5622. EXPECT_EQ(file1.content_type, "text/plain");
  5623. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5624. auto file2 = file1_values[1];
  5625. EXPECT_EQ(file2.filename, "world.json");
  5626. EXPECT_EQ(file2.content_type, "application/json");
  5627. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5628. }
  5629. })
  5630. .Post("/empty",
  5631. [&](const Request &req, Response &res) {
  5632. EXPECT_EQ(req.body, "");
  5633. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5634. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5635. res.set_content("empty", "text/plain");
  5636. })
  5637. .Post("/empty-no-content-type",
  5638. [&](const Request &req, Response &res) {
  5639. EXPECT_EQ(req.body, "");
  5640. EXPECT_FALSE(req.has_header("Content-Type"));
  5641. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5642. res.set_content("empty-no-content-type", "text/plain");
  5643. })
  5644. .Post("/path-only",
  5645. [&](const Request &req, Response &res) {
  5646. EXPECT_EQ(req.body, "");
  5647. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5648. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5649. res.set_content("path-only", "text/plain");
  5650. })
  5651. .Post("/path-headers-only",
  5652. [&](const Request &req, Response &res) {
  5653. EXPECT_EQ(req.body, "");
  5654. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5655. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5656. EXPECT_EQ("world", req.get_header_value("hello"));
  5657. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5658. res.set_content("path-headers-only", "text/plain");
  5659. })
  5660. .Post("/post-large",
  5661. [&](const Request &req, Response &res) {
  5662. EXPECT_EQ(req.body, LARGE_DATA);
  5663. res.set_content(req.body, "text/plain");
  5664. })
  5665. .Post("/post-loopback",
  5666. [&](const Request &, Response &res,
  5667. ContentReader const &content_reader) {
  5668. std::string body;
  5669. content_reader([&](const char *data, size_t data_length) {
  5670. body.append(data, data_length);
  5671. return true;
  5672. });
  5673. res.set_content(body, "text/plain");
  5674. })
  5675. .Put("/put-loopback",
  5676. [&](const Request &, Response &res,
  5677. ContentReader const &content_reader) {
  5678. std::string body;
  5679. content_reader([&](const char *data, size_t data_length) {
  5680. body.append(data, data_length);
  5681. return true;
  5682. });
  5683. res.set_content(body, "text/plain");
  5684. })
  5685. .Patch("/patch-loopback",
  5686. [&](const Request &, Response &res,
  5687. ContentReader const &content_reader) {
  5688. std::string body;
  5689. content_reader([&](const char *data, size_t data_length) {
  5690. body.append(data, data_length);
  5691. return true;
  5692. });
  5693. res.set_content(body, "text/plain");
  5694. })
  5695. .Put("/empty-no-content-type",
  5696. [&](const Request &req, Response &res) {
  5697. EXPECT_EQ(req.body, "");
  5698. EXPECT_FALSE(req.has_header("Content-Type"));
  5699. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5700. res.set_content("empty-no-content-type", "text/plain");
  5701. })
  5702. .Put("/put",
  5703. [&](const Request &req, Response &res) {
  5704. EXPECT_EQ(req.body, "PUT");
  5705. res.set_content(req.body, "text/plain");
  5706. })
  5707. .Put("/put-large",
  5708. [&](const Request &req, Response &res) {
  5709. EXPECT_EQ(req.body, LARGE_DATA);
  5710. res.set_content(req.body, "text/plain");
  5711. })
  5712. .Patch("/patch",
  5713. [&](const Request &req, Response &res) {
  5714. EXPECT_EQ(req.body, "PATCH");
  5715. res.set_content(req.body, "text/plain");
  5716. })
  5717. .Delete("/delete",
  5718. [&](const Request & /*req*/, Response &res) {
  5719. res.set_content("DELETE", "text/plain");
  5720. })
  5721. .Delete("/delete-body",
  5722. [&](const Request &req, Response &res) {
  5723. EXPECT_EQ(req.body, "content");
  5724. res.set_content(req.body, "text/plain");
  5725. })
  5726. .Options(R"(\*)",
  5727. [&](const Request & /*req*/, Response &res) {
  5728. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5729. })
  5730. .CustomRoute("PROPFIND", "/dav/:id",
  5731. [&](const Request &req, Response &res) {
  5732. res.set_header("x-body-size",
  5733. std::to_string(req.body.size()));
  5734. res.set_header("x-matched-route", req.matched_route);
  5735. res.set_header("x-dav-id", req.path_params.at("id"));
  5736. res.status = StatusCode::MultiStatus_207;
  5737. res.set_content(req.body, "application/xml");
  5738. })
  5739. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5740. [&](const Request &req, Response &res) {
  5741. res.set_header("x-dav-match", req.matches[1]);
  5742. res.status = StatusCode::MultiStatus_207;
  5743. })
  5744. .CustomRoute("MKCOL", "/dav-mkcol",
  5745. [&](const Request &req, Response &res) {
  5746. EXPECT_TRUE(req.body.empty());
  5747. res.status = StatusCode::Created_201;
  5748. })
  5749. .CustomRoute(
  5750. "REPORT", "/dav-report",
  5751. [&](const Request & /*req*/, Response &res,
  5752. const ContentReader &content_reader) {
  5753. std::string body;
  5754. content_reader([&](const char *data, size_t data_length) {
  5755. body.append(data, data_length);
  5756. return true;
  5757. });
  5758. res.set_header("x-body-size", std::to_string(body.size()));
  5759. res.status = StatusCode::MultiStatus_207;
  5760. res.set_content(body, "application/xml");
  5761. })
  5762. .Get("/request-target",
  5763. [&](const Request &req, Response & /*res*/) {
  5764. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5765. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5766. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5767. })
  5768. .Get("/long-query-value",
  5769. [&](const Request &req, Response & /*res*/) {
  5770. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5771. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5772. })
  5773. .Get("/too-long-query-value",
  5774. [&](const Request &req, Response & /*res*/) {
  5775. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5776. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5777. })
  5778. .Get("/array-param",
  5779. [&](const Request &req, Response & /*res*/) {
  5780. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5781. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5782. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5783. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5784. })
  5785. .Get("/array-param-values",
  5786. [&](const Request &req, Response & /*res*/) {
  5787. auto values = req.get_param_values("array");
  5788. EXPECT_EQ(3u, values.size());
  5789. EXPECT_EQ("value1", values[0]);
  5790. EXPECT_EQ("value2", values[1]);
  5791. EXPECT_EQ("value3", values[2]);
  5792. auto empty = req.get_param_values("nonexistent");
  5793. EXPECT_TRUE(empty.empty());
  5794. })
  5795. .Post("/validate-no-multiple-headers",
  5796. [&](const Request &req, Response & /*res*/) {
  5797. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5798. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5799. })
  5800. .Post("/content_receiver",
  5801. [&](const Request &req, Response &res,
  5802. const ContentReader &content_reader) {
  5803. if (req.is_multipart_form_data()) {
  5804. std::vector<FormData> items;
  5805. content_reader(
  5806. [&](const FormData &file) {
  5807. items.push_back(file);
  5808. return true;
  5809. },
  5810. [&](const char *data, size_t data_length) {
  5811. items.back().content.append(data, data_length);
  5812. return true;
  5813. });
  5814. EXPECT_EQ(5u, items.size());
  5815. {
  5816. const auto &file = get_file_value(items, "text1");
  5817. EXPECT_TRUE(file.filename.empty());
  5818. EXPECT_EQ("text default", file.content);
  5819. }
  5820. {
  5821. const auto &file = get_file_value(items, "text2");
  5822. EXPECT_TRUE(file.filename.empty());
  5823. EXPECT_EQ("aωb", file.content);
  5824. }
  5825. {
  5826. const auto &file = get_file_value(items, "file1");
  5827. EXPECT_EQ("hello.txt", file.filename);
  5828. EXPECT_EQ("text/plain", file.content_type);
  5829. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5830. }
  5831. {
  5832. const auto &file = get_file_value(items, "file2");
  5833. EXPECT_EQ("world.json", file.filename);
  5834. EXPECT_EQ("application/json", file.content_type);
  5835. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5836. }
  5837. {
  5838. const auto &file = get_file_value(items, "file3");
  5839. EXPECT_TRUE(file.filename.empty());
  5840. EXPECT_EQ("application/octet-stream", file.content_type);
  5841. EXPECT_EQ(0u, file.content.size());
  5842. }
  5843. } else {
  5844. std::string body;
  5845. content_reader([&](const char *data, size_t data_length) {
  5846. EXPECT_EQ(7U, data_length);
  5847. body.append(data, data_length);
  5848. return true;
  5849. });
  5850. EXPECT_EQ(body, "content");
  5851. res.set_content(body, "text/plain");
  5852. }
  5853. })
  5854. .Put("/content_receiver",
  5855. [&](const Request & /*req*/, Response &res,
  5856. const ContentReader &content_reader) {
  5857. std::string body;
  5858. content_reader([&](const char *data, size_t data_length) {
  5859. body.append(data, data_length);
  5860. return true;
  5861. });
  5862. EXPECT_EQ(body, "content");
  5863. res.set_content(body, "text/plain");
  5864. })
  5865. .Patch("/content_receiver",
  5866. [&](const Request & /*req*/, Response &res,
  5867. const ContentReader &content_reader) {
  5868. std::string body;
  5869. content_reader([&](const char *data, size_t data_length) {
  5870. body.append(data, data_length);
  5871. return true;
  5872. });
  5873. EXPECT_EQ(body, "content");
  5874. res.set_content(body, "text/plain");
  5875. })
  5876. .Post("/query-string-and-body",
  5877. [&](const Request &req, Response & /*res*/) {
  5878. ASSERT_TRUE(req.has_param("key"));
  5879. EXPECT_EQ(req.get_param_value("key"), "value");
  5880. EXPECT_EQ(req.body, "content");
  5881. })
  5882. .Get("/last-request",
  5883. [&](const Request &req, Response & /*res*/) {
  5884. EXPECT_EQ("close", req.get_header_value("Connection"));
  5885. })
  5886. .Get(R"(/redirect/(\d+))",
  5887. [&](const Request &req, Response &res) {
  5888. auto num = std::stoi(req.matches[1]) + 1;
  5889. std::string url = "/redirect/" + std::to_string(num);
  5890. res.set_redirect(url);
  5891. })
  5892. .Post("/binary",
  5893. [&](const Request &req, Response &res) {
  5894. EXPECT_EQ(4U, req.body.size());
  5895. EXPECT_EQ("application/octet-stream",
  5896. req.get_header_value("Content-Type"));
  5897. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5898. res.set_content(req.body, "application/octet-stream");
  5899. })
  5900. .Put("/binary",
  5901. [&](const Request &req, Response &res) {
  5902. EXPECT_EQ(4U, req.body.size());
  5903. EXPECT_EQ("application/octet-stream",
  5904. req.get_header_value("Content-Type"));
  5905. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5906. res.set_content(req.body, "application/octet-stream");
  5907. })
  5908. .Patch("/binary",
  5909. [&](const Request &req, Response &res) {
  5910. EXPECT_EQ(4U, req.body.size());
  5911. EXPECT_EQ("application/octet-stream",
  5912. req.get_header_value("Content-Type"));
  5913. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5914. res.set_content(req.body, "application/octet-stream");
  5915. })
  5916. .Delete("/binary",
  5917. [&](const Request &req, Response &res) {
  5918. EXPECT_EQ(4U, req.body.size());
  5919. EXPECT_EQ("application/octet-stream",
  5920. req.get_header_value("Content-Type"));
  5921. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5922. res.set_content(req.body, "application/octet-stream");
  5923. })
  5924. .Get("/issue1772",
  5925. [&](const Request & /*req*/, Response &res) {
  5926. res.status = 401;
  5927. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5928. })
  5929. .Delete("/issue609",
  5930. [](const httplib::Request &, httplib::Response &res,
  5931. const httplib::ContentReader &) {
  5932. res.set_content("ok", "text/plain");
  5933. })
  5934. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5935. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5936. .Get("/compress",
  5937. [&](const Request & /*req*/, Response &res) {
  5938. res.set_content(
  5939. "12345678901234567890123456789012345678901234567890123456789"
  5940. "01234567890123456789012345678901234567890",
  5941. "text/plain");
  5942. })
  5943. .Get("/compress-with-charset",
  5944. [&](const Request & /*req*/, Response &res) {
  5945. res.set_content(
  5946. "12345678901234567890123456789012345678901234567890123456789"
  5947. "01234567890123456789012345678901234567890",
  5948. "application/json; charset=utf-8");
  5949. })
  5950. .Get("/nocompress",
  5951. [&](const Request & /*req*/, Response &res) {
  5952. res.set_content(
  5953. "12345678901234567890123456789012345678901234567890123456789"
  5954. "01234567890123456789012345678901234567890",
  5955. "application/octet-stream");
  5956. })
  5957. .Post("/compress-multipart",
  5958. [&](const Request &req, Response & /*res*/) {
  5959. EXPECT_EQ(2u, req.form.fields.size());
  5960. ASSERT_TRUE(!req.form.has_field("???"));
  5961. {
  5962. const auto &text = req.form.get_field("key1");
  5963. EXPECT_EQ("test", text);
  5964. }
  5965. {
  5966. const auto &text = req.form.get_field("key2");
  5967. EXPECT_EQ("--abcdefg123", text);
  5968. }
  5969. })
  5970. #endif
  5971. ;
  5972. persons_["john"] = "programmer";
  5973. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5974. svr_.wait_until_ready();
  5975. }
  5976. virtual void TearDown() {
  5977. svr_.stop();
  5978. if (!request_threads_.empty()) {
  5979. std::this_thread::sleep_for(std::chrono::seconds(1));
  5980. for (auto &t : request_threads_) {
  5981. t.join();
  5982. }
  5983. }
  5984. t_.join();
  5985. }
  5986. map<string, string> persons_;
  5987. #ifdef CPPHTTPLIB_SSL_ENABLED
  5988. SSLClient cli_;
  5989. SSLServer svr_;
  5990. #else
  5991. Client cli_;
  5992. Server svr_;
  5993. #endif
  5994. thread t_;
  5995. std::vector<thread> request_threads_;
  5996. };
  5997. TEST_F(ServerTest, GetMethod200) {
  5998. auto res = cli_.Get("/hi");
  5999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6000. EXPECT_EQ("HTTP/1.1", res->version);
  6001. EXPECT_EQ(StatusCode::OK_200, res->status);
  6002. EXPECT_EQ("OK", res->reason);
  6003. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6004. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6005. EXPECT_EQ("Hello World!", res->body);
  6006. }
  6007. TEST_F(ServerTest, GetEmptyFile) {
  6008. auto res = cli_.Get("/empty_file");
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. EXPECT_EQ(StatusCode::OK_200, res->status);
  6011. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6012. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6013. EXPECT_EQ("", res->body);
  6014. }
  6015. TEST_F(ServerTest, GetFileContent) {
  6016. auto res = cli_.Get("/file_content");
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6020. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6021. EXPECT_EQ("test.html", res->body);
  6022. }
  6023. TEST_F(ServerTest, GetFileContentWithRange) {
  6024. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6027. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6028. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6029. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6030. EXPECT_EQ("est", res->body);
  6031. }
  6032. TEST_F(ServerTest, GetFileContentWithContentType) {
  6033. auto res = cli_.Get("/file_content_with_content_type");
  6034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6035. EXPECT_EQ(StatusCode::OK_200, res->status);
  6036. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6037. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6038. EXPECT_EQ("file\n", res->body);
  6039. }
  6040. TEST_F(ServerTest, GetInvalidFileContent) {
  6041. auto res = cli_.Get("/invalid_file_content");
  6042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6043. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6044. }
  6045. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6046. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. EXPECT_EQ("HTTP/1.1", res->version);
  6049. EXPECT_EQ(StatusCode::OK_200, res->status);
  6050. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6051. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6052. EXPECT_EQ("Hello World!", res->body);
  6053. }
  6054. TEST_F(ServerTest, GetMethod302) {
  6055. auto res = cli_.Get("/");
  6056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6057. EXPECT_EQ(StatusCode::Found_302, res->status);
  6058. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6059. }
  6060. TEST_F(ServerTest, GetMethod302Redirect) {
  6061. cli_.set_follow_location(true);
  6062. auto res = cli_.Get("/");
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ(StatusCode::OK_200, res->status);
  6065. EXPECT_EQ("Hello World!", res->body);
  6066. EXPECT_EQ("/hi", res->location);
  6067. }
  6068. TEST_F(ServerTest, GetMethod404) {
  6069. auto res = cli_.Get("/invalid");
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6072. }
  6073. TEST_F(ServerTest, HeadMethod200) {
  6074. auto res = cli_.Head("/hi");
  6075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6076. EXPECT_EQ(StatusCode::OK_200, res->status);
  6077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6078. EXPECT_TRUE(res->body.empty());
  6079. }
  6080. TEST_F(ServerTest, HeadMethod200Static) {
  6081. auto res = cli_.Head("/mount/dir/index.html");
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. EXPECT_EQ(StatusCode::OK_200, res->status);
  6084. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6085. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6086. EXPECT_TRUE(res->body.empty());
  6087. }
  6088. TEST_F(ServerTest, HeadMethod404) {
  6089. auto res = cli_.Head("/invalid");
  6090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6091. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6092. EXPECT_TRUE(res->body.empty());
  6093. }
  6094. TEST_F(ServerTest, GetMethodPersonJohn) {
  6095. auto res = cli_.Get("/person/john");
  6096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6097. EXPECT_EQ(StatusCode::OK_200, res->status);
  6098. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6099. EXPECT_EQ("programmer", res->body);
  6100. }
  6101. TEST_F(ServerTest, PostMethod1) {
  6102. auto res = cli_.Get("/person/john1");
  6103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6104. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6105. res = cli_.Post("/person", "name=john1&note=coder",
  6106. "application/x-www-form-urlencoded");
  6107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6108. ASSERT_EQ(StatusCode::OK_200, res->status);
  6109. res = cli_.Get("/person/john1");
  6110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6111. ASSERT_EQ(StatusCode::OK_200, res->status);
  6112. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6113. ASSERT_EQ("coder", res->body);
  6114. }
  6115. TEST_F(ServerTest, PostMethod2) {
  6116. auto res = cli_.Get("/person/john2");
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6119. Params params;
  6120. params.emplace("name", "john2");
  6121. params.emplace("note", "coder");
  6122. res = cli_.Post("/person", params);
  6123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6124. ASSERT_EQ(StatusCode::OK_200, res->status);
  6125. res = cli_.Get("/person/john2");
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. ASSERT_EQ(StatusCode::OK_200, res->status);
  6128. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6129. ASSERT_EQ("coder", res->body);
  6130. }
  6131. TEST_F(ServerTest, PutMethod3) {
  6132. auto res = cli_.Get("/person/john3");
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6135. Params params;
  6136. params.emplace("name", "john3");
  6137. params.emplace("note", "coder");
  6138. res = cli_.Put("/person", params);
  6139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6140. ASSERT_EQ(StatusCode::OK_200, res->status);
  6141. res = cli_.Get("/person/john3");
  6142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6143. ASSERT_EQ(StatusCode::OK_200, res->status);
  6144. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6145. ASSERT_EQ("coder", res->body);
  6146. }
  6147. TEST_F(ServerTest, DeleteMethod1) {
  6148. auto res = cli_.Get("/person/john4");
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6151. Params params;
  6152. params.emplace("name", "john4");
  6153. params.emplace("note", "coder");
  6154. res = cli_.Post("/person", params);
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. ASSERT_EQ(StatusCode::OK_200, res->status);
  6157. res = cli_.Get("/person/john4");
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. ASSERT_EQ(StatusCode::OK_200, res->status);
  6160. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6161. ASSERT_EQ("coder", res->body);
  6162. Params delete_params;
  6163. delete_params.emplace("name", "john4");
  6164. res = cli_.Delete("/person", delete_params);
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. ASSERT_EQ(StatusCode::OK_200, res->status);
  6167. ASSERT_EQ("DELETED", res->body);
  6168. res = cli_.Get("/person/john4");
  6169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6170. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6171. }
  6172. TEST_F(ServerTest, DeleteMethod2) {
  6173. auto res = cli_.Get("/person/john5");
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6176. Params params;
  6177. params.emplace("name", "john5");
  6178. params.emplace("note", "developer");
  6179. res = cli_.Post("/person", params);
  6180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6181. ASSERT_EQ(StatusCode::OK_200, res->status);
  6182. res = cli_.Get("/person/john5");
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. ASSERT_EQ(StatusCode::OK_200, res->status);
  6185. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6186. ASSERT_EQ("developer", res->body);
  6187. Params delete_params;
  6188. delete_params.emplace("name", "john5");
  6189. Headers headers;
  6190. headers.emplace("Custom-Header", "test-value");
  6191. res = cli_.Delete("/person", headers, delete_params);
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. ASSERT_EQ(StatusCode::OK_200, res->status);
  6194. ASSERT_EQ("DELETED", res->body);
  6195. res = cli_.Get("/person/john5");
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6198. }
  6199. TEST_F(ServerTest, DeleteMethod3) {
  6200. auto res = cli_.Get("/person/john6");
  6201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6202. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6203. Params params;
  6204. params.emplace("name", "john6");
  6205. params.emplace("note", "tester");
  6206. res = cli_.Post("/person", params);
  6207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6208. ASSERT_EQ(StatusCode::OK_200, res->status);
  6209. res = cli_.Get("/person/john6");
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. ASSERT_EQ(StatusCode::OK_200, res->status);
  6212. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6213. ASSERT_EQ("tester", res->body);
  6214. Params delete_params;
  6215. delete_params.emplace("name", "john6");
  6216. Headers headers;
  6217. headers.emplace("Custom-Header", "test-value");
  6218. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. ASSERT_EQ(StatusCode::OK_200, res->status);
  6221. ASSERT_EQ("DELETED", res->body);
  6222. res = cli_.Get("/person/john6");
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6225. }
  6226. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6227. Params params;
  6228. params.emplace("json", JSON_DATA);
  6229. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. ASSERT_EQ(StatusCode::OK_200, res->status);
  6232. ASSERT_EQ(JSON_DATA, res->body);
  6233. }
  6234. TEST_F(ServerTest, PostEmptyContent) {
  6235. auto res = cli_.Post("/empty", "", "text/plain");
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. ASSERT_EQ(StatusCode::OK_200, res->status);
  6238. ASSERT_EQ("empty", res->body);
  6239. }
  6240. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6241. auto res = cli_.Post("/empty-no-content-type");
  6242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6243. ASSERT_EQ(StatusCode::OK_200, res->status);
  6244. ASSERT_EQ("empty-no-content-type", res->body);
  6245. }
  6246. TEST_F(ServerTest, PostPathOnly) {
  6247. auto res = cli_.Post("/path-only");
  6248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6249. ASSERT_EQ(StatusCode::OK_200, res->status);
  6250. ASSERT_EQ("path-only", res->body);
  6251. }
  6252. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6253. auto res = cli_.Post("/path-headers-only",
  6254. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. ASSERT_EQ(StatusCode::OK_200, res->status);
  6257. ASSERT_EQ("path-headers-only", res->body);
  6258. }
  6259. TEST_F(ServerTest, PostLarge) {
  6260. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6262. ASSERT_EQ(StatusCode::OK_200, res->status);
  6263. EXPECT_EQ(LARGE_DATA, res->body);
  6264. }
  6265. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6266. auto res = cli_.Put("/empty-no-content-type");
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. ASSERT_EQ(StatusCode::OK_200, res->status);
  6269. ASSERT_EQ("empty-no-content-type", res->body);
  6270. }
  6271. TEST_F(ServerTest, GetMethodDir) {
  6272. auto res = cli_.Get("/dir/");
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6276. auto body = R"(<html>
  6277. <head>
  6278. </head>
  6279. <body>
  6280. <a href="/dir/test.html">Test</a>
  6281. <a href="/hi">hi</a>
  6282. </body>
  6283. </html>
  6284. )";
  6285. EXPECT_EQ(body, res->body);
  6286. }
  6287. TEST_F(ServerTest, GetMethodDirTest) {
  6288. auto res = cli_.Get("/dir/test.html");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. EXPECT_EQ(StatusCode::OK_200, res->status);
  6291. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6292. EXPECT_EQ("test.html", res->body);
  6293. }
  6294. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6295. auto res = cli_.Get("/dir/../dir/test.html");
  6296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6297. EXPECT_EQ(StatusCode::OK_200, res->status);
  6298. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6299. EXPECT_EQ("test.html", res->body);
  6300. }
  6301. TEST_F(ServerTest, GetMethodInvalidPath) {
  6302. auto res = cli_.Get("/dir/../test.html");
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6305. }
  6306. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6307. auto res = cli_.Get("/../www/dir/test.html");
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6310. }
  6311. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6312. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6315. }
  6316. TEST_F(ServerTest, GetMethodDirMountTest) {
  6317. auto res = cli_.Get("/mount/dir/test.html");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. EXPECT_EQ(StatusCode::OK_200, res->status);
  6320. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6321. EXPECT_EQ("test.html", res->body);
  6322. }
  6323. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6324. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. EXPECT_EQ(StatusCode::OK_200, res->status);
  6327. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6328. EXPECT_EQ("test.html", res->body);
  6329. }
  6330. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6331. auto res = cli_.Get("/mount/dir/../test.html");
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6334. }
  6335. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6336. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6338. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6339. }
  6340. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6341. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6343. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6344. }
  6345. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6346. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6349. }
  6350. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6351. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6354. }
  6355. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6356. auto res = cli_.Get("/mount/dir");
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6359. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6360. }
  6361. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6362. auto res = cli_.Get("//dir");
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6365. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6366. }
  6367. TEST_F(ServerTest, PostMethod303) {
  6368. auto res = cli_.Post("/1", "body", "text/plain");
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6371. EXPECT_EQ("/2", res->get_header_value("Location"));
  6372. }
  6373. TEST_F(ServerTest, PostMethod303Redirect) {
  6374. cli_.set_follow_location(true);
  6375. auto res = cli_.Post("/1", "body", "text/plain");
  6376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6377. EXPECT_EQ(StatusCode::OK_200, res->status);
  6378. EXPECT_EQ("redirected.", res->body);
  6379. EXPECT_EQ("/2", res->location);
  6380. }
  6381. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6382. auto res = cli_.Get("/dir/test.abcde");
  6383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6384. EXPECT_EQ(StatusCode::OK_200, res->status);
  6385. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6386. EXPECT_EQ("abcde", res->body);
  6387. }
  6388. TEST_F(ServerTest, StaticFileRange) {
  6389. auto res =
  6390. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6393. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6394. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6395. EXPECT_EQ(true, res->has_header("Content-Range"));
  6396. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6397. EXPECT_EQ(std::string("cd"), res->body);
  6398. }
  6399. TEST_F(ServerTest, StaticFileRanges) {
  6400. auto res = cli_.Get("/dir/test.abcde",
  6401. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6404. EXPECT_TRUE(
  6405. res->get_header_value("Content-Type")
  6406. .find(
  6407. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6408. 0);
  6409. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6410. }
  6411. TEST_F(ServerTest, StaticFileRangeHead) {
  6412. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6414. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6415. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6416. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6417. EXPECT_EQ(true, res->has_header("Content-Range"));
  6418. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6419. }
  6420. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6421. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6423. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6424. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6425. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6426. EXPECT_EQ(true, res->has_header("Content-Range"));
  6427. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6428. res->get_header_value("Content-Range"));
  6429. EXPECT_EQ("LAST\n", res->body);
  6430. }
  6431. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6432. auto res =
  6433. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6435. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6436. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6437. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6438. EXPECT_EQ(true, res->has_header("Content-Range"));
  6439. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6440. }
  6441. TEST_F(ServerTest, StaticFileBigFile) {
  6442. auto res = cli_.Get("/dir/1MB.txt");
  6443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6444. EXPECT_EQ(StatusCode::OK_200, res->status);
  6445. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6446. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6447. }
  6448. TEST_F(ServerTest, InvalidBaseDirMount) {
  6449. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6450. }
  6451. TEST_F(ServerTest, Binary) {
  6452. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6453. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6454. "application/octet-stream");
  6455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6456. ASSERT_EQ(StatusCode::OK_200, res->status);
  6457. ASSERT_EQ(4U, res->body.size());
  6458. res = cli_.Put("/binary", binary.data(), binary.size(),
  6459. "application/octet-stream");
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. ASSERT_EQ(StatusCode::OK_200, res->status);
  6462. ASSERT_EQ(4U, res->body.size());
  6463. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6464. "application/octet-stream");
  6465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6466. ASSERT_EQ(StatusCode::OK_200, res->status);
  6467. ASSERT_EQ(4U, res->body.size());
  6468. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6469. "application/octet-stream");
  6470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6471. ASSERT_EQ(StatusCode::OK_200, res->status);
  6472. ASSERT_EQ(4U, res->body.size());
  6473. }
  6474. TEST_F(ServerTest, BinaryString) {
  6475. auto binary = std::string("\x00\x01\x02\x03", 4);
  6476. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6478. ASSERT_EQ(StatusCode::OK_200, res->status);
  6479. ASSERT_EQ(4U, res->body.size());
  6480. res = cli_.Put("/binary", binary, "application/octet-stream");
  6481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6482. ASSERT_EQ(StatusCode::OK_200, res->status);
  6483. ASSERT_EQ(4U, res->body.size());
  6484. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. ASSERT_EQ(StatusCode::OK_200, res->status);
  6487. ASSERT_EQ(4U, res->body.size());
  6488. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. ASSERT_EQ(StatusCode::OK_200, res->status);
  6491. ASSERT_EQ(4U, res->body.size());
  6492. }
  6493. TEST_F(ServerTest, EmptyRequest) {
  6494. auto res = cli_.Get("");
  6495. ASSERT_TRUE(!res);
  6496. EXPECT_EQ(Error::Connection, res.error());
  6497. }
  6498. TEST_F(ServerTest, LongRequest) {
  6499. std::string request;
  6500. for (size_t i = 0; i < 545; i++) {
  6501. request += "/TooLongRequest";
  6502. }
  6503. request += "OK";
  6504. auto res = cli_.Get(request.c_str());
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6507. }
  6508. TEST_F(ServerTest, TooLongRequest) {
  6509. std::string request;
  6510. for (size_t i = 0; i < 546; i++) {
  6511. request += "/TooLongRequest";
  6512. }
  6513. request += "_NG";
  6514. auto start = std::chrono::high_resolution_clock::now();
  6515. cli_.set_keep_alive(true);
  6516. auto res = cli_.Get(request.c_str());
  6517. auto end = std::chrono::high_resolution_clock::now();
  6518. auto elapsed =
  6519. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6520. .count();
  6521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6522. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6523. EXPECT_LE(elapsed, 1000);
  6524. EXPECT_EQ("close", res->get_header_value("Connection"));
  6525. EXPECT_FALSE(cli_.is_socket_open());
  6526. }
  6527. TEST_F(ServerTest, AlmostTooLongRequest) {
  6528. // test for #2046 - URI length check shouldn't include other content on req
  6529. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6530. // leading /, space, HTTP/1.1)
  6531. std::string request =
  6532. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6533. auto res = cli_.Get(request.c_str());
  6534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6536. }
  6537. TEST_F(ServerTest, LongHeader) {
  6538. Request req;
  6539. req.method = "GET";
  6540. req.path = "/hi";
  6541. std::string host_and_port;
  6542. host_and_port += HOST;
  6543. host_and_port += ":";
  6544. host_and_port += std::to_string(PORT);
  6545. req.headers.emplace("Host", host_and_port.c_str());
  6546. req.headers.emplace("Accept", "*/*");
  6547. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6548. req.headers.emplace(
  6549. "Header-Name",
  6550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6578. "@@@@@@@@@@@@@@@@");
  6579. auto res = std::make_shared<Response>();
  6580. auto error = Error::Success;
  6581. auto ret = cli_.send(req, *res, error);
  6582. ASSERT_TRUE(ret);
  6583. EXPECT_EQ(StatusCode::OK_200, res->status);
  6584. }
  6585. TEST_F(ServerTest, LongQueryValue) {
  6586. auto start = std::chrono::high_resolution_clock::now();
  6587. cli_.set_keep_alive(true);
  6588. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6589. auto end = std::chrono::high_resolution_clock::now();
  6590. auto elapsed =
  6591. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6592. .count();
  6593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6594. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6595. EXPECT_LE(elapsed, 1000);
  6596. EXPECT_EQ("close", res->get_header_value("Connection"));
  6597. EXPECT_FALSE(cli_.is_socket_open());
  6598. }
  6599. TEST_F(ServerTest, TooLongQueryValue) {
  6600. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6601. ASSERT_FALSE(res);
  6602. EXPECT_EQ(Error::Read, res.error());
  6603. }
  6604. TEST_F(ServerTest, TooLongHeader) {
  6605. Request req;
  6606. req.method = "GET";
  6607. req.path = "/hi";
  6608. std::string host_and_port;
  6609. host_and_port += HOST;
  6610. host_and_port += ":";
  6611. host_and_port += std::to_string(PORT);
  6612. req.headers.emplace("Host", host_and_port.c_str());
  6613. req.headers.emplace("Accept", "*/*");
  6614. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6615. req.headers.emplace(
  6616. "Header-Name",
  6617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6645. "@@@@@@@@@@@@@@@@@");
  6646. auto res = std::make_shared<Response>();
  6647. auto error = Error::Success;
  6648. auto ret = cli_.send(req, *res, error);
  6649. ASSERT_TRUE(ret);
  6650. EXPECT_EQ(StatusCode::OK_200, res->status);
  6651. }
  6652. TEST_F(ServerTest, HeaderCountAtLimit) {
  6653. // Test with headers just under the 100 limit
  6654. httplib::Headers headers;
  6655. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6656. // This should keep us just under the 100 header limit
  6657. for (int i = 0; i < 95; i++) {
  6658. std::string name = "X-Test-Header-" + std::to_string(i);
  6659. std::string value = "value" + std::to_string(i);
  6660. headers.emplace(name, value);
  6661. }
  6662. // This should work fine as we're under the limit
  6663. auto res = cli_.Get("/hi", headers);
  6664. EXPECT_TRUE(res);
  6665. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6666. }
  6667. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6668. // Test with many headers to exceed the 100 limit
  6669. httplib::Headers headers;
  6670. // Add 150 headers to definitely exceed the 100 limit
  6671. for (int i = 0; i < 150; i++) {
  6672. std::string name = "X-Test-Header-" + std::to_string(i);
  6673. std::string value = "value" + std::to_string(i);
  6674. headers.emplace(name, value);
  6675. }
  6676. // This should fail due to exceeding header count limit
  6677. cli_.set_keep_alive(true);
  6678. auto res = cli_.Get("/hi", headers);
  6679. // The server should respond with 400 Bad Request
  6680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6681. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6682. EXPECT_EQ("close", res->get_header_value("Connection"));
  6683. EXPECT_FALSE(cli_.is_socket_open());
  6684. }
  6685. TEST_F(ServerTest, PercentEncoding) {
  6686. auto res = cli_.Get("/e%6edwith%");
  6687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6688. EXPECT_EQ(StatusCode::OK_200, res->status);
  6689. }
  6690. TEST_F(ServerTest, PercentEncodingUnicode) {
  6691. auto res = cli_.Get("/e%u006edwith%");
  6692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6693. EXPECT_EQ(StatusCode::OK_200, res->status);
  6694. }
  6695. TEST_F(ServerTest, InvalidPercentEncoding) {
  6696. auto res = cli_.Get("/%endwith%");
  6697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6698. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6699. }
  6700. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6701. auto res = cli_.Get("/%uendwith%");
  6702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6703. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6704. }
  6705. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6706. auto res = cli_.Get("/hello?aaa=bbb%");
  6707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6709. }
  6710. TEST_F(ServerTest, PlusSignEncoding) {
  6711. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_EQ(StatusCode::OK_200, res->status);
  6714. EXPECT_EQ("a +b", res->body);
  6715. }
  6716. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6717. // This test simulates a potential DoS attack using many headers
  6718. // to verify our security fix prevents memory exhaustion
  6719. httplib::Headers attack_headers;
  6720. // Attempt to add many headers like an attacker would (200 headers to far
  6721. // exceed limit)
  6722. for (int i = 0; i < 200; i++) {
  6723. std::string name = "X-Attack-Header-" + std::to_string(i);
  6724. std::string value = "attack_payload_" + std::to_string(i);
  6725. attack_headers.emplace(name, value);
  6726. }
  6727. // Try to POST with excessive headers
  6728. cli_.set_keep_alive(true);
  6729. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6730. // Should either fail or return 400 Bad Request due to security limit
  6731. if (res) {
  6732. // If we get a response, it should be 400 Bad Request
  6733. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6734. EXPECT_EQ("close", res->get_header_value("Connection"));
  6735. }
  6736. EXPECT_FALSE(cli_.is_socket_open());
  6737. }
  6738. TEST_F(ServerTest, MultipartFormData) {
  6739. UploadFormDataItems items = {
  6740. {"text1", "text default", "", ""},
  6741. {"text2", "aωb", "", ""},
  6742. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6743. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6744. {"file3", "", "", "application/octet-stream"},
  6745. {"file4", "", "", " application/json tmp-string "}};
  6746. auto res = cli_.Post("/multipart", items);
  6747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6748. EXPECT_EQ(StatusCode::OK_200, res->status);
  6749. }
  6750. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6751. UploadFormDataItems items = {
  6752. {"text", "default text", "", ""},
  6753. {"multi_text1", "aaaaa", "", ""},
  6754. {"multi_text1", "bbbbb", "", ""},
  6755. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6756. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6757. "application/json"},
  6758. };
  6759. auto res = cli_.Post("/multipart/multi_file_values", items);
  6760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6761. EXPECT_EQ(StatusCode::OK_200, res->status);
  6762. }
  6763. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6764. auto res = cli_.Get("/hi");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6768. EXPECT_EQ("Hello World!", res->body);
  6769. }
  6770. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6771. Request req;
  6772. req.method = "POST";
  6773. req.path = "/chunked";
  6774. std::string host_and_port;
  6775. host_and_port += HOST;
  6776. host_and_port += ":";
  6777. host_and_port += std::to_string(PORT);
  6778. req.headers.emplace("Host", host_and_port.c_str());
  6779. req.headers.emplace("Accept", "*/*");
  6780. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6781. req.headers.emplace("Content-Type", "text/plain");
  6782. req.headers.emplace("Content-Length", "0");
  6783. req.headers.emplace(
  6784. "Transfer-Encoding",
  6785. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6786. // Client does not chunk, so make a chunked body manually.
  6787. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6788. auto res = std::make_shared<Response>();
  6789. auto error = Error::Success;
  6790. auto ret = cli_.send(req, *res, error);
  6791. ASSERT_TRUE(ret);
  6792. EXPECT_EQ(StatusCode::OK_200, res->status);
  6793. }
  6794. template <typename ClientT>
  6795. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6796. int expected_status) {
  6797. Request req;
  6798. req.method = "POST";
  6799. req.path = "/chunked";
  6800. std::string host_and_port;
  6801. host_and_port += HOST;
  6802. host_and_port += ":";
  6803. host_and_port += std::to_string(PORT);
  6804. req.headers.emplace("Host", host_and_port.c_str());
  6805. req.headers.emplace("Content-Length", "0");
  6806. req.headers.emplace("Transfer-Encoding", "chunked");
  6807. req.body = body;
  6808. auto res = std::make_shared<Response>();
  6809. auto error = Error::Success;
  6810. ASSERT_TRUE(cli.send(req, *res, error));
  6811. EXPECT_EQ(expected_status, res->status);
  6812. }
  6813. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6814. // rather than treat them as valid lengths.
  6815. template <typename ClientT>
  6816. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6817. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6818. }
  6819. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6820. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6821. }
  6822. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6823. expect_chunked_body_rejected(
  6824. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6825. }
  6826. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6827. // chunk-size line carries no CR, LF or other control character ahead of its
  6828. // terminator. Such a line must be refused rather than read as extension text.
  6829. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6830. expect_chunked_body_rejected(
  6831. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6832. }
  6833. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6834. expect_chunked_body_rejected(
  6835. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6836. }
  6837. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6838. expect_chunked_body_rejected(
  6839. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6840. }
  6841. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6842. // The literal stays split: a hex escape consumes every hex digit that
  6843. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6844. expect_chunked_body_rejected(
  6845. cli_, "4;a\x01"
  6846. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6847. }
  6848. TEST_F(ServerTest, AcceptsChunkExtension) {
  6849. expect_chunked_body_status(cli_,
  6850. "4;name=value\r\ndech\r\n"
  6851. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6852. "0;last\r\n\r\n",
  6853. StatusCode::OK_200);
  6854. }
  6855. TEST_F(ServerTest, GetStreamed2) {
  6856. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6858. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6859. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6860. EXPECT_EQ(true, res->has_header("Content-Range"));
  6861. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6862. EXPECT_EQ(std::string("ab"), res->body);
  6863. }
  6864. TEST_F(ServerTest, GetStreamed) {
  6865. auto res = cli_.Get("/streamed");
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6869. EXPECT_EQ(std::string("aaabbb"), res->body);
  6870. }
  6871. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6872. auto res = cli_.Get("/streamed-without-length",
  6873. Headers{make_range_header({{0, -1}})});
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. EXPECT_EQ(false, res->has_header("Content-Length"));
  6877. EXPECT_EQ(false, res->has_header("Content-Range"));
  6878. EXPECT_EQ(std::string("abcdefg"), res->body);
  6879. }
  6880. TEST_F(ServerTest, GetStreamedWithRange1) {
  6881. auto res =
  6882. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6884. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6885. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6886. EXPECT_EQ(true, res->has_header("Content-Range"));
  6887. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6888. EXPECT_EQ(std::string("def"), res->body);
  6889. }
  6890. TEST_F(ServerTest, GetStreamedWithRange2) {
  6891. auto res =
  6892. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6895. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6896. EXPECT_EQ(true, res->has_header("Content-Range"));
  6897. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6898. EXPECT_EQ(std::string("bcdefg"), res->body);
  6899. }
  6900. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6901. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6904. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6905. EXPECT_EQ(true, res->has_header("Content-Range"));
  6906. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6907. EXPECT_EQ(std::string("efg"), res->body);
  6908. }
  6909. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6910. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6911. // the entire representation.
  6912. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6913. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6915. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6916. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6917. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6918. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6919. }
  6920. }
  6921. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6922. auto res =
  6923. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6925. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6926. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6927. EXPECT_EQ(false, res->has_header("Content-Range"));
  6928. EXPECT_EQ(0U, res->body.size());
  6929. }
  6930. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6931. // Only a 206 is served as a partial representation. Under any other status
  6932. // `apply_ranges()` reported the full content length, so the body must match
  6933. // that header, and the content provider must never be asked for an offset
  6934. // outside the representation.
  6935. auto check = [&](int status, const char *range) {
  6936. auto path =
  6937. std::string("/streamed-with-range?status=") + std::to_string(status);
  6938. auto ctx = path + " Range: " + range;
  6939. auto res = cli_.Get(path, Headers{{"Range", range}});
  6940. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6941. EXPECT_EQ(status, res->status) << ctx;
  6942. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6944. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6945. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6946. };
  6947. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6948. check(403, "bytes=3-5");
  6949. // The offset is far past the representation.
  6950. check(403, "bytes=100000-100200");
  6951. // `first_pos` is still -1 here, and the bounds asserts in
  6952. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6953. check(403, "bytes=-3");
  6954. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6955. // multipart branch would have written one that is empty.
  6956. check(403, "bytes=1-2, 4-5");
  6957. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6958. // covers the whole representation.
  6959. check(200, "bytes=3-5");
  6960. check(200, "bytes=1-2, 4-5");
  6961. }
  6962. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6963. auto res =
  6964. cli_.Get("/streamed-with-range",
  6965. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6966. "92233720368547758079223372036854775807"}});
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6969. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6970. EXPECT_EQ(false, res->has_header("Content-Range"));
  6971. EXPECT_EQ(0U, res->body.size());
  6972. }
  6973. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6974. auto res = cli_.Get(
  6975. "/with-range",
  6976. Headers{{"Range",
  6977. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6978. {"Accept-Encoding", ""}});
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6981. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6982. EXPECT_EQ(true, res->has_header("Content-Range"));
  6983. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6984. EXPECT_EQ(std::string("abcdefg"), res->body);
  6985. }
  6986. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6987. auto res = cli_.Get("/with-range", Headers{
  6988. {"Range", "bytes=0-"},
  6989. {"Accept-Encoding", ""},
  6990. });
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6993. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6994. EXPECT_EQ(true, res->has_header("Content-Range"));
  6995. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6996. EXPECT_EQ(std::string("abcdefg"), res->body);
  6997. }
  6998. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6999. auto res = cli_.Get("/streamed-with-range",
  7000. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7003. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7004. EXPECT_EQ(false, res->has_header("Content-Range"));
  7005. EXPECT_EQ(267U, res->body.size());
  7006. // Check that both range contents are present
  7007. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7008. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7009. // Check that Content-Range headers are present for both ranges
  7010. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7011. std::string::npos);
  7012. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7013. std::string::npos);
  7014. }
  7015. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7016. Ranges ranges;
  7017. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7018. ranges.emplace_back(0, -1);
  7019. }
  7020. auto res = cli_.Get("/streamed-with-range?error",
  7021. Headers{{make_range_header(ranges)}});
  7022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7023. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7024. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7025. EXPECT_EQ(false, res->has_header("Content-Range"));
  7026. EXPECT_EQ(0U, res->body.size());
  7027. }
  7028. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7029. auto res = cli_.Get("/streamed-with-range",
  7030. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7033. EXPECT_EQ(5U, res->body.size());
  7034. // Check that overlapping ranges are coalesced into a single range
  7035. EXPECT_EQ("bcdef", res->body);
  7036. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7037. // Should be single range, not multipart
  7038. EXPECT_TRUE(res->has_header("Content-Range"));
  7039. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7040. }
  7041. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7042. auto res = cli_.Get("/streamed-with-range",
  7043. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7046. EXPECT_EQ(268U, res->body.size());
  7047. // Check that both range contents are present
  7048. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7049. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7050. // Check that Content-Range headers are present for both ranges
  7051. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7052. std::string::npos);
  7053. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7054. std::string::npos);
  7055. }
  7056. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7057. auto res = cli_.Get("/streamed-with-range",
  7058. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7061. EXPECT_EQ(269U, res->body.size());
  7062. // Check that both duplicate range contents are present
  7063. size_t first_abc = res->body.find("abc\r\n");
  7064. EXPECT_TRUE(first_abc != std::string::npos);
  7065. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7066. EXPECT_TRUE(second_abc != std::string::npos);
  7067. // Check that Content-Range headers are present for both ranges
  7068. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7069. EXPECT_TRUE(first_range != std::string::npos);
  7070. size_t second_range =
  7071. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7072. EXPECT_TRUE(second_range != std::string::npos);
  7073. }
  7074. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7075. auto res =
  7076. cli_.Get("/streamed-with-range?error",
  7077. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7079. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7080. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7081. EXPECT_EQ(false, res->has_header("Content-Range"));
  7082. EXPECT_EQ(0U, res->body.size());
  7083. }
  7084. TEST_F(ServerTest, GetStreamedEndless) {
  7085. uint64_t offset = 0;
  7086. auto res = cli_.Get("/streamed-cancel",
  7087. [&](const char * /*data*/, uint64_t data_length) {
  7088. if (offset < 100) {
  7089. offset += data_length;
  7090. return true;
  7091. }
  7092. return false;
  7093. });
  7094. ASSERT_TRUE(!res);
  7095. EXPECT_EQ(Error::Canceled, res.error());
  7096. }
  7097. TEST_F(ServerTest, ClientStop) {
  7098. std::atomic_size_t count{4};
  7099. std::vector<std::thread> threads;
  7100. for (auto i = count.load(); i != 0; --i) {
  7101. threads.emplace_back([&]() {
  7102. auto res = cli_.Get("/streamed-cancel",
  7103. [&](const char *, uint64_t) { return true; });
  7104. --count;
  7105. ASSERT_TRUE(!res);
  7106. EXPECT_TRUE(res.error() == Error::Canceled ||
  7107. res.error() == Error::Read || res.error() == Error::Write);
  7108. });
  7109. }
  7110. std::this_thread::sleep_for(std::chrono::seconds(2));
  7111. while (count != 0) {
  7112. cli_.stop();
  7113. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7114. }
  7115. for (auto &t : threads) {
  7116. t.join();
  7117. }
  7118. }
  7119. TEST_F(ServerTest, GetWithRange1) {
  7120. auto res = cli_.Get("/with-range", Headers{
  7121. make_range_header({{3, 5}}),
  7122. {"Accept-Encoding", ""},
  7123. });
  7124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7125. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7126. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7127. EXPECT_EQ(true, res->has_header("Content-Range"));
  7128. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7129. EXPECT_EQ(std::string("def"), res->body);
  7130. }
  7131. TEST_F(ServerTest, GetWithRange2) {
  7132. auto res = cli_.Get("/with-range", Headers{
  7133. make_range_header({{1, -1}}),
  7134. {"Accept-Encoding", ""},
  7135. });
  7136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7137. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7138. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7139. EXPECT_EQ(true, res->has_header("Content-Range"));
  7140. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7141. EXPECT_EQ(std::string("bcdefg"), res->body);
  7142. }
  7143. TEST_F(ServerTest, GetWithRange3) {
  7144. auto res = cli_.Get("/with-range", Headers{
  7145. make_range_header({{0, 0}}),
  7146. {"Accept-Encoding", ""},
  7147. });
  7148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7149. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7150. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7151. EXPECT_EQ(true, res->has_header("Content-Range"));
  7152. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7153. EXPECT_EQ(std::string("a"), res->body);
  7154. }
  7155. TEST_F(ServerTest, GetWithRange4) {
  7156. auto res = cli_.Get("/with-range", Headers{
  7157. make_range_header({{-1, 2}}),
  7158. {"Accept-Encoding", ""},
  7159. });
  7160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7161. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7162. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7163. EXPECT_EQ(true, res->has_header("Content-Range"));
  7164. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7165. EXPECT_EQ(std::string("fg"), res->body);
  7166. }
  7167. TEST_F(ServerTest, GetWithRange5) {
  7168. auto res = cli_.Get("/with-range", Headers{
  7169. make_range_header({{0, 5}}),
  7170. {"Accept-Encoding", ""},
  7171. });
  7172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7174. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7175. EXPECT_EQ(true, res->has_header("Content-Range"));
  7176. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7177. EXPECT_EQ(std::string("abcdef"), res->body);
  7178. }
  7179. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7180. auto res =
  7181. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7183. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7184. }
  7185. TEST_F(ServerTest, GetWithRangeMultipart) {
  7186. auto res =
  7187. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7189. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7190. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7191. EXPECT_EQ(false, res->has_header("Content-Range"));
  7192. EXPECT_EQ(267U, res->body.size());
  7193. }
  7194. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7195. auto res = cli_.Get("/with-range",
  7196. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7198. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7199. }
  7200. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7201. auto res = cli_.Get("/with-range-customized-response",
  7202. Headers{{make_range_header({{1, 2}})}});
  7203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7204. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7205. EXPECT_EQ(true, res->has_header("Content-Length"));
  7206. EXPECT_EQ(false, res->has_header("Content-Range"));
  7207. EXPECT_EQ(JSON_DATA, res->body);
  7208. }
  7209. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7210. auto res = cli_.Get("/with-range-customized-response",
  7211. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7213. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7214. EXPECT_EQ(true, res->has_header("Content-Length"));
  7215. EXPECT_EQ(false, res->has_header("Content-Range"));
  7216. EXPECT_EQ(JSON_DATA, res->body);
  7217. }
  7218. TEST_F(ServerTest, Issue1772) {
  7219. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7221. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7222. }
  7223. TEST_F(ServerTest, Issue609) {
  7224. auto res = cli_.Delete("/issue609");
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::OK_200, res->status);
  7227. EXPECT_EQ(std::string("ok"), res->body);
  7228. }
  7229. TEST_F(ServerTest, GetStreamedChunked) {
  7230. auto res = cli_.Get("/streamed-chunked");
  7231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7232. EXPECT_EQ(StatusCode::OK_200, res->status);
  7233. EXPECT_EQ(std::string("123456789"), res->body);
  7234. }
  7235. TEST_F(ServerTest, GetStreamedChunked2) {
  7236. auto res = cli_.Get("/streamed-chunked2");
  7237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7238. EXPECT_EQ(StatusCode::OK_200, res->status);
  7239. EXPECT_EQ(std::string("123456789"), res->body);
  7240. }
  7241. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7242. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ(std::string("123456789"), res->body);
  7246. EXPECT_TRUE(res->has_header("Trailer"));
  7247. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7248. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7249. // Trailers are now stored separately from headers (security fix)
  7250. EXPECT_EQ(2U, res->trailers.size());
  7251. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7252. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7253. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7254. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7255. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7256. // Verify trailers are NOT in headers (security verification)
  7257. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7258. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7259. }
  7260. TEST_F(ServerTest, LargeChunkedPost) {
  7261. Request req;
  7262. req.method = "POST";
  7263. req.path = "/large-chunked";
  7264. std::string host_and_port;
  7265. host_and_port += HOST;
  7266. host_and_port += ":";
  7267. host_and_port += std::to_string(PORT);
  7268. req.headers.emplace("Host", host_and_port.c_str());
  7269. req.headers.emplace("Accept", "*/*");
  7270. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7271. req.headers.emplace("Content-Type", "text/plain");
  7272. req.headers.emplace("Content-Length", "0");
  7273. req.headers.emplace("Transfer-Encoding", "chunked");
  7274. std::string long_string(30 * 1024u, 'a');
  7275. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7276. // Attempt to make a large enough post to exceed OS buffers, to test that
  7277. // the server handles short reads if the full chunk data isn't available.
  7278. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7279. auto res = std::make_shared<Response>();
  7280. auto error = Error::Success;
  7281. auto ret = cli_.send(req, *res, error);
  7282. ASSERT_TRUE(ret);
  7283. EXPECT_EQ(StatusCode::OK_200, res->status);
  7284. }
  7285. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7286. auto res = cli_.Get("/remote_addr");
  7287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7288. EXPECT_EQ(StatusCode::OK_200, res->status);
  7289. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7290. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7291. }
  7292. TEST_F(ServerTest, GetMethodLocalAddr) {
  7293. auto res = cli_.Get("/local_addr");
  7294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7295. EXPECT_EQ(StatusCode::OK_200, res->status);
  7296. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7297. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7298. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7299. }
  7300. TEST_F(ServerTest, HTTPResponseSplitting) {
  7301. auto res = cli_.Get("/http_response_splitting");
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. }
  7305. TEST_F(ServerTest, SlowRequest) {
  7306. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7307. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7308. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7309. }
  7310. #if 0
  7311. TEST_F(ServerTest, SlowPost) {
  7312. char buffer[64 * 1024];
  7313. memset(buffer, 0x42, sizeof(buffer));
  7314. auto res = cli_.Post(
  7315. "/slowpost", 64 * 1024 * 1024,
  7316. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7317. auto ret = sink.write(buffer, sizeof(buffer));
  7318. EXPECT_TRUE(ret);
  7319. return true;
  7320. },
  7321. "text/plain");
  7322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7323. EXPECT_EQ(StatusCode::OK_200, res->status);
  7324. }
  7325. TEST_F(ServerTest, SlowPostFail) {
  7326. char buffer[64 * 1024];
  7327. memset(buffer, 0x42, sizeof(buffer));
  7328. cli_.set_write_timeout(std::chrono::seconds(0));
  7329. auto res = cli_.Post(
  7330. "/slowpost", 64 * 1024 * 1024,
  7331. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7332. sink.write(buffer, sizeof(buffer));
  7333. return true;
  7334. },
  7335. "text/plain");
  7336. ASSERT_TRUE(!res);
  7337. EXPECT_EQ(Error::Write, res.error());
  7338. }
  7339. #endif
  7340. TEST_F(ServerTest, Put) {
  7341. auto res = cli_.Put("/put", "PUT", "text/plain");
  7342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7343. EXPECT_EQ(StatusCode::OK_200, res->status);
  7344. EXPECT_EQ("PUT", res->body);
  7345. }
  7346. TEST_F(ServerTest, PutWithContentProvider) {
  7347. auto res = cli_.Put(
  7348. "/put", 3,
  7349. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7350. sink.os << "PUT";
  7351. return true;
  7352. },
  7353. "text/plain");
  7354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7355. EXPECT_EQ(StatusCode::OK_200, res->status);
  7356. EXPECT_EQ("PUT", res->body);
  7357. }
  7358. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7359. auto res = cli_.Post(
  7360. "/post", 42,
  7361. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7362. return false;
  7363. },
  7364. "text/plain");
  7365. ASSERT_TRUE(!res);
  7366. EXPECT_EQ(Error::Canceled, res.error());
  7367. }
  7368. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7369. auto res = cli_.Put(
  7370. "/put",
  7371. [](size_t /*offset*/, DataSink &sink) {
  7372. sink.os << "PUT";
  7373. sink.done();
  7374. return true;
  7375. },
  7376. "text/plain");
  7377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7378. EXPECT_EQ(StatusCode::OK_200, res->status);
  7379. EXPECT_EQ("PUT", res->body);
  7380. }
  7381. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7382. auto res = cli_.Post(
  7383. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7384. "text/plain");
  7385. ASSERT_TRUE(!res);
  7386. EXPECT_EQ(Error::Canceled, res.error());
  7387. }
  7388. TEST_F(ServerTest, PostLoopBack) {
  7389. std::string body;
  7390. auto res = cli_.Post(
  7391. "/post-loopback", 9,
  7392. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7393. EXPECT_EQ(9u, length);
  7394. sink.write("123", 3);
  7395. sink.write("456", 3);
  7396. sink.write("789", 3);
  7397. return true;
  7398. },
  7399. "text/plain",
  7400. [&body](const char *data, size_t data_length) {
  7401. body.append(data, data_length);
  7402. return true;
  7403. });
  7404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7405. EXPECT_EQ(StatusCode::OK_200, res->status);
  7406. EXPECT_EQ("123456789", body);
  7407. }
  7408. TEST_F(ServerTest, PutLoopBack) {
  7409. std::string body;
  7410. auto res = cli_.Put(
  7411. "/put-loopback", 9,
  7412. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7413. EXPECT_EQ(9u, length);
  7414. sink.write("123", 3);
  7415. sink.write("456", 3);
  7416. sink.write("789", 3);
  7417. return true;
  7418. },
  7419. "text/plain",
  7420. [&body](const char *data, size_t data_length) {
  7421. body.append(data, data_length);
  7422. return true;
  7423. });
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. EXPECT_EQ("123456789", body);
  7427. }
  7428. TEST_F(ServerTest, PatchLoopBack) {
  7429. std::string body;
  7430. auto res = cli_.Patch(
  7431. "/patch-loopback", 9,
  7432. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7433. EXPECT_EQ(9u, length);
  7434. sink.write("123", 3);
  7435. sink.write("456", 3);
  7436. sink.write("789", 3);
  7437. return true;
  7438. },
  7439. "text/plain",
  7440. [&body](const char *data, size_t data_length) {
  7441. body.append(data, data_length);
  7442. return true;
  7443. });
  7444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7445. EXPECT_EQ(StatusCode::OK_200, res->status);
  7446. EXPECT_EQ("123456789", body);
  7447. }
  7448. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7449. std::string body;
  7450. auto res = cli_.Post(
  7451. "/post-loopback",
  7452. [](size_t /*offset*/, DataSink &sink) {
  7453. sink.write("123", 3);
  7454. sink.write("456", 3);
  7455. sink.write("789", 3);
  7456. sink.done();
  7457. return true;
  7458. },
  7459. "text/plain",
  7460. [&body](const char *data, size_t data_length) {
  7461. body.append(data, data_length);
  7462. return true;
  7463. });
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ(StatusCode::OK_200, res->status);
  7466. EXPECT_EQ("123456789", body);
  7467. }
  7468. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7469. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7470. cli_.set_compress(true);
  7471. auto res = cli_.Put(
  7472. "/put", 3,
  7473. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7474. sink.os << "PUT";
  7475. return true;
  7476. },
  7477. "text/plain");
  7478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7479. EXPECT_EQ(StatusCode::OK_200, res->status);
  7480. EXPECT_EQ("PUT", res->body);
  7481. }
  7482. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7483. cli_.set_compress(true);
  7484. auto res = cli_.Post(
  7485. "/post", 42,
  7486. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7487. return false;
  7488. },
  7489. "text/plain");
  7490. ASSERT_TRUE(!res);
  7491. EXPECT_EQ(Error::Canceled, res.error());
  7492. }
  7493. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7494. cli_.set_compress(true);
  7495. auto res = cli_.Put(
  7496. "/put",
  7497. [](size_t /*offset*/, DataSink &sink) {
  7498. sink.os << "PUT";
  7499. sink.done();
  7500. return true;
  7501. },
  7502. "text/plain");
  7503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. EXPECT_EQ("PUT", res->body);
  7506. }
  7507. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7508. cli_.set_compress(true);
  7509. auto res = cli_.Post(
  7510. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7511. "text/plain");
  7512. ASSERT_TRUE(!res);
  7513. EXPECT_EQ(Error::Canceled, res.error());
  7514. }
  7515. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7516. cli_.set_compress(true);
  7517. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7519. EXPECT_EQ(StatusCode::OK_200, res->status);
  7520. EXPECT_EQ(LARGE_DATA, res->body);
  7521. }
  7522. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7523. #ifdef CPPHTTPLIB_SSL_ENABLED
  7524. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7525. Client cli(s.c_str());
  7526. cli.enable_server_certificate_verification(false);
  7527. #else
  7528. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7529. Client cli(s.c_str());
  7530. #endif
  7531. cli.set_compress(true);
  7532. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. EXPECT_EQ(StatusCode::OK_200, res->status);
  7535. EXPECT_EQ(LARGE_DATA, res->body);
  7536. // The compressed size should be less than a 10th of the original. May vary
  7537. // depending on the zlib library.
  7538. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7539. static_cast<uint64_t>(10 * 1024 * 1024));
  7540. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7541. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7542. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7543. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7544. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7545. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7546. #endif
  7547. }
  7548. TEST_F(ServerTest, PutContentWithDeflate) {
  7549. cli_.set_compress(false);
  7550. Headers headers;
  7551. headers.emplace("Content-Encoding", "deflate");
  7552. // PUT in deflate format:
  7553. auto res = cli_.Put("/put", headers,
  7554. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7556. EXPECT_EQ(StatusCode::OK_200, res->status);
  7557. EXPECT_EQ("PUT", res->body);
  7558. }
  7559. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7560. Headers headers;
  7561. headers.emplace("Accept-Encoding", "gzip, deflate");
  7562. auto res = cli_.Get("/streamed-chunked", headers);
  7563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7564. EXPECT_EQ(StatusCode::OK_200, res->status);
  7565. EXPECT_EQ(std::string("123456789"), res->body);
  7566. }
  7567. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7568. Headers headers;
  7569. headers.emplace("Accept-Encoding", "gzip, deflate");
  7570. auto res = cli_.Get("/streamed-chunked2", headers);
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. EXPECT_EQ(std::string("123456789"), res->body);
  7574. }
  7575. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7576. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7578. EXPECT_EQ(StatusCode::OK_200, res->status);
  7579. }
  7580. TEST(GzipDecompressor, ChunkedDecompression) {
  7581. std::string data;
  7582. for (size_t i = 0; i < 32 * 1024; ++i) {
  7583. data.push_back(static_cast<char>('a' + i % 26));
  7584. }
  7585. std::string compressed_data;
  7586. {
  7587. httplib::detail::gzip_compressor compressor;
  7588. bool result = compressor.compress(
  7589. data.data(), data.size(),
  7590. /*last=*/true,
  7591. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7592. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7593. compressed_data_size);
  7594. return true;
  7595. });
  7596. ASSERT_TRUE(result);
  7597. }
  7598. std::string decompressed_data;
  7599. {
  7600. httplib::detail::gzip_decompressor decompressor;
  7601. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7602. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7603. size_t chunk_size = 130;
  7604. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7605. chunk_begin += chunk_size) {
  7606. size_t current_chunk_size =
  7607. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7608. bool result = decompressor.decompress(
  7609. compressed_data.data() + chunk_begin, current_chunk_size,
  7610. [&](const char *decompressed_data_chunk,
  7611. size_t decompressed_data_chunk_size) {
  7612. decompressed_data.insert(decompressed_data.size(),
  7613. decompressed_data_chunk,
  7614. decompressed_data_chunk_size);
  7615. return true;
  7616. });
  7617. ASSERT_TRUE(result);
  7618. }
  7619. }
  7620. ASSERT_EQ(data, decompressed_data);
  7621. }
  7622. TEST(GzipDecompressor, DeflateDecompression) {
  7623. std::string original_text = "Raw deflate without gzip";
  7624. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7625. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7626. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7627. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7628. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7629. std::string decompressed_data;
  7630. {
  7631. httplib::detail::gzip_decompressor decompressor;
  7632. bool result = decompressor.decompress(
  7633. compressed_data.data(), compressed_data.size(),
  7634. [&](const char *decompressed_data_chunk,
  7635. size_t decompressed_data_chunk_size) {
  7636. decompressed_data.insert(decompressed_data.size(),
  7637. decompressed_data_chunk,
  7638. decompressed_data_chunk_size);
  7639. return true;
  7640. });
  7641. ASSERT_TRUE(result);
  7642. }
  7643. ASSERT_EQ(original_text, decompressed_data);
  7644. }
  7645. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7646. std::string original_text = "Raw deflate without gzip";
  7647. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7648. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7649. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7650. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7651. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7652. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7653. std::string decompressed_data;
  7654. {
  7655. httplib::detail::gzip_decompressor decompressor;
  7656. bool result = decompressor.decompress(
  7657. compressed_data.data(), compressed_data.size(),
  7658. [&](const char *decompressed_data_chunk,
  7659. size_t decompressed_data_chunk_size) {
  7660. decompressed_data.insert(decompressed_data.size(),
  7661. decompressed_data_chunk,
  7662. decompressed_data_chunk_size);
  7663. return true;
  7664. });
  7665. ASSERT_TRUE(result);
  7666. }
  7667. ASSERT_EQ(original_text, decompressed_data);
  7668. }
  7669. #endif
  7670. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7671. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7672. Headers headers;
  7673. headers.emplace("Accept-Encoding", "br");
  7674. auto res = cli_.Get("/streamed-chunked", headers);
  7675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7676. EXPECT_EQ(StatusCode::OK_200, res->status);
  7677. EXPECT_EQ(std::string("123456789"), res->body);
  7678. }
  7679. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7680. Headers headers;
  7681. headers.emplace("Accept-Encoding", "br");
  7682. auto res = cli_.Get("/streamed-chunked2", headers);
  7683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7684. EXPECT_EQ(StatusCode::OK_200, res->status);
  7685. EXPECT_EQ(std::string("123456789"), res->body);
  7686. }
  7687. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7688. cli_.set_compress(true);
  7689. auto res = cli_.Put(
  7690. "/put", 3,
  7691. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7692. sink.os << "PUT";
  7693. return true;
  7694. },
  7695. "text/plain");
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. EXPECT_EQ("PUT", res->body);
  7699. }
  7700. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7701. cli_.set_compress(true);
  7702. auto res = cli_.Put(
  7703. "/put",
  7704. [](size_t /*offset*/, DataSink &sink) {
  7705. sink.os << "PUT";
  7706. sink.done();
  7707. return true;
  7708. },
  7709. "text/plain");
  7710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7711. EXPECT_EQ(StatusCode::OK_200, res->status);
  7712. EXPECT_EQ("PUT", res->body);
  7713. }
  7714. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7715. cli_.set_compress(true);
  7716. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7718. EXPECT_EQ(StatusCode::OK_200, res->status);
  7719. EXPECT_EQ(LARGE_DATA, res->body);
  7720. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7721. }
  7722. #endif
  7723. TEST_F(ServerTest, Patch) {
  7724. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("PATCH", res->body);
  7728. }
  7729. TEST_F(ServerTest, Delete) {
  7730. auto res = cli_.Delete("/delete");
  7731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7732. EXPECT_EQ(StatusCode::OK_200, res->status);
  7733. EXPECT_EQ("DELETE", res->body);
  7734. }
  7735. TEST_F(ServerTest, DeleteContentReceiver) {
  7736. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7738. EXPECT_EQ(StatusCode::OK_200, res->status);
  7739. EXPECT_EQ("content", res->body);
  7740. }
  7741. TEST_F(ServerTest, Options) {
  7742. auto res = cli_.Options("*");
  7743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7744. EXPECT_EQ(StatusCode::OK_200, res->status);
  7745. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7746. EXPECT_TRUE(res->body.empty());
  7747. }
  7748. TEST_F(ServerTest, URL) {
  7749. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7751. EXPECT_EQ(StatusCode::OK_200, res->status);
  7752. }
  7753. TEST_F(ServerTest, ArrayParam) {
  7754. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7756. EXPECT_EQ(StatusCode::OK_200, res->status);
  7757. }
  7758. TEST_F(ServerTest, ArrayParamValues) {
  7759. auto res =
  7760. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. }
  7764. TEST_F(ServerTest, NoMultipleHeaders) {
  7765. Headers headers = {{"Content-Length", "5"}};
  7766. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7767. "text/plain");
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::OK_200, res->status);
  7770. }
  7771. TEST_F(ServerTest, PostContentReceiver) {
  7772. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7774. ASSERT_EQ(StatusCode::OK_200, res->status);
  7775. ASSERT_EQ("content", res->body);
  7776. }
  7777. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7778. UploadFormDataItems items = {
  7779. {"text1", "text default", "", ""},
  7780. {"text2", "aωb", "", ""},
  7781. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7782. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7783. {"file3", "", "", "application/octet-stream"},
  7784. };
  7785. auto res = cli_.Post("/content_receiver", items);
  7786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7787. EXPECT_EQ(StatusCode::OK_200, res->status);
  7788. }
  7789. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7790. UploadFormDataItems items = {
  7791. {"text1", "text default", "", ""},
  7792. {"text2", "aωb", "", ""},
  7793. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7794. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7795. {"file3", "", "", "application/octet-stream"},
  7796. };
  7797. auto boundary = std::string("+++++");
  7798. std::string body;
  7799. for (const auto &item : items) {
  7800. body += "--" + boundary + "\r\n";
  7801. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7802. if (!item.filename.empty()) {
  7803. body += "; filename=\"" + item.filename + "\"";
  7804. }
  7805. body += "\r\n";
  7806. if (!item.content_type.empty()) {
  7807. body += "Content-Type: " + item.content_type + "\r\n";
  7808. }
  7809. body += "\r\n";
  7810. body += item.content + "\r\n";
  7811. }
  7812. body += "--" + boundary + "--\r\n";
  7813. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7814. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7816. EXPECT_EQ(StatusCode::OK_200, res->status);
  7817. }
  7818. TEST(MultipartFormDataTest, FieldEscaping) {
  7819. Server svr;
  7820. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7821. const ContentReader &content_reader) {
  7822. ASSERT_TRUE(req.is_multipart_form_data());
  7823. std::vector<FormData> received;
  7824. content_reader(
  7825. [&](const FormData &file) {
  7826. received.push_back(file);
  7827. return true;
  7828. },
  7829. [&](const char *data, size_t data_length) {
  7830. received.back().content.append(data, data_length);
  7831. return true;
  7832. });
  7833. // '"', CR and LF in names and filenames are escaped following the
  7834. // WHATWG HTML standard, so each part still parses as a single part
  7835. // with no injected headers. Content types get CR/LF escaped too,
  7836. // while '"' (legal there, e.g. quoted charset) is preserved.
  7837. ASSERT_EQ(4U, received.size());
  7838. EXPECT_EQ("na%22me", received[0].name);
  7839. EXPECT_EQ("quoted name", received[0].content);
  7840. EXPECT_EQ("file", received[1].name);
  7841. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7842. received[1].filename);
  7843. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7844. EXPECT_EQ("injected", received[1].content);
  7845. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7846. EXPECT_EQ("my%22file.txt", received[2].filename);
  7847. EXPECT_EQ("cr lf name", received[2].content);
  7848. EXPECT_EQ("typed", received[3].name);
  7849. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7850. received[3].content_type);
  7851. EXPECT_EQ("typed content", received[3].content);
  7852. });
  7853. auto port = svr.bind_to_any_port("localhost");
  7854. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7855. auto se = detail::scope_exit([&] {
  7856. svr.stop();
  7857. t.join();
  7858. ASSERT_FALSE(svr.is_running());
  7859. });
  7860. svr.wait_until_ready();
  7861. Client cli("localhost", port);
  7862. UploadFormDataItems items = {
  7863. {"na\"me", "quoted name", "", ""},
  7864. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7865. "application/octet-stream"},
  7866. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7867. {"typed", "typed content", "",
  7868. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7869. };
  7870. auto res = cli.Post("/post", items);
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::OK_200, res->status);
  7873. }
  7874. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7875. const UploadFormDataItems items = {
  7876. {"name1", "Content 1", "", ""},
  7877. {"name2", "Content 2", "file2.txt", "text/plain"},
  7878. };
  7879. Server svr;
  7880. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7881. const ContentReader &content_reader) {
  7882. ASSERT_TRUE(req.is_multipart_form_data());
  7883. std::vector<FormData> received;
  7884. content_reader(
  7885. [&](const FormData &file) {
  7886. received.push_back(file);
  7887. return true;
  7888. },
  7889. [&](const char *data, size_t data_length) {
  7890. received.back().content.append(data, data_length);
  7891. return true;
  7892. });
  7893. ASSERT_EQ(2U, received.size());
  7894. EXPECT_EQ("name1", received[0].name);
  7895. EXPECT_EQ("Content 1", received[0].content);
  7896. EXPECT_EQ("name2", received[1].name);
  7897. EXPECT_EQ("Content 2", received[1].content);
  7898. EXPECT_EQ("file2.txt", received[1].filename);
  7899. EXPECT_EQ("text/plain", received[1].content_type);
  7900. });
  7901. auto port = svr.bind_to_any_port("localhost");
  7902. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7903. auto se = detail::scope_exit([&] {
  7904. svr.stop();
  7905. t.join();
  7906. ASSERT_FALSE(svr.is_running());
  7907. });
  7908. svr.wait_until_ready();
  7909. Client cli("localhost", port);
  7910. // Whole-body serialization with a generated boundary
  7911. {
  7912. MultipartFormDataWriter writer;
  7913. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7914. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7915. writer.content_type());
  7916. auto body = writer.serialize(items);
  7917. EXPECT_EQ(body.size(), writer.content_length(items));
  7918. auto res = cli.Post("/post", body, writer.content_type());
  7919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7920. EXPECT_EQ(StatusCode::OK_200, res->status);
  7921. }
  7922. // Per-part framing with a custom boundary via a content provider
  7923. {
  7924. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7925. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7926. MultipartFormDataWriter writer("custom-boundary_123");
  7927. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7928. std::string body;
  7929. for (const auto &item : items) {
  7930. body += writer.item_begin(item);
  7931. body += item.content;
  7932. body += MultipartFormDataWriter::item_end();
  7933. }
  7934. body += writer.finish();
  7935. EXPECT_EQ(body.size(), writer.content_length(items));
  7936. auto res = cli.Post(
  7937. "/post", body.size(),
  7938. [&](size_t offset, size_t length, DataSink &sink) {
  7939. sink.write(body.data() + offset, length);
  7940. return true;
  7941. },
  7942. writer.content_type());
  7943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7944. EXPECT_EQ(StatusCode::OK_200, res->status);
  7945. }
  7946. }
  7947. TEST_F(ServerTest, PostContentReceiverGzip) {
  7948. cli_.set_compress(true);
  7949. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7951. ASSERT_EQ(StatusCode::OK_200, res->status);
  7952. ASSERT_EQ("content", res->body);
  7953. }
  7954. TEST_F(ServerTest, PutContentReceiver) {
  7955. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. ASSERT_EQ(StatusCode::OK_200, res->status);
  7958. ASSERT_EQ("content", res->body);
  7959. }
  7960. TEST_F(ServerTest, PatchContentReceiver) {
  7961. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7963. ASSERT_EQ(StatusCode::OK_200, res->status);
  7964. ASSERT_EQ("content", res->body);
  7965. }
  7966. template <typename ClientType>
  7967. void TestWithHeadersAndContentReceiver(
  7968. ClientType &cli,
  7969. std::function<Result(ClientType &, const std::string &, const Headers &,
  7970. const std::string &, const std::string &,
  7971. ContentReceiver, DownloadProgress)>
  7972. request_func) {
  7973. Headers headers;
  7974. headers.emplace("X-Custom-Header", "test-value");
  7975. std::string received_body;
  7976. auto res = request_func(
  7977. cli, "/content_receiver", headers, "content", "application/json",
  7978. [&](const char *data, size_t data_length) {
  7979. received_body.append(data, data_length);
  7980. return true;
  7981. },
  7982. nullptr);
  7983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. EXPECT_EQ("content", received_body);
  7986. }
  7987. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7988. #ifdef CPPHTTPLIB_SSL_ENABLED
  7989. using ClientT = SSLClient;
  7990. #else
  7991. using ClientT = Client;
  7992. #endif
  7993. TestWithHeadersAndContentReceiver<ClientT>(
  7994. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7995. const std::string &body, const std::string &content_type,
  7996. ContentReceiver receiver, DownloadProgress progress) {
  7997. return cli.Post(path, headers, body, content_type, receiver, progress);
  7998. });
  7999. }
  8000. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8001. #ifdef CPPHTTPLIB_SSL_ENABLED
  8002. using ClientT = SSLClient;
  8003. #else
  8004. using ClientT = Client;
  8005. #endif
  8006. TestWithHeadersAndContentReceiver<ClientT>(
  8007. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8008. const std::string &body, const std::string &content_type,
  8009. ContentReceiver receiver, DownloadProgress progress) {
  8010. return cli.Put(path, headers, body, content_type, receiver, progress);
  8011. });
  8012. }
  8013. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8014. #ifdef CPPHTTPLIB_SSL_ENABLED
  8015. using ClientT = SSLClient;
  8016. #else
  8017. using ClientT = Client;
  8018. #endif
  8019. TestWithHeadersAndContentReceiver<ClientT>(
  8020. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8021. const std::string &body, const std::string &content_type,
  8022. ContentReceiver receiver, DownloadProgress progress) {
  8023. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8024. });
  8025. }
  8026. template <typename ClientType>
  8027. void TestWithHeadersAndContentReceiverWithProgress(
  8028. ClientType &cli,
  8029. std::function<Result(ClientType &, const std::string &, const Headers &,
  8030. const std::string &, const std::string &,
  8031. ContentReceiver, DownloadProgress)>
  8032. request_func) {
  8033. Headers headers;
  8034. headers.emplace("X-Test-Header", "progress-test");
  8035. std::string received_body;
  8036. auto progress_called = false;
  8037. auto res = request_func(
  8038. cli, "/content_receiver", headers, "content", "text/plain",
  8039. [&](const char *data, size_t data_length) {
  8040. received_body.append(data, data_length);
  8041. return true;
  8042. },
  8043. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8044. progress_called = true;
  8045. return true;
  8046. });
  8047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8048. EXPECT_EQ(StatusCode::OK_200, res->status);
  8049. EXPECT_EQ("content", received_body);
  8050. EXPECT_TRUE(progress_called);
  8051. }
  8052. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8053. #ifdef CPPHTTPLIB_SSL_ENABLED
  8054. using ClientT = SSLClient;
  8055. #else
  8056. using ClientT = Client;
  8057. #endif
  8058. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8059. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8060. const std::string &body, const std::string &content_type,
  8061. ContentReceiver receiver, DownloadProgress progress) {
  8062. return cli.Post(path, headers, body, content_type, receiver, progress);
  8063. });
  8064. }
  8065. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8066. #ifdef CPPHTTPLIB_SSL_ENABLED
  8067. using ClientT = SSLClient;
  8068. #else
  8069. using ClientT = Client;
  8070. #endif
  8071. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8072. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8073. const std::string &body, const std::string &content_type,
  8074. ContentReceiver receiver, DownloadProgress progress) {
  8075. return cli.Put(path, headers, body, content_type, receiver, progress);
  8076. });
  8077. }
  8078. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8079. #ifdef CPPHTTPLIB_SSL_ENABLED
  8080. using ClientT = SSLClient;
  8081. #else
  8082. using ClientT = Client;
  8083. #endif
  8084. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8085. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8086. const std::string &body, const std::string &content_type,
  8087. ContentReceiver receiver, DownloadProgress progress) {
  8088. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8089. });
  8090. }
  8091. template <typename ClientType>
  8092. void TestWithHeadersAndContentReceiverError(
  8093. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8094. const Headers &, const std::string &,
  8095. const std::string &, ContentReceiver)>
  8096. request_func) {
  8097. Headers headers;
  8098. headers.emplace("X-Error-Test", "true");
  8099. std::string received_body;
  8100. auto receiver_failed = false;
  8101. auto res =
  8102. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8103. [&](const char *data, size_t data_length) {
  8104. received_body.append(data, data_length);
  8105. receiver_failed = true;
  8106. return false;
  8107. });
  8108. ASSERT_FALSE(res);
  8109. EXPECT_TRUE(receiver_failed);
  8110. }
  8111. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8112. #ifdef CPPHTTPLIB_SSL_ENABLED
  8113. using ClientT = SSLClient;
  8114. #else
  8115. using ClientT = Client;
  8116. #endif
  8117. TestWithHeadersAndContentReceiverError<ClientT>(
  8118. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8119. const std::string &body, const std::string &content_type,
  8120. ContentReceiver receiver) {
  8121. return cli.Post(path, headers, body, content_type, receiver);
  8122. });
  8123. }
  8124. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8125. #ifdef CPPHTTPLIB_SSL_ENABLED
  8126. using ClientT = SSLClient;
  8127. #else
  8128. using ClientT = Client;
  8129. #endif
  8130. TestWithHeadersAndContentReceiverError<ClientT>(
  8131. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8132. const std::string &body, const std::string &content_type,
  8133. ContentReceiver receiver) {
  8134. return cli.Put(path, headers, body, content_type, receiver);
  8135. });
  8136. }
  8137. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8138. #ifdef CPPHTTPLIB_SSL_ENABLED
  8139. using ClientT = SSLClient;
  8140. #else
  8141. using ClientT = Client;
  8142. #endif
  8143. TestWithHeadersAndContentReceiverError<ClientT>(
  8144. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8145. const std::string &body, const std::string &content_type,
  8146. ContentReceiver receiver) {
  8147. return cli.Patch(path, headers, body, content_type, receiver);
  8148. });
  8149. }
  8150. TEST_F(ServerTest, PostQueryStringAndBody) {
  8151. auto res =
  8152. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8154. ASSERT_EQ(StatusCode::OK_200, res->status);
  8155. }
  8156. TEST_F(ServerTest, HTTP2Magic) {
  8157. Request req;
  8158. req.method = "PRI";
  8159. req.path = "*";
  8160. req.body = "SM";
  8161. auto res = std::make_shared<Response>();
  8162. auto error = Error::Success;
  8163. auto ret = cli_.send(req, *res, error);
  8164. ASSERT_TRUE(ret);
  8165. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8166. }
  8167. TEST_F(ServerTest, KeepAlive) {
  8168. auto res = cli_.Get("/hi");
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. EXPECT_EQ(StatusCode::OK_200, res->status);
  8171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8172. EXPECT_EQ("Hello World!", res->body);
  8173. res = cli_.Get("/hi");
  8174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8175. EXPECT_EQ(StatusCode::OK_200, res->status);
  8176. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8177. EXPECT_EQ("Hello World!", res->body);
  8178. res = cli_.Get("/hi");
  8179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8180. EXPECT_EQ(StatusCode::OK_200, res->status);
  8181. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8182. EXPECT_EQ("Hello World!", res->body);
  8183. res = cli_.Get("/not-exist");
  8184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8185. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8186. res = cli_.Post("/empty", "", "text/plain");
  8187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8188. EXPECT_EQ(StatusCode::OK_200, res->status);
  8189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8190. EXPECT_EQ("empty", res->body);
  8191. EXPECT_EQ("close", res->get_header_value("Connection"));
  8192. res = cli_.Post(
  8193. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8194. "text/plain");
  8195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8196. EXPECT_EQ(StatusCode::OK_200, res->status);
  8197. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8198. EXPECT_EQ("empty", res->body);
  8199. cli_.set_keep_alive(false);
  8200. res = cli_.Get("/last-request");
  8201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8202. EXPECT_EQ(StatusCode::OK_200, res->status);
  8203. EXPECT_EQ("close", res->get_header_value("Connection"));
  8204. }
  8205. TEST_F(ServerTest, TooManyRedirect) {
  8206. cli_.set_follow_location(true);
  8207. auto res = cli_.Get("/redirect/0");
  8208. ASSERT_TRUE(!res);
  8209. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8210. }
  8211. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8212. Request req;
  8213. req.method = "FOOBAR";
  8214. req.path = "/hi";
  8215. cli_.set_keep_alive(true);
  8216. auto res = cli_.send(req);
  8217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8218. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8219. EXPECT_EQ("close", res->get_header_value("Connection"));
  8220. EXPECT_FALSE(cli_.is_socket_open());
  8221. }
  8222. TEST_F(ServerTest, CustomRouteReadsBody) {
  8223. const std::string xml =
  8224. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8225. Request req;
  8226. req.method = "PROPFIND";
  8227. req.path = "/dav/dir";
  8228. req.set_header("Depth", "1");
  8229. req.body = xml;
  8230. auto res = cli_.send(req);
  8231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8232. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8233. EXPECT_EQ(xml, res->body);
  8234. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8235. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8236. }
  8237. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8238. Request req;
  8239. req.method = "PROPFIND";
  8240. req.path = "/dav/42";
  8241. auto res = cli_.send(req);
  8242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8243. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8244. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8245. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8246. }
  8247. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8248. Request req;
  8249. req.method = "PROPFIND";
  8250. req.path = "/dav-re/123";
  8251. auto res = cli_.send(req);
  8252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8253. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8254. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8255. }
  8256. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8257. Request req;
  8258. req.method = "MKCOL";
  8259. req.path = "/dav-mkcol";
  8260. auto res = cli_.send(req);
  8261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8262. EXPECT_EQ(StatusCode::Created_201, res->status);
  8263. }
  8264. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8265. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8266. Request req;
  8267. req.method = "REPORT";
  8268. req.path = "/dav-report";
  8269. req.body = xml;
  8270. auto res = cli_.send(req);
  8271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8272. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8273. EXPECT_EQ(xml, res->body);
  8274. }
  8275. // A content reader route must fire even when the request carries no body,
  8276. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8277. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8278. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8279. Request req;
  8280. req.method = "REPORT";
  8281. req.path = "/dav-report";
  8282. auto res = cli_.send(req);
  8283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8284. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8285. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8286. }
  8287. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8288. Request req;
  8289. req.method = "PROPFIND";
  8290. req.path = "/not-dav";
  8291. auto res = cli_.send(req);
  8292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8294. }
  8295. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8296. Request req;
  8297. req.method = "UNLOCK";
  8298. req.path = "/dav/dir";
  8299. cli_.set_keep_alive(true);
  8300. auto res = cli_.send(req);
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8303. EXPECT_EQ("close", res->get_header_value("Connection"));
  8304. EXPECT_FALSE(cli_.is_socket_open());
  8305. }
  8306. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8307. // The mount point serves this path, but only for GET and HEAD.
  8308. auto get_res = cli_.Get("/dir/index.html");
  8309. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8310. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8311. Request req;
  8312. req.method = "PROPFIND";
  8313. req.path = "/dir/index.html";
  8314. auto res = cli_.send(req);
  8315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8316. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8317. }
  8318. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8319. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8320. cli_.set_keep_alive(true);
  8321. for (auto i = 0; i < 2; i++) {
  8322. Request req;
  8323. req.method = "PROPFIND";
  8324. req.path = "/dav/dir";
  8325. req.body = xml;
  8326. auto res = cli_.send(req);
  8327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8328. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8329. EXPECT_EQ(xml, res->body);
  8330. EXPECT_TRUE(cli_.is_socket_open());
  8331. }
  8332. // A built-in method must still be served on the same connection.
  8333. cli_.set_keep_alive(false);
  8334. auto res = cli_.Get("/hi");
  8335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8336. EXPECT_EQ(StatusCode::OK_200, res->status);
  8337. EXPECT_EQ("close", res->get_header_value("Connection"));
  8338. }
  8339. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8340. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8341. Request req;
  8342. req.method = "PROPFIND";
  8343. req.path = "/dav/dir";
  8344. req.set_header("Expect", "100-continue");
  8345. req.body = xml;
  8346. auto res = cli_.send(req);
  8347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8348. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8349. EXPECT_EQ(xml, res->body);
  8350. }
  8351. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8352. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8353. TEST_F(ServerTest, Gzip) {
  8354. Headers headers;
  8355. headers.emplace("Accept-Encoding", "gzip, deflate");
  8356. auto res = cli_.Get("/compress", headers);
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8359. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8360. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8361. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8362. "7890123456789012345678901234567890",
  8363. res->body);
  8364. EXPECT_EQ(StatusCode::OK_200, res->status);
  8365. }
  8366. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8367. Headers headers;
  8368. headers.emplace("Accept-Encoding", "gzip, deflate");
  8369. auto res = cli_.Get("/compress-with-charset", headers);
  8370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8371. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8372. EXPECT_EQ("application/json; charset=utf-8",
  8373. res->get_header_value("Content-Type"));
  8374. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8375. "7890123456789012345678901234567890",
  8376. res->body);
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. }
  8379. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8380. Headers headers;
  8381. headers.emplace("Accept-Encoding", "");
  8382. auto res = cli_.Get("/compress", headers);
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8386. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8387. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8388. "7890123456789012345678901234567890",
  8389. res->body);
  8390. EXPECT_EQ(StatusCode::OK_200, res->status);
  8391. }
  8392. TEST_F(ServerTest, GzipWithContentReceiver) {
  8393. Headers headers;
  8394. headers.emplace("Accept-Encoding", "gzip, deflate");
  8395. std::string body;
  8396. auto res =
  8397. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8398. EXPECT_EQ(100U, data_length);
  8399. body.append(data, data_length);
  8400. return true;
  8401. });
  8402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8403. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8404. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8405. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8406. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8407. "7890123456789012345678901234567890",
  8408. body);
  8409. EXPECT_EQ(StatusCode::OK_200, res->status);
  8410. }
  8411. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8412. Headers headers;
  8413. headers.emplace("Accept-Encoding", "gzip, deflate");
  8414. cli_.set_decompress(false);
  8415. auto res = cli_.Get("/compress", headers);
  8416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8417. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8418. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8419. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8420. EXPECT_EQ(33U, res->body.size());
  8421. EXPECT_EQ(StatusCode::OK_200, res->status);
  8422. }
  8423. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8424. Headers headers;
  8425. headers.emplace("Accept-Encoding", "");
  8426. std::string body;
  8427. auto res =
  8428. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8429. EXPECT_EQ(100U, data_length);
  8430. body.append(data, data_length);
  8431. return true;
  8432. });
  8433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8434. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8435. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8436. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8437. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8438. "7890123456789012345678901234567890",
  8439. body);
  8440. EXPECT_EQ(StatusCode::OK_200, res->status);
  8441. }
  8442. TEST_F(ServerTest, NoGzip) {
  8443. Headers headers;
  8444. headers.emplace("Accept-Encoding", "gzip, deflate");
  8445. auto res = cli_.Get("/nocompress", headers);
  8446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8447. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8448. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8449. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8450. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8451. "7890123456789012345678901234567890",
  8452. res->body);
  8453. EXPECT_EQ(StatusCode::OK_200, res->status);
  8454. }
  8455. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8456. Headers headers;
  8457. headers.emplace("Accept-Encoding", "gzip, deflate");
  8458. std::string body;
  8459. auto res = cli_.Get("/nocompress", headers,
  8460. [&](const char *data, size_t data_length) {
  8461. EXPECT_EQ(100U, data_length);
  8462. body.append(data, data_length);
  8463. return true;
  8464. });
  8465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8466. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8467. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8468. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8469. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8470. "7890123456789012345678901234567890",
  8471. body);
  8472. EXPECT_EQ(StatusCode::OK_200, res->status);
  8473. }
  8474. TEST_F(ServerTest, MultipartFormDataGzip) {
  8475. UploadFormDataItems items = {
  8476. {"key1", "test", "", ""},
  8477. {"key2", "--abcdefg123", "", ""},
  8478. };
  8479. cli_.set_compress(true);
  8480. auto res = cli_.Post("/compress-multipart", items);
  8481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8482. EXPECT_EQ(StatusCode::OK_200, res->status);
  8483. }
  8484. #endif
  8485. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8486. // Static file compression is opt-in, so these run their own server rather than
  8487. // flipping it on for the shared ServerTest fixture, which would silently
  8488. // rewrite what every other static file test is asserting.
  8489. class StaticFileCompressionTest : public ::testing::Test {
  8490. protected:
  8491. void TearDown() override {
  8492. if (t_.joinable()) {
  8493. svr_.stop();
  8494. t_.join();
  8495. }
  8496. }
  8497. int start(const std::function<void(Server &)> &configure = nullptr) {
  8498. // Serves the same tree as a directory of build-time compressed assets
  8499. // would be served: the mount point names the coding the files are already
  8500. // stored in. Registered before "/" so it is the one that matches.
  8501. svr_.set_mount_point("/pre-encoded", "./www",
  8502. {{"Content-Encoding", "gzip"}});
  8503. svr_.set_mount_point("/", "./www");
  8504. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8505. res.set_file_content("./www/dir/index.html", "text/html");
  8506. });
  8507. svr_.Get("/pre-encoded-file-content",
  8508. [](const Request & /*req*/, Response &res) {
  8509. res.set_header("Content-Encoding", "gzip");
  8510. res.set_file_content("./www/dir/index.html", "text/html");
  8511. });
  8512. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8513. res.set_content_provider(
  8514. 6, "text/plain",
  8515. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8516. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8517. return true;
  8518. });
  8519. });
  8520. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8521. res.set_content_provider(
  8522. 1000, "text/plain",
  8523. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8524. if (offset < 100) {
  8525. std::string data(100, 'A');
  8526. sink.write(data.data(), data.size());
  8527. return true;
  8528. }
  8529. std::this_thread::sleep_for(std::chrono::seconds(2));
  8530. std::string data(900, 'B');
  8531. sink.write(data.data(), data.size());
  8532. return true;
  8533. });
  8534. });
  8535. if (configure) { configure(svr_); }
  8536. auto port = svr_.bind_to_any_port(HOST);
  8537. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8538. svr_.wait_until_ready();
  8539. return port;
  8540. }
  8541. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8542. // Every file under ./www except 1MB.txt is smaller than the default
  8543. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8544. // it out of the way.
  8545. static void enable_without_floor(Server &svr) {
  8546. svr.set_static_file_compression(true);
  8547. svr.set_static_file_compression_min_length(0);
  8548. }
  8549. Server svr_;
  8550. std::thread t_;
  8551. };
  8552. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8553. auto port = start();
  8554. Client cli(HOST, port);
  8555. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8557. EXPECT_EQ(StatusCode::OK_200, res->status);
  8558. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8559. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8560. EXPECT_EQ(1048576U, res->body.size());
  8561. }
  8562. TEST_F(StaticFileCompressionTest, MountPoint) {
  8563. auto port = start(enable);
  8564. Client cli(HOST, port);
  8565. cli.set_decompress(false);
  8566. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8568. EXPECT_EQ(StatusCode::OK_200, res->status);
  8569. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8570. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8571. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8572. // The response stays self-delimiting: a length, not a chunked body.
  8573. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8574. EXPECT_EQ(std::to_string(res->body.size()),
  8575. res->get_header_value("Content-Length"));
  8576. EXPECT_LT(res->body.size(), 1048576U);
  8577. EXPECT_FALSE(res->body.empty());
  8578. }
  8579. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8580. auto port = start(enable);
  8581. Client cli(HOST, port);
  8582. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8584. EXPECT_EQ(StatusCode::OK_200, res->status);
  8585. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8586. EXPECT_EQ(1048576U, res->body.size());
  8587. }
  8588. TEST_F(StaticFileCompressionTest, FileContent) {
  8589. auto port = start(enable_without_floor);
  8590. Client cli(HOST, port);
  8591. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8593. EXPECT_EQ(StatusCode::OK_200, res->status);
  8594. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8595. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8596. EXPECT_EQ(104U, res->body.size());
  8597. }
  8598. // A handler that serves an already-encoded file names the coding itself. The
  8599. // file-backed path decided its coding from Accept-Encoding and the content
  8600. // type alone, so it compressed the stored bytes a second time and appended a
  8601. // second Content-Encoding field line.
  8602. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8603. auto port = start(enable_without_floor);
  8604. Client cli(HOST, port);
  8605. cli.set_decompress(false);
  8606. auto res = cli.Get("/pre-encoded-file-content",
  8607. Headers{{"Accept-Encoding", "gzip"}});
  8608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8609. EXPECT_EQ(StatusCode::OK_200, res->status);
  8610. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8611. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8612. // Vary belongs to a coding the server chose, and it chose none here.
  8613. EXPECT_FALSE(res->has_header("Vary"));
  8614. // The file travels exactly as it is stored on disk.
  8615. EXPECT_EQ(104U, res->body.size());
  8616. }
  8617. // The 1MB file clears the default floor, so this one runs the configuration a
  8618. // deployment would actually have.
  8619. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8620. auto port = start(enable);
  8621. Client cli(HOST, port);
  8622. cli.set_decompress(false);
  8623. auto res =
  8624. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8626. EXPECT_EQ(StatusCode::OK_200, res->status);
  8627. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8628. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8629. EXPECT_FALSE(res->has_header("Vary"));
  8630. EXPECT_EQ(1048576U, res->body.size());
  8631. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8632. }
  8633. TEST_F(StaticFileCompressionTest, Head) {
  8634. auto port = start(enable);
  8635. Client cli(HOST, port);
  8636. cli.set_decompress(false);
  8637. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8638. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8639. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8641. EXPECT_EQ(StatusCode::OK_200, res->status);
  8642. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8643. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8644. // HEAD still reports the size a GET would return.
  8645. EXPECT_EQ(get->get_header_value("Content-Length"),
  8646. res->get_header_value("Content-Length"));
  8647. EXPECT_TRUE(res->body.empty());
  8648. }
  8649. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8650. auto port = start(enable);
  8651. Client cli(HOST, port);
  8652. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8653. {"Accept-Encoding", "gzip"}});
  8654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8655. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8656. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8657. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8658. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8659. EXPECT_EQ("cd", res->body);
  8660. }
  8661. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8662. auto port = start(enable);
  8663. Client cli(HOST, port);
  8664. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8666. EXPECT_EQ(StatusCode::OK_200, res->status);
  8667. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8668. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8669. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8670. }
  8671. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8672. auto port = start(enable);
  8673. Client cli(HOST, port);
  8674. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8676. EXPECT_EQ(StatusCode::OK_200, res->status);
  8677. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8678. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8679. EXPECT_TRUE(res->body.empty());
  8680. }
  8681. TEST_F(StaticFileCompressionTest, MinLength) {
  8682. auto port = start(enable);
  8683. Client cli(HOST, port);
  8684. // 104 bytes, well under the default floor. Compressing it would add the
  8685. // gzip header and trailer to a body that already fits in one packet.
  8686. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8688. EXPECT_EQ(StatusCode::OK_200, res->status);
  8689. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8690. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8691. }
  8692. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8693. auto port = start([](Server &svr) {
  8694. svr.set_static_file_compression(true);
  8695. svr.set_static_file_compression_min_length(1);
  8696. });
  8697. Client cli(HOST, port);
  8698. cli.set_decompress(false);
  8699. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8701. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8702. // A 9-byte file comes back larger than it went in, because gzip's header and
  8703. // trailer outweigh anything deflate can save. That is the end of the range
  8704. // the floor exists to keep out.
  8705. EXPECT_GT(res->body.size(), 9U);
  8706. }
  8707. TEST_F(StaticFileCompressionTest, MaxLength) {
  8708. auto port = start([](Server &svr) {
  8709. svr.set_static_file_compression(true);
  8710. svr.set_static_file_compression_min_length(0);
  8711. svr.set_static_file_compression_max_length(1024);
  8712. });
  8713. Client cli(HOST, port);
  8714. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8715. // defines `small` as a macro on Windows.
  8716. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8717. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8718. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8719. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8720. // Under it: compressed.
  8721. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8722. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8723. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8724. }
  8725. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8726. auto port = start(enable_without_floor);
  8727. Client cli(HOST, port);
  8728. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8729. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8730. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8731. auto identity_etag = identity->get_header_value("ETag");
  8732. ASSERT_FALSE(identity_etag.empty());
  8733. auto gzipped =
  8734. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8735. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8736. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8737. auto gzip_etag = gzipped->get_header_value("ETag");
  8738. ASSERT_FALSE(gzip_etag.empty());
  8739. // Two representations, two validators.
  8740. EXPECT_NE(identity_etag, gzip_etag);
  8741. // Each one revalidates against the request that would produce it...
  8742. auto fresh =
  8743. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8744. {"If-None-Match", gzip_etag}});
  8745. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8746. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8747. auto fresh_identity =
  8748. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8749. {"If-None-Match", identity_etag}});
  8750. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8751. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8752. // ...and not against the other representation.
  8753. auto crossed =
  8754. cli.Get("/dir/index.html",
  8755. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8756. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8757. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8758. }
  8759. // The opt-in covers responses the server reads off disk itself. A caller's own
  8760. // known-length provider keeps its Content-Length and, more importantly, keeps
  8761. // delivering incrementally: routing it through a compressor would hold every
  8762. // write back until zlib's window filled.
  8763. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8764. auto port = start(enable);
  8765. Client cli(HOST, port);
  8766. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8768. EXPECT_EQ(StatusCode::OK_200, res->status);
  8769. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8770. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8771. EXPECT_EQ("aaabbb", res->body);
  8772. }
  8773. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8774. auto port = start(enable);
  8775. Client cli(HOST, port);
  8776. cli.set_read_timeout(1, 0);
  8777. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8778. Headers{{"Accept-Encoding", "gzip"}});
  8779. ASSERT_TRUE(handle.is_valid());
  8780. // The provider writes 100 bytes and then stalls for longer than the read
  8781. // timeout. Those first bytes have to arrive anyway: run the response through
  8782. // a compressor and zlib holds them until its window fills, so the read would
  8783. // come back empty instead.
  8784. char buf[256];
  8785. auto n = handle.read(buf, sizeof(buf));
  8786. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8787. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8788. }
  8789. #endif
  8790. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8791. TEST_F(ServerTest, Brotli) {
  8792. Headers headers;
  8793. headers.emplace("Accept-Encoding", "br");
  8794. auto res = cli_.Get("/compress", headers);
  8795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8796. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8797. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8798. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8799. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8800. "7890123456789012345678901234567890",
  8801. res->body);
  8802. EXPECT_EQ(StatusCode::OK_200, res->status);
  8803. }
  8804. #endif
  8805. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8806. TEST_F(ServerTest, Zstd) {
  8807. Headers headers;
  8808. headers.emplace("Accept-Encoding", "zstd");
  8809. auto res = cli_.Get("/compress", headers);
  8810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8811. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8812. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8813. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8814. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8815. "7890123456789012345678901234567890",
  8816. res->body);
  8817. EXPECT_EQ(StatusCode::OK_200, res->status);
  8818. }
  8819. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8820. Headers headers;
  8821. headers.emplace("Accept-Encoding", "");
  8822. auto res = cli_.Get("/compress", headers);
  8823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8824. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8826. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8827. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8828. "7890123456789012345678901234567890",
  8829. res->body);
  8830. EXPECT_EQ(StatusCode::OK_200, res->status);
  8831. }
  8832. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8833. Headers headers;
  8834. headers.emplace("Accept-Encoding", "zstd");
  8835. std::string body;
  8836. auto res =
  8837. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8838. EXPECT_EQ(100U, data_length);
  8839. body.append(data, data_length);
  8840. return true;
  8841. });
  8842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8843. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8844. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8845. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8846. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8847. "7890123456789012345678901234567890",
  8848. body);
  8849. EXPECT_EQ(StatusCode::OK_200, res->status);
  8850. }
  8851. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8852. Headers headers;
  8853. headers.emplace("Accept-Encoding", "zstd");
  8854. cli_.set_decompress(false);
  8855. auto res = cli_.Get("/compress", headers);
  8856. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8857. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8858. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8859. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8861. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8862. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8863. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8864. EXPECT_EQ(StatusCode::OK_200, res->status);
  8865. ASSERT_EQ(26U, res->body.size());
  8866. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8867. 0);
  8868. }
  8869. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8870. Headers headers;
  8871. headers.emplace("Accept-Encoding", "");
  8872. std::string body;
  8873. auto res =
  8874. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8875. EXPECT_EQ(100U, data_length);
  8876. body.append(data, data_length);
  8877. return true;
  8878. });
  8879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8880. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8881. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8882. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8883. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8884. "7890123456789012345678901234567890",
  8885. body);
  8886. EXPECT_EQ(StatusCode::OK_200, res->status);
  8887. }
  8888. TEST_F(ServerTest, NoZstd) {
  8889. Headers headers;
  8890. headers.emplace("Accept-Encoding", "zstd");
  8891. auto res = cli_.Get("/nocompress", headers);
  8892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8893. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8894. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8895. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8896. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8897. "7890123456789012345678901234567890",
  8898. res->body);
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. }
  8901. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8902. Headers headers;
  8903. headers.emplace("Accept-Encoding", "zstd");
  8904. std::string body;
  8905. auto res = cli_.Get("/nocompress", headers,
  8906. [&](const char *data, size_t data_length) {
  8907. EXPECT_EQ(100U, data_length);
  8908. body.append(data, data_length);
  8909. return true;
  8910. });
  8911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8912. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8913. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8914. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8915. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8916. "7890123456789012345678901234567890",
  8917. body);
  8918. EXPECT_EQ(StatusCode::OK_200, res->status);
  8919. }
  8920. // TODO: How to enable zstd ??
  8921. TEST_F(ServerTest, MultipartFormDataZstd) {
  8922. UploadFormDataItems items = {
  8923. {"key1", "test", "", ""},
  8924. {"key2", "--abcdefg123", "", ""},
  8925. };
  8926. Headers headers;
  8927. headers.emplace("Accept-Encoding", "zstd");
  8928. cli_.set_compress(true);
  8929. auto res = cli_.Post("/compress-multipart", headers, items);
  8930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8931. EXPECT_EQ(StatusCode::OK_200, res->status);
  8932. }
  8933. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8934. Headers headers;
  8935. headers.emplace("Accept-Encoding", "zstd");
  8936. cli_.set_compress(true);
  8937. auto res = cli_.Put(
  8938. "/put", headers, 3,
  8939. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8940. sink.os << "PUT";
  8941. return true;
  8942. },
  8943. "text/plain");
  8944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8945. EXPECT_EQ(StatusCode::OK_200, res->status);
  8946. EXPECT_EQ("PUT", res->body);
  8947. }
  8948. // Pre-compression logging tests
  8949. TEST_F(ServerTest, PreCompressionLogging) {
  8950. // Test data for compression (matches the actual /compress endpoint content)
  8951. const std::string test_content =
  8952. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8953. "3456789012345678901234567890";
  8954. // Variables to capture logging data
  8955. std::string pre_compression_body;
  8956. std::string pre_compression_content_type;
  8957. std::string pre_compression_content_encoding;
  8958. std::string post_compression_body;
  8959. std::string post_compression_content_type;
  8960. std::string post_compression_content_encoding;
  8961. // Set up pre-compression logger
  8962. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8963. const Response &res) {
  8964. pre_compression_body = res.body;
  8965. pre_compression_content_type = res.get_header_value("Content-Type");
  8966. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8967. });
  8968. // Set up post-compression logger
  8969. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8970. post_compression_body = res.body;
  8971. post_compression_content_type = res.get_header_value("Content-Type");
  8972. post_compression_content_encoding =
  8973. res.get_header_value("Content-Encoding");
  8974. });
  8975. // Test with gzip compression
  8976. Headers headers;
  8977. headers.emplace("Accept-Encoding", "gzip");
  8978. auto res = cli_.Get("/compress", headers);
  8979. // Verify response was compressed
  8980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8981. EXPECT_EQ(StatusCode::OK_200, res->status);
  8982. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8983. // Verify pre-compression logger captured uncompressed content
  8984. EXPECT_EQ(test_content, pre_compression_body);
  8985. EXPECT_EQ("text/plain", pre_compression_content_type);
  8986. EXPECT_TRUE(pre_compression_content_encoding
  8987. .empty()); // No encoding header before compression
  8988. // Verify post-compression logger captured compressed content
  8989. EXPECT_NE(test_content,
  8990. post_compression_body); // Should be different after compression
  8991. EXPECT_EQ("text/plain", post_compression_content_type);
  8992. EXPECT_EQ("gzip", post_compression_content_encoding);
  8993. // Verify compressed content is smaller
  8994. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8995. }
  8996. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8997. const std::string test_content =
  8998. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8999. "3456789012345678901234567890";
  9000. std::string pre_compression_body;
  9001. std::string post_compression_body;
  9002. svr_.set_pre_compression_logger(
  9003. [&](const Request & /*req*/, const Response &res) {
  9004. pre_compression_body = res.body;
  9005. });
  9006. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9007. post_compression_body = res.body;
  9008. });
  9009. Headers headers;
  9010. headers.emplace("Accept-Encoding", "br");
  9011. auto res = cli_.Get("/compress", headers);
  9012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9013. EXPECT_EQ(StatusCode::OK_200, res->status);
  9014. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9015. // Verify pre-compression content is uncompressed
  9016. EXPECT_EQ(test_content, pre_compression_body);
  9017. // Verify post-compression content is compressed
  9018. EXPECT_NE(test_content, post_compression_body);
  9019. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9020. }
  9021. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9022. const std::string test_content =
  9023. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9024. "3456789012345678901234567890";
  9025. std::string pre_compression_body;
  9026. std::string post_compression_body;
  9027. svr_.set_pre_compression_logger(
  9028. [&](const Request & /*req*/, const Response &res) {
  9029. pre_compression_body = res.body;
  9030. });
  9031. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9032. post_compression_body = res.body;
  9033. });
  9034. // Request without compression (use /nocompress endpoint)
  9035. Headers headers;
  9036. auto res = cli_.Get("/nocompress", headers);
  9037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9038. EXPECT_EQ(StatusCode::OK_200, res->status);
  9039. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9040. // Pre-compression logger should not be called when no compression is applied
  9041. EXPECT_TRUE(
  9042. pre_compression_body.empty()); // Pre-compression logger not called
  9043. EXPECT_EQ(
  9044. test_content,
  9045. post_compression_body); // Post-compression logger captures final content
  9046. }
  9047. TEST_F(ServerTest, LoggerSeesContentLength) {
  9048. size_t logged_content_length = 0;
  9049. std::string logged_content_length_header;
  9050. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9051. logged_content_length = res.content_length_;
  9052. logged_content_length_header = res.get_header_value("Content-Length");
  9053. });
  9054. auto res = cli_.Get("/nocompress");
  9055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9056. EXPECT_EQ(StatusCode::OK_200, res->status);
  9057. EXPECT_EQ(res->body.size(), logged_content_length);
  9058. EXPECT_EQ(std::to_string(logged_content_length),
  9059. logged_content_length_header);
  9060. }
  9061. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9062. const std::string test_content =
  9063. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9064. "3456789012345678901234567890";
  9065. std::string pre_compression_body;
  9066. bool pre_logger_called = false;
  9067. // Set only pre-compression logger
  9068. svr_.set_pre_compression_logger(
  9069. [&](const Request & /*req*/, const Response &res) {
  9070. pre_compression_body = res.body;
  9071. pre_logger_called = true;
  9072. });
  9073. Headers headers;
  9074. headers.emplace("Accept-Encoding", "gzip");
  9075. auto res = cli_.Get("/compress", headers);
  9076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9077. EXPECT_EQ(StatusCode::OK_200, res->status);
  9078. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9079. // Verify pre-compression logger was called
  9080. EXPECT_TRUE(pre_logger_called);
  9081. EXPECT_EQ(test_content, pre_compression_body);
  9082. }
  9083. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9084. {
  9085. // Test with Expect: 100-continue header - success case
  9086. // Server returns 100 Continue, client sends body, server returns 200 OK
  9087. Request req;
  9088. req.method = "POST";
  9089. req.path = "/post-large";
  9090. req.set_header("Expect", "100-continue");
  9091. req.body = LARGE_DATA;
  9092. Response res;
  9093. auto error = Error::Success;
  9094. cli_.set_keep_alive(true);
  9095. auto ret = cli_.send(req, res, error);
  9096. EXPECT_TRUE(ret);
  9097. EXPECT_EQ(StatusCode::OK_200, res.status);
  9098. EXPECT_EQ(LARGE_DATA, res.body);
  9099. }
  9100. {
  9101. // Test with Expect: 100-continue header - error case
  9102. // Client should not send the body when server returns an error
  9103. Request req;
  9104. req.method = "POST";
  9105. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9106. req.set_header("Expect", "100-continue");
  9107. req.body = LARGE_DATA;
  9108. Response res;
  9109. auto error = Error::Success;
  9110. auto start = std::chrono::high_resolution_clock::now();
  9111. cli_.set_keep_alive(true);
  9112. auto ret = cli_.send(req, res, error);
  9113. auto end = std::chrono::high_resolution_clock::now();
  9114. auto elapsed =
  9115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9116. .count();
  9117. // With Expect: 100-continue, request completes successfully but with error
  9118. EXPECT_TRUE(ret);
  9119. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9120. EXPECT_EQ("close", res.get_header_value("Connection"));
  9121. EXPECT_FALSE(cli_.is_socket_open());
  9122. EXPECT_LE(elapsed, 2000);
  9123. }
  9124. {
  9125. // Send an extra GET request to ensure error recovery without hanging
  9126. Request req;
  9127. req.method = "GET";
  9128. req.path = "/hi";
  9129. auto start = std::chrono::high_resolution_clock::now();
  9130. auto res = cli_.send(req);
  9131. auto end = std::chrono::high_resolution_clock::now();
  9132. auto elapsed =
  9133. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9134. .count();
  9135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9136. EXPECT_EQ(StatusCode::OK_200, res->status);
  9137. EXPECT_EQ("Hello World!", res->body);
  9138. EXPECT_LE(elapsed, 500);
  9139. }
  9140. }
  9141. TEST(ZstdDecompressor, ChunkedDecompression) {
  9142. std::string data;
  9143. for (size_t i = 0; i < 32 * 1024; ++i) {
  9144. data.push_back(static_cast<char>('a' + i % 26));
  9145. }
  9146. std::string compressed_data;
  9147. {
  9148. httplib::detail::zstd_compressor compressor;
  9149. bool result = compressor.compress(
  9150. data.data(), data.size(),
  9151. /*last=*/true,
  9152. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9153. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9154. compressed_data_size);
  9155. return true;
  9156. });
  9157. ASSERT_TRUE(result);
  9158. }
  9159. std::string decompressed_data;
  9160. {
  9161. httplib::detail::zstd_decompressor decompressor;
  9162. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9163. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9164. size_t chunk_size = 130;
  9165. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9166. chunk_begin += chunk_size) {
  9167. size_t current_chunk_size =
  9168. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9169. bool result = decompressor.decompress(
  9170. compressed_data.data() + chunk_begin, current_chunk_size,
  9171. [&](const char *decompressed_data_chunk,
  9172. size_t decompressed_data_chunk_size) {
  9173. decompressed_data.insert(decompressed_data.size(),
  9174. decompressed_data_chunk,
  9175. decompressed_data_chunk_size);
  9176. return true;
  9177. });
  9178. ASSERT_TRUE(result);
  9179. }
  9180. }
  9181. ASSERT_EQ(data, decompressed_data);
  9182. }
  9183. TEST(ZstdDecompressor, Decompress) {
  9184. std::string original_text = "Compressed with ZSTD";
  9185. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9186. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9187. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9188. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9189. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9190. std::string decompressed_data;
  9191. {
  9192. httplib::detail::zstd_decompressor decompressor;
  9193. bool result = decompressor.decompress(
  9194. compressed_data.data(), compressed_data.size(),
  9195. [&](const char *decompressed_data_chunk,
  9196. size_t decompressed_data_chunk_size) {
  9197. decompressed_data.insert(decompressed_data.size(),
  9198. decompressed_data_chunk,
  9199. decompressed_data_chunk_size);
  9200. return true;
  9201. });
  9202. ASSERT_TRUE(result);
  9203. }
  9204. ASSERT_EQ(original_text, decompressed_data);
  9205. }
  9206. #endif
  9207. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9208. // separate chunks so that the server sees each part in its own read(). Used to
  9209. // place a read boundary at a specific offset of a request body.
  9210. static bool send_request_in_parts(time_t read_timeout_sec,
  9211. const std::vector<std::string> &parts,
  9212. std::string *resp = nullptr,
  9213. int port = PORT) {
  9214. auto error = Error::Success;
  9215. auto client_sock = detail::create_client_socket(
  9216. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9217. /*connection_timeout_sec=*/5, 0,
  9218. /*read_timeout_sec=*/5, 0,
  9219. /*write_timeout_sec=*/5, 0, std::string(), error);
  9220. if (client_sock == INVALID_SOCKET) { return false; }
  9221. auto ret = detail::process_client_socket(
  9222. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9223. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9224. for (size_t i = 0; i < parts.size(); i++) {
  9225. const auto &part = parts[i];
  9226. if (part.size() !=
  9227. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9228. return false;
  9229. }
  9230. if (i + 1 < parts.size()) {
  9231. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9232. }
  9233. }
  9234. char buf[512];
  9235. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9236. while (line_reader.getline()) {
  9237. if (resp) { *resp += line_reader.ptr(); }
  9238. }
  9239. return true;
  9240. });
  9241. detail::close_socket(client_sock);
  9242. return ret;
  9243. }
  9244. // Sends a raw request to a server listening at HOST:PORT.
  9245. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9246. std::string *resp = nullptr, int port = PORT) {
  9247. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9248. }
  9249. #ifdef CPPHTTPLIB_SSL_ENABLED
  9250. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9251. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9252. ASSERT_TRUE(svr.is_valid());
  9253. svr.set_read_timeout(1, 0);
  9254. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9255. auto se = detail::scope_exit([&] {
  9256. svr.stop();
  9257. t.join();
  9258. ASSERT_FALSE(svr.is_running());
  9259. });
  9260. svr.wait_until_ready();
  9261. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9262. // keeps each wait well within the read timeout. The server gives up a
  9263. // second in, so the bytes sent after that fail.
  9264. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9265. parts.resize(26, std::string(1, '\0'));
  9266. EXPECT_FALSE(send_request_in_parts(5, parts));
  9267. }
  9268. #endif
  9269. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9270. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9271. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9272. const std::vector<std::string> &parts,
  9273. std::string *resp = nullptr,
  9274. int port = PORT) {
  9275. auto error = Error::Success;
  9276. auto sock = detail::create_client_socket(
  9277. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9278. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9279. /*write_timeout_sec=*/5, 0, std::string(), error);
  9280. if (sock == INVALID_SOCKET) { return false; }
  9281. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9282. auto ctx = SSL_CTX_new(TLS_client_method());
  9283. auto ssl = SSL_new(ctx);
  9284. auto ssl_se = detail::scope_exit([&] {
  9285. SSL_free(ssl);
  9286. SSL_CTX_free(ctx);
  9287. });
  9288. SSL_set_fd(ssl, static_cast<int>(sock));
  9289. if (SSL_connect(ssl) != 1) { return false; }
  9290. for (size_t i = 0; i < parts.size(); i++) {
  9291. const auto &part = parts[i];
  9292. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9293. static_cast<int>(part.size())) {
  9294. return false;
  9295. }
  9296. if (i + 1 < parts.size()) {
  9297. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9298. }
  9299. }
  9300. char buf[512];
  9301. int n;
  9302. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9303. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9304. }
  9305. return true;
  9306. }
  9307. #endif
  9308. // The request line, then a header value a byte at a time.
  9309. static std::vector<std::string> slow_request_head_parts() {
  9310. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9311. parts.resize(26, "a");
  9312. parts.emplace_back("\r\n\r\n");
  9313. return parts;
  9314. }
  9315. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9316. // within the one-second read timeout. The server gives up a second in, before
  9317. // the head is complete.
  9318. static void
  9319. expect_slow_request_head_dropped(Server &svr,
  9320. const std::function<std::string()> &send) {
  9321. std::atomic<bool> handled(false);
  9322. svr.Get("/", [&](const Request &, Response &res) {
  9323. handled = true;
  9324. res.set_content("ok", "text/plain");
  9325. });
  9326. svr.set_read_timeout(1, 0);
  9327. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9328. auto se = detail::scope_exit([&] {
  9329. svr.stop();
  9330. t.join();
  9331. ASSERT_FALSE(svr.is_running());
  9332. });
  9333. svr.wait_until_ready();
  9334. auto resp = send();
  9335. EXPECT_FALSE(handled);
  9336. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9337. }
  9338. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9339. Server svr;
  9340. expect_slow_request_head_dropped(svr, [] {
  9341. std::string resp;
  9342. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9343. return resp;
  9344. });
  9345. }
  9346. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9347. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9349. ASSERT_TRUE(svr.is_valid());
  9350. expect_slow_request_head_dropped(svr, [] {
  9351. std::string resp;
  9352. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9353. return resp;
  9354. });
  9355. }
  9356. #endif
  9357. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9358. Server svr;
  9359. std::string header_value;
  9360. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9361. header_value = req.get_header_value("foo");
  9362. res.set_content("ok", "text/plain");
  9363. });
  9364. thread t = thread([&] { svr.listen(HOST, PORT); });
  9365. auto se = detail::scope_exit([&] {
  9366. svr.stop();
  9367. t.join();
  9368. ASSERT_FALSE(svr.is_running());
  9369. });
  9370. svr.wait_until_ready();
  9371. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9372. // like characters are not treated the same - use vertical tab and escape.
  9373. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9374. "foo: \t \v bar \x1B\t \r\n"
  9375. "Connection: close\r\n"
  9376. "\r\n";
  9377. std::string res;
  9378. ASSERT_TRUE(send_request(5, req, &res));
  9379. EXPECT_EQ(header_value, "");
  9380. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9381. }
  9382. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9383. Server svr;
  9384. std::string received;
  9385. svr.Get("/order", [&](const Request &req, Response &res) {
  9386. received = entries_to_string(req.headers);
  9387. res.set_content("ok", "text/plain");
  9388. });
  9389. auto port = svr.bind_to_any_port(HOST);
  9390. thread t = thread([&] { svr.listen_after_bind(); });
  9391. auto se = detail::scope_exit([&] {
  9392. svr.stop();
  9393. t.join();
  9394. ASSERT_FALSE(svr.is_running());
  9395. });
  9396. svr.wait_until_ready();
  9397. const std::string req = "GET /order HTTP/1.1\r\n"
  9398. "Host: localhost\r\n"
  9399. "X-First: 1\r\n"
  9400. "X-Dup: a\r\n"
  9401. "X-Second: 2\r\n"
  9402. "X-Dup: b\r\n"
  9403. "Connection: close\r\n"
  9404. "\r\n";
  9405. std::string res;
  9406. ASSERT_TRUE(send_request(5, req, &res, port));
  9407. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9408. EXPECT_EQ(
  9409. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9410. received);
  9411. }
  9412. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9413. Server svr;
  9414. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9415. res.set_header("Set-Cookie", "first=1");
  9416. res.set_header("X-Between", "y");
  9417. res.set_header("Set-Cookie", "second=2");
  9418. res.set_content("ok", "text/plain");
  9419. });
  9420. auto port = svr.bind_to_any_port(HOST);
  9421. thread t = thread([&] { svr.listen_after_bind(); });
  9422. auto se = detail::scope_exit([&] {
  9423. svr.stop();
  9424. t.join();
  9425. ASSERT_FALSE(svr.is_running());
  9426. });
  9427. svr.wait_until_ready();
  9428. Client cli(HOST, port);
  9429. auto res = cli.Get("/cookies");
  9430. ASSERT_TRUE(res);
  9431. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9432. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9433. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9434. }
  9435. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9436. Server svr;
  9437. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9438. auto i = new int(0);
  9439. res.set_header("Trailer", "X-Safe, X-Reflected");
  9440. res.set_chunked_content_provider(
  9441. "text/plain",
  9442. [i](size_t /*offset*/, DataSink &sink) {
  9443. if (*i == 0) {
  9444. sink.os << "body";
  9445. } else {
  9446. Headers trailer;
  9447. // A valid trailer that must survive.
  9448. trailer.emplace("X-Safe", "safe");
  9449. // Attacker-controlled value carrying CR/LF (response splitting).
  9450. trailer.emplace("X-Reflected",
  9451. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9452. // Attacker-controlled name carrying CR/LF.
  9453. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9454. sink.done_with_trailer(trailer);
  9455. }
  9456. (*i)++;
  9457. return true;
  9458. },
  9459. [i](bool /*success*/) { delete i; });
  9460. });
  9461. thread t = thread([&] { svr.listen(HOST, PORT); });
  9462. auto se = detail::scope_exit([&] {
  9463. svr.stop();
  9464. t.join();
  9465. ASSERT_FALSE(svr.is_running());
  9466. });
  9467. svr.wait_until_ready();
  9468. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9469. "Host: " + HOST +
  9470. "\r\n"
  9471. "Connection: close\r\n"
  9472. "\r\n";
  9473. std::string res;
  9474. ASSERT_TRUE(send_request(5, req, &res));
  9475. // The injected fields must not appear anywhere in the raw response.
  9476. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9477. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9478. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9479. // Invalid trailers are dropped entirely, matching set_header().
  9480. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9481. // The valid trailer still passes through.
  9482. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9483. }
  9484. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9485. Server svr;
  9486. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9487. // res.headers is a public field an application can populate directly,
  9488. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9489. // A valid header that must survive.
  9490. res.headers.emplace("X-Safe", "safe");
  9491. // Attacker-controlled value carrying CR/LF (response splitting).
  9492. res.headers.emplace("X-Reflected",
  9493. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9494. // Attacker-controlled name carrying CR/LF.
  9495. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9496. res.set_content("body", "text/plain");
  9497. });
  9498. thread t = thread([&] { svr.listen(HOST, PORT); });
  9499. auto se = detail::scope_exit([&] {
  9500. svr.stop();
  9501. t.join();
  9502. ASSERT_FALSE(svr.is_running());
  9503. });
  9504. svr.wait_until_ready();
  9505. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9506. "Host: " + HOST +
  9507. "\r\n"
  9508. "Connection: close\r\n"
  9509. "\r\n";
  9510. std::string res;
  9511. ASSERT_TRUE(send_request(5, req, &res));
  9512. // The injected fields must not appear anywhere in the raw response.
  9513. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9514. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9515. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9516. // Invalid headers are dropped entirely, matching set_header().
  9517. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9518. // The valid header still passes through.
  9519. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9520. }
  9521. // Forward declaration: in split builds split.py strips `inline` and moves the
  9522. // definition into httplib.cc, so detail::write_request_line is not visible from
  9523. // the public httplib.h. Re-declaring it here lets the tests link against the
  9524. // symbol in both header-only and split builds.
  9525. namespace httplib {
  9526. namespace detail {
  9527. ssize_t write_request_line(Stream &strm, const std::string &method,
  9528. const std::string &path);
  9529. } // namespace detail
  9530. } // namespace httplib
  9531. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9532. // A well-formed target is written verbatim.
  9533. {
  9534. detail::BufferStream strm;
  9535. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9536. EXPECT_GT(n, 0);
  9537. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9538. }
  9539. // A target carrying CR/LF, SP or other control octets must be rejected
  9540. // before anything reaches the wire, otherwise it splits the request line and
  9541. // injects a header or a whole request.
  9542. const std::string evil_targets[] = {
  9543. "/a\r\nInjected: pwned",
  9544. "/a\rInjected",
  9545. "/a\nInjected",
  9546. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9547. "/a b",
  9548. "/a\tb",
  9549. "/a\x7f",
  9550. };
  9551. for (const auto &evil : evil_targets) {
  9552. detail::BufferStream strm;
  9553. auto n = detail::write_request_line(strm, "GET", evil);
  9554. EXPECT_LT(n, 0);
  9555. EXPECT_TRUE(strm.get_buffer().empty());
  9556. }
  9557. }
  9558. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9559. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9560. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9561. // target reaches write_request. The client must fail cleanly with
  9562. // Error::Write instead of putting a request-line-less, header-injecting
  9563. // request on the wire.
  9564. Server svr;
  9565. svr.Get("/a", [](const Request &, Response &res) {
  9566. res.set_content("ok", "text/plain");
  9567. });
  9568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9569. auto se = detail::scope_exit([&] {
  9570. svr.stop();
  9571. thread.join();
  9572. ASSERT_FALSE(svr.is_running());
  9573. });
  9574. svr.wait_until_ready();
  9575. {
  9576. Client cli(HOST, PORT);
  9577. cli.set_path_encode(false);
  9578. // The request is rejected before anything is written, so the connection
  9579. // stays silent and the subsequent response read would otherwise block for
  9580. // the full default read timeout. Shorten it -- the assertion is on the
  9581. // error, not the timeout.
  9582. cli.set_read_timeout(1, 0);
  9583. auto res = cli.Get("/a\r\nInjected: pwned");
  9584. EXPECT_FALSE(res);
  9585. EXPECT_EQ(Error::Write, res.error());
  9586. }
  9587. }
  9588. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9589. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9590. // including extension methods.
  9591. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9592. for (const auto &method : good_methods) {
  9593. detail::BufferStream strm;
  9594. auto n = detail::write_request_line(strm, method, "/");
  9595. EXPECT_GT(n, 0);
  9596. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9597. }
  9598. // A method carrying CR/LF would split the request line and smuggle a whole
  9599. // request ahead of the real one. A space or an empty method corrupts the
  9600. // request line. All must be rejected before anything reaches the wire.
  9601. const std::string evil_methods[] = {
  9602. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9603. "GET\r\nInjected: pwned",
  9604. "GET\r",
  9605. "GET\n",
  9606. "GE T",
  9607. "",
  9608. };
  9609. for (const auto &evil : evil_methods) {
  9610. detail::BufferStream strm;
  9611. auto n = detail::write_request_line(strm, evil, "/");
  9612. EXPECT_LT(n, 0);
  9613. EXPECT_TRUE(strm.get_buffer().empty());
  9614. }
  9615. }
  9616. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9617. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9618. // through Client::send must fail with Error::Write and no request, neither
  9619. // the smuggled one nor the real one, may reach the server.
  9620. Server svr;
  9621. std::atomic<int> request_count(0);
  9622. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9623. request_count++;
  9624. res.status = StatusCode::OK_200;
  9625. return Server::HandlerResponse::Handled;
  9626. });
  9627. auto port = svr.bind_to_any_port(HOST);
  9628. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9629. auto se = detail::scope_exit([&] {
  9630. svr.stop();
  9631. thread.join();
  9632. ASSERT_FALSE(svr.is_running());
  9633. });
  9634. svr.wait_until_ready();
  9635. {
  9636. Client cli(HOST, port);
  9637. const std::string evil_methods[] = {
  9638. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9639. "GE T",
  9640. "",
  9641. };
  9642. for (const auto &evil : evil_methods) {
  9643. Request req;
  9644. req.method = evil;
  9645. req.path = "/";
  9646. auto res = cli.send(req);
  9647. EXPECT_FALSE(res);
  9648. EXPECT_EQ(Error::Write, res.error());
  9649. }
  9650. auto handle =
  9651. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9652. EXPECT_FALSE(handle.is_valid());
  9653. EXPECT_EQ(Error::Write, handle.error);
  9654. // A valid request on the same client still goes through.
  9655. auto res = cli.Get("/");
  9656. ASSERT_TRUE(res);
  9657. EXPECT_EQ(StatusCode::OK_200, res->status);
  9658. }
  9659. EXPECT_EQ(1, request_count.load());
  9660. }
  9661. // Sends a raw request and verifies that there isn't a crash or exception.
  9662. static void test_raw_request(const std::string &req,
  9663. std::string *out = nullptr) {
  9664. Server svr;
  9665. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9666. res.set_content("ok", "text/plain");
  9667. });
  9668. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9669. res.set_content("ok", "text/plain");
  9670. });
  9671. svr.Get("/header_field_value_check",
  9672. [&](const Request & /*req*/, Response &res) {
  9673. res.set_content("ok", "text/plain");
  9674. });
  9675. svr.CustomRoute("PROPFIND", "/dav",
  9676. [&](const Request & /*req*/, Response &res) {
  9677. res.status = StatusCode::MultiStatus_207;
  9678. });
  9679. // Server read timeout must be longer than the client read timeout for the
  9680. // bug to reproduce, probably to force the server to process a request
  9681. // without a trailing blank line.
  9682. const time_t client_read_timeout_sec = 1;
  9683. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9684. bool listen_thread_ok = false;
  9685. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9686. auto se = detail::scope_exit([&] {
  9687. svr.stop();
  9688. t.join();
  9689. ASSERT_FALSE(svr.is_running());
  9690. EXPECT_TRUE(listen_thread_ok);
  9691. });
  9692. svr.wait_until_ready();
  9693. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9694. }
  9695. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9696. // A certain header line causes an exception if the header property is parsed
  9697. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9698. test_raw_request(
  9699. "GET /hi HTTP/1.1\r\n"
  9700. " : "
  9701. " "
  9702. " ");
  9703. }
  9704. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9705. // A certain header line causes an exception if the header property *name* is
  9706. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9707. // greedy matcher and requires backtracking when there are a lot of ":"
  9708. // characters.
  9709. // This occurs with libc++ but not libstdc++.
  9710. test_raw_request(
  9711. "GET /hi HTTP/1.1\r\n"
  9712. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9713. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9714. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9715. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9716. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9717. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9718. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9719. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9720. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9721. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9722. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9723. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9724. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9725. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9726. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9727. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9728. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9729. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9730. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9731. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9732. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9733. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9734. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9735. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9736. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9737. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9738. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9739. "&&&%%%");
  9740. }
  9741. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9742. // Make sure this doesn't crash the server.
  9743. // In a previous version of the header line regex, the "\r" rendered the line
  9744. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9745. // a new position where the leading white space ended and the field value
  9746. // began.
  9747. // The crash occurs with libc++ but not libstdc++.
  9748. test_raw_request("GET /hi HTTP/1.1\r\n"
  9749. "a:" +
  9750. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9751. "\r\n"
  9752. "\r\n");
  9753. }
  9754. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9755. const char *rejected[] = {
  9756. // RFC 9112 §3: one SP between the parts, and nothing else
  9757. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9758. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9759. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9760. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9761. // A request-target has no fragment
  9762. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9763. // An HTTP/1.1 request needs a Host
  9764. "GET /hi HTTP/1.1\r\n\r\n",
  9765. };
  9766. for (auto request : rejected) {
  9767. std::string out;
  9768. test_raw_request(request, &out);
  9769. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9770. }
  9771. std::string out;
  9772. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9773. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9774. }
  9775. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9776. // RFC 9112 §6.1
  9777. const char *requests[] = {
  9778. "PUT /put_hi HTTP/1.1\r\n"
  9779. "Host: localhost\r\n"
  9780. "Content-Length: 0\r\n"
  9781. "Transfer-Encoding: chunked\r\n"
  9782. "\r\n"
  9783. "0\r\n\r\n",
  9784. "PUT /put_hi HTTP/1.0\r\n"
  9785. "Connection: keep-alive\r\n"
  9786. "Transfer-Encoding: chunked\r\n"
  9787. "\r\n"
  9788. "0\r\n\r\n",
  9789. };
  9790. for (auto request : requests) {
  9791. std::string out;
  9792. test_raw_request(request, &out);
  9793. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9794. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9795. }
  9796. }
  9797. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9798. std::string out;
  9799. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9800. "Content-Type: text/plain\r\n"
  9801. "Transfer-Encoding: chunked\r\n"
  9802. "\r\n"
  9803. "nothex\r\n",
  9804. &out);
  9805. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9806. }
  9807. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9808. std::string out;
  9809. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9810. "Content-Type: text/plain\r\n"
  9811. "Transfer-Encoding: chunked\r\n"
  9812. "\r\n"
  9813. "3\r\n"
  9814. "xyz\r\n"
  9815. "NaN\r\n",
  9816. &out);
  9817. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9818. }
  9819. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9820. std::string out;
  9821. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9822. "Content-Type: text/plain\r\n"
  9823. "Transfer-Encoding: chunked\r\n"
  9824. "\r\n"
  9825. // Length is too large for 64 bits.
  9826. "1ffffffffffffffff\r\n"
  9827. "xyz\r\n",
  9828. &out);
  9829. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9830. }
  9831. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9832. test_raw_request("GET /hi HTTP/1.1\r\n"
  9833. "Content-Type: text/plain\r\n\r");
  9834. }
  9835. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9836. std::string out;
  9837. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9838. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9839. }
  9840. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9841. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9842. std::string out;
  9843. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9844. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9845. }
  9846. }
  9847. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9848. std::string out;
  9849. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9850. "Host: localhost\r\n"
  9851. "Connection: close\r\n\r\n",
  9852. &out);
  9853. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9854. }
  9855. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9856. Server svr;
  9857. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9858. EXPECT_TRUE(!req.remote_addr.empty());
  9859. });
  9860. thread t = thread([&] { svr.listen(HOST, PORT); });
  9861. auto se = detail::scope_exit([&] {
  9862. svr.stop();
  9863. t.join();
  9864. ASSERT_FALSE(svr.is_running());
  9865. });
  9866. svr.wait_until_ready();
  9867. // Send an invalid request line to trigger Bad Request
  9868. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9869. std::string out;
  9870. ASSERT_TRUE(send_request(5, bad_req, &out));
  9871. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9872. }
  9873. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9874. // answered right away rather than blocking on a read that waits for EOF.
  9875. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9876. std::string out;
  9877. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9878. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9879. }
  9880. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9881. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9882. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9883. for (const auto *method : methods) {
  9884. Server svr;
  9885. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9886. EXPECT_FALSE(svr.is_valid()) << method;
  9887. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9888. }
  9889. }
  9890. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9891. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9892. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9893. for (const auto *method : methods) {
  9894. Server svr;
  9895. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9896. EXPECT_FALSE(svr.is_valid()) << method;
  9897. }
  9898. }
  9899. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9900. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9901. "COPY", "MOVE", "LOCK",
  9902. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9903. Server svr;
  9904. for (const auto *method : methods) {
  9905. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9906. }
  9907. EXPECT_TRUE(svr.is_valid());
  9908. }
  9909. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9910. Server svr;
  9911. svr.CustomRoute("POST", "/x",
  9912. [](const Request &, Response &, const ContentReader &) {});
  9913. EXPECT_FALSE(svr.is_valid());
  9914. }
  9915. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9916. Server svr;
  9917. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9918. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9919. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9920. EXPECT_FALSE(svr.is_valid());
  9921. }
  9922. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9923. Server svr;
  9924. auto captured = Error::Success;
  9925. svr.set_error_logger(
  9926. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9927. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9928. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9929. }
  9930. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9931. std::string out;
  9932. std::string request(
  9933. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9934. test_raw_request(request, &out);
  9935. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9936. }
  9937. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9938. std::string out;
  9939. std::string request(
  9940. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9941. test_raw_request(request, &out);
  9942. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9943. }
  9944. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9945. std::string out;
  9946. std::string request(
  9947. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9948. test_raw_request(request, &out);
  9949. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9950. }
  9951. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9952. std::string out;
  9953. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9954. "Host: localhost\r\n"
  9955. "Test: \r\n\r\n",
  9956. &out);
  9957. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9958. }
  9959. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9960. Server svr;
  9961. std::string x_custom;
  9962. std::string cookie;
  9963. std::string xff;
  9964. std::string x_unicode;
  9965. std::string x_iis;
  9966. svr.Get("/check", [&](const Request &req, Response &res) {
  9967. x_custom = req.get_header_value("X-Custom");
  9968. cookie = req.get_header_value("Cookie");
  9969. xff = req.get_header_value("X-Forwarded-For");
  9970. x_unicode = req.get_header_value("X-Unicode");
  9971. x_iis = req.get_header_value("X-IIS");
  9972. res.set_content("ok", "text/plain");
  9973. });
  9974. thread t = thread([&] { svr.listen(HOST, PORT); });
  9975. auto se = detail::scope_exit([&] {
  9976. svr.stop();
  9977. t.join();
  9978. ASSERT_FALSE(svr.is_running());
  9979. });
  9980. svr.wait_until_ready();
  9981. const std::string req = "GET /check HTTP/1.1\r\n"
  9982. "Host: localhost\r\n"
  9983. "X-Custom: a%0D%0AInjected: b\r\n"
  9984. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9985. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9986. "X-Unicode: %E3%81%82\r\n"
  9987. "X-IIS: %u00E9\r\n"
  9988. "Connection: close\r\n"
  9989. "\r\n";
  9990. std::string res;
  9991. ASSERT_TRUE(send_request(5, req, &res));
  9992. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9993. // Every value must be returned verbatim (wire form), with no decoding.
  9994. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9995. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9996. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9997. EXPECT_EQ("%E3%81%82", x_unicode);
  9998. EXPECT_EQ("%u00E9", x_iis);
  9999. }
  10000. // Applications that previously relied on automatic percent-decoding can
  10001. // reproduce the old behavior by explicitly calling decode_path_component()
  10002. // or, for RFC 3986 conformance, decode_uri_component().
  10003. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10004. Server svr;
  10005. std::string decoded;
  10006. svr.Get("/check", [&](const Request &req, Response &res) {
  10007. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10008. res.set_content("ok", "text/plain");
  10009. });
  10010. thread t = thread([&] { svr.listen(HOST, PORT); });
  10011. auto se = detail::scope_exit([&] {
  10012. svr.stop();
  10013. t.join();
  10014. ASSERT_FALSE(svr.is_running());
  10015. });
  10016. svr.wait_until_ready();
  10017. const std::string req = "GET /check HTTP/1.1\r\n"
  10018. "Host: localhost\r\n"
  10019. "X-Custom: hello%20world\r\n"
  10020. "Connection: close\r\n"
  10021. "\r\n";
  10022. std::string res;
  10023. ASSERT_TRUE(send_request(5, req, &res));
  10024. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10025. EXPECT_EQ("hello world", decoded);
  10026. }
  10027. // Regression test for #2033. Browsers send Referer values that include
  10028. // percent-encoded characters such as %0A inside the URL. Decoding the
  10029. // header value would either trip the post-decode CR/LF/NUL guard (the
  10030. // original bug, returning 400) or, after that guard was relaxed, silently
  10031. // store a literal LF — both unacceptable. The wire form must round-trip.
  10032. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10033. Server svr;
  10034. std::string referer;
  10035. svr.Get("/check", [&](const Request &req, Response &res) {
  10036. referer = req.get_header_value("Referer");
  10037. res.set_content("ok", "text/plain");
  10038. });
  10039. thread t = thread([&] { svr.listen(HOST, PORT); });
  10040. auto se = detail::scope_exit([&] {
  10041. svr.stop();
  10042. t.join();
  10043. ASSERT_FALSE(svr.is_running());
  10044. });
  10045. svr.wait_until_ready();
  10046. const std::string req = "GET /check HTTP/1.1\r\n"
  10047. "Host: localhost\r\n"
  10048. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10049. "Connection: close\r\n"
  10050. "\r\n";
  10051. std::string res;
  10052. ASSERT_TRUE(send_request(5, req, &res));
  10053. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10054. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10055. }
  10056. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10057. Server svr;
  10058. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10059. res.set_header("Cache-Control", "no-cache");
  10060. res.set_chunked_content_provider(
  10061. "text/event-stream", [](size_t offset, DataSink &sink) {
  10062. std::string s = "data:";
  10063. s += std::to_string(offset);
  10064. s += "\n\n";
  10065. auto ret = sink.write(s.data(), s.size());
  10066. EXPECT_TRUE(ret);
  10067. std::this_thread::sleep_for(std::chrono::seconds(1));
  10068. return true;
  10069. });
  10070. });
  10071. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10072. svr.wait_until_ready();
  10073. Client client(HOST, PORT);
  10074. const Headers headers = {{"Accept", "text/event-stream"}};
  10075. auto get_thread = std::thread([&client, &headers]() {
  10076. auto res = client.Get(
  10077. "/events", headers,
  10078. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10079. });
  10080. auto se = detail::scope_exit([&] {
  10081. svr.stop();
  10082. get_thread.join();
  10083. listen_thread.join();
  10084. ASSERT_FALSE(svr.is_running());
  10085. });
  10086. // Give GET time to get a few messages.
  10087. std::this_thread::sleep_for(std::chrono::seconds(2));
  10088. }
  10089. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10090. httplib::Server svr;
  10091. svr.Post("/hi",
  10092. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10093. res.status = StatusCode::OK_200;
  10094. });
  10095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10096. svr.wait_until_ready();
  10097. Client cli(HOST, PORT);
  10098. auto res = cli.Post("/hi", "data", "text/plain");
  10099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10100. EXPECT_EQ(StatusCode::OK_200, res->status);
  10101. svr.stop();
  10102. thread.join();
  10103. ASSERT_FALSE(svr.is_running());
  10104. res = cli.Post("/hi", "data", "text/plain");
  10105. ASSERT_FALSE(res);
  10106. }
  10107. TEST(ServerStopTest, ListenFailure) {
  10108. Server svr;
  10109. auto t = thread([&]() {
  10110. auto ret = svr.listen("????", PORT);
  10111. EXPECT_FALSE(ret);
  10112. });
  10113. svr.wait_until_ready();
  10114. svr.stop();
  10115. t.join();
  10116. }
  10117. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10118. TEST(ServerStopTest, Decommision) {
  10119. Server svr;
  10120. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10121. for (int i = 0; i < 4; i++) {
  10122. auto is_even = !(i % 2);
  10123. std::thread t{[&] {
  10124. try {
  10125. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10126. if (is_even) {
  10127. throw std::runtime_error("Some thing that happens to go wrong.");
  10128. }
  10129. svr.listen(HOST, PORT);
  10130. } catch (...) { svr.decommission(); }
  10131. }};
  10132. svr.wait_until_ready();
  10133. // Server is up
  10134. {
  10135. Client cli(HOST, PORT);
  10136. auto res = cli.Get("/hi");
  10137. if (is_even) {
  10138. EXPECT_FALSE(res);
  10139. } else {
  10140. EXPECT_TRUE(res);
  10141. EXPECT_EQ("hi...", res->body);
  10142. }
  10143. }
  10144. svr.stop();
  10145. t.join();
  10146. // Server is down...
  10147. {
  10148. Client cli(HOST, PORT);
  10149. auto res = cli.Get("/hi");
  10150. EXPECT_FALSE(res);
  10151. }
  10152. }
  10153. }
  10154. #endif
  10155. // Helper function for string body upload progress tests
  10156. template <typename SetupHandler, typename ClientCall>
  10157. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10158. ClientCall &&client_call,
  10159. const string &body) {
  10160. Server svr;
  10161. setup_handler(svr);
  10162. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10163. auto se = detail::scope_exit([&] {
  10164. svr.stop();
  10165. t.join();
  10166. });
  10167. svr.wait_until_ready();
  10168. Client cli(HOST, PORT);
  10169. vector<uint64_t> progress_values;
  10170. bool progress_called = false;
  10171. auto res =
  10172. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10173. progress_values.push_back(current);
  10174. progress_called = true;
  10175. return true;
  10176. });
  10177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10178. EXPECT_EQ(200, res->status);
  10179. EXPECT_TRUE(progress_called);
  10180. }
  10181. TEST(UploadProgressTest, PostStringBodyBasic) {
  10182. TestStringBodyUploadProgress(
  10183. [](Server &svr) {
  10184. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10185. res.set_content("received", "text/plain");
  10186. });
  10187. },
  10188. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10189. return cli.Post("/test", body, "text/plain", progress_callback);
  10190. },
  10191. "test data for upload progress");
  10192. }
  10193. TEST(UploadProgressTest, PutStringBodyBasic) {
  10194. TestStringBodyUploadProgress(
  10195. [](Server &svr) {
  10196. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10197. res.set_content("put received", "text/plain");
  10198. });
  10199. },
  10200. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10201. return cli.Put("/test", body, "text/plain", progress_callback);
  10202. },
  10203. "put test data for upload progress");
  10204. }
  10205. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10206. TestStringBodyUploadProgress(
  10207. [](Server &svr) {
  10208. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10209. res.set_content("patch received", "text/plain");
  10210. });
  10211. },
  10212. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10213. return cli.Patch("/test", body, "text/plain", progress_callback);
  10214. },
  10215. "patch test data for upload progress");
  10216. }
  10217. // Helper function for content provider upload progress tests
  10218. template <typename SetupHandler, typename ClientCall>
  10219. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10220. ClientCall &&client_call) {
  10221. Server svr;
  10222. setup_handler(svr);
  10223. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10224. auto se = detail::scope_exit([&] {
  10225. svr.stop();
  10226. t.join();
  10227. });
  10228. svr.wait_until_ready();
  10229. Client cli(HOST, PORT);
  10230. vector<uint64_t> progress_values;
  10231. auto res =
  10232. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10233. progress_values.push_back(current);
  10234. return true;
  10235. });
  10236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10237. EXPECT_EQ(200, res->status);
  10238. EXPECT_FALSE(progress_values.empty());
  10239. }
  10240. TEST(UploadProgressTest, PostContentProviderProgress) {
  10241. TestContentProviderUploadProgress(
  10242. [](Server &svr) {
  10243. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10244. res.set_content("provider received", "text/plain");
  10245. });
  10246. },
  10247. [](Client &cli, UploadProgress progress_callback) {
  10248. return cli.Post(
  10249. "/test", 9,
  10250. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10251. sink.os << "test data";
  10252. return true;
  10253. },
  10254. "text/plain", progress_callback);
  10255. });
  10256. }
  10257. // Helper function for multipart upload progress tests
  10258. template <typename SetupHandler, typename ClientCall>
  10259. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10260. ClientCall &&client_call,
  10261. const string &endpoint) {
  10262. Server svr;
  10263. setup_handler(svr);
  10264. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10265. auto se = detail::scope_exit([&] {
  10266. svr.stop();
  10267. t.join();
  10268. });
  10269. svr.wait_until_ready();
  10270. Client cli(HOST, PORT);
  10271. vector<uint64_t> progress_values;
  10272. UploadFormDataItems items = {
  10273. {"field1", "value1", "", ""},
  10274. {"field2", "longer value for progress tracking test", "", ""},
  10275. {"file1", "file content data for upload progress", "test.txt",
  10276. "text/plain"}};
  10277. auto res = client_call(cli, endpoint, items,
  10278. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10279. progress_values.push_back(current);
  10280. return true;
  10281. });
  10282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10283. EXPECT_EQ(200, res->status);
  10284. EXPECT_FALSE(progress_values.empty());
  10285. }
  10286. TEST(UploadProgressTest, PostMultipartProgress) {
  10287. TestMultipartUploadProgress(
  10288. [](Server &svr) {
  10289. svr.Post("/multipart", [](const Request &req, Response &res) {
  10290. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10291. res.set_content("multipart received", "text/plain");
  10292. });
  10293. },
  10294. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10295. UploadProgress progress_callback) {
  10296. return cli.Post(endpoint, items, progress_callback);
  10297. },
  10298. "/multipart");
  10299. }
  10300. // Helper function for basic download progress tests
  10301. template <typename SetupHandler, typename ClientCall>
  10302. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10303. ClientCall &&client_call, const string &endpoint,
  10304. size_t expected_content_size) {
  10305. Server svr;
  10306. setup_handler(svr);
  10307. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10308. auto se = detail::scope_exit([&] {
  10309. svr.stop();
  10310. t.join();
  10311. });
  10312. svr.wait_until_ready();
  10313. Client cli(HOST, PORT);
  10314. vector<uint64_t> progress_values;
  10315. auto res = client_call(cli, endpoint,
  10316. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10317. progress_values.push_back(current);
  10318. return true;
  10319. });
  10320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10321. EXPECT_EQ(200, res->status);
  10322. EXPECT_FALSE(progress_values.empty());
  10323. EXPECT_EQ(expected_content_size, res->body.size());
  10324. }
  10325. TEST(DownloadProgressTest, GetBasic) {
  10326. TestBasicDownloadProgress(
  10327. [](Server &svr) {
  10328. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10329. string content(1000, 'D');
  10330. res.set_content(content, "text/plain");
  10331. });
  10332. },
  10333. [](Client &cli, const string &endpoint,
  10334. DownloadProgress progress_callback) {
  10335. return cli.Get(endpoint, progress_callback);
  10336. },
  10337. "/download", 1000u);
  10338. }
  10339. // Helper function for content receiver download progress tests
  10340. template <typename SetupHandler, typename ClientCall>
  10341. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10342. ClientCall &&client_call,
  10343. const string &endpoint,
  10344. size_t expected_content_size) {
  10345. Server svr;
  10346. setup_handler(svr);
  10347. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10348. auto se = detail::scope_exit([&] {
  10349. svr.stop();
  10350. t.join();
  10351. });
  10352. svr.wait_until_ready();
  10353. Client cli(HOST, PORT);
  10354. vector<uint64_t> progress_values;
  10355. string received_body;
  10356. auto res = client_call(
  10357. cli, endpoint,
  10358. [&](const char *data, size_t data_length) -> bool {
  10359. received_body.append(data, data_length);
  10360. return true;
  10361. },
  10362. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10363. progress_values.push_back(current);
  10364. return true;
  10365. });
  10366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10367. EXPECT_EQ(200, res->status);
  10368. EXPECT_FALSE(progress_values.empty());
  10369. EXPECT_EQ(expected_content_size, received_body.size());
  10370. EXPECT_TRUE(res->body.empty());
  10371. }
  10372. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10373. TestContentReceiverDownloadProgress(
  10374. [](Server &svr) {
  10375. svr.Get("/download-receiver",
  10376. [](const Request & /*req*/, Response &res) {
  10377. string content(2000, 'R');
  10378. res.set_content(content, "text/plain");
  10379. });
  10380. },
  10381. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10382. DownloadProgress progress_callback) {
  10383. return cli.Get(endpoint, content_receiver, progress_callback);
  10384. },
  10385. "/download-receiver", 2000u);
  10386. }
  10387. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10388. // A provider reaching a pass with nothing to hand over - an empty buffer
  10389. // popped off a queue, say - must not be taken to mean the body is finished.
  10390. // It used to end the loop with the terminating chunk unwritten while the
  10391. // server still considered the response complete, so the peer waited for an
  10392. // end that never arrived.
  10393. Server svr;
  10394. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10395. auto step = std::make_shared<int>(0);
  10396. res.set_chunked_content_provider("text/plain",
  10397. [step](size_t /*offset*/, DataSink &sink) {
  10398. switch ((*step)++) {
  10399. case 0: sink.write("", 0); break;
  10400. case 1: sink.write("hello", 5); break;
  10401. default: sink.done(); break;
  10402. }
  10403. return true;
  10404. });
  10405. });
  10406. auto port = svr.bind_to_any_port(HOST);
  10407. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10408. auto listen_se = detail::scope_exit([&] {
  10409. svr.stop();
  10410. listen_thread.join();
  10411. ASSERT_FALSE(svr.is_running());
  10412. });
  10413. svr.wait_until_ready();
  10414. Client cli(HOST, port);
  10415. // Without the fix the body is never terminated, so bound the wait rather
  10416. // than letting the test hang on the default read timeout.
  10417. cli.set_read_timeout(5, 0);
  10418. auto res = cli.Get("/stream");
  10419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10420. EXPECT_EQ(StatusCode::OK_200, res->status);
  10421. EXPECT_EQ("hello", res->body);
  10422. }
  10423. TEST(StreamingTest, NoContentLengthStreaming) {
  10424. Server svr;
  10425. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10426. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10427. if (offset < 6) {
  10428. sink.os << (offset < 3 ? "a" : "b");
  10429. } else {
  10430. sink.done();
  10431. }
  10432. return true;
  10433. });
  10434. });
  10435. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10436. auto listen_se = detail::scope_exit([&] {
  10437. svr.stop();
  10438. listen_thread.join();
  10439. ASSERT_FALSE(svr.is_running());
  10440. });
  10441. svr.wait_until_ready();
  10442. Client client(HOST, PORT);
  10443. auto get_thread = std::thread([&client]() {
  10444. std::string s;
  10445. auto res =
  10446. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10447. s += std::string(data, len);
  10448. return true;
  10449. });
  10450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10451. EXPECT_EQ(StatusCode::OK_200, res->status);
  10452. EXPECT_EQ("aaabbb", s);
  10453. });
  10454. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10455. // Give GET time to get a few messages.
  10456. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10457. }
  10458. TEST(MountTest, Unmount) {
  10459. Server svr;
  10460. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10461. auto se = detail::scope_exit([&] {
  10462. svr.stop();
  10463. listen_thread.join();
  10464. ASSERT_FALSE(svr.is_running());
  10465. });
  10466. svr.wait_until_ready();
  10467. Client cli("localhost", PORT);
  10468. svr.set_mount_point("/mount2", "./www2");
  10469. auto res = cli.Get("/");
  10470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10471. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10472. res = cli.Get("/mount2/dir/test.html");
  10473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10474. EXPECT_EQ(StatusCode::OK_200, res->status);
  10475. svr.set_mount_point("/", "./www");
  10476. res = cli.Get("/dir/");
  10477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10478. EXPECT_EQ(StatusCode::OK_200, res->status);
  10479. svr.remove_mount_point("/");
  10480. res = cli.Get("/dir/");
  10481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10482. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10483. svr.remove_mount_point("/mount2");
  10484. res = cli.Get("/mount2/dir/test.html");
  10485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10486. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10487. }
  10488. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10489. Server svr;
  10490. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10491. svr.Get("/api/hello", [](const Request &, Response &res) {
  10492. res.set_content("api", "text/plain");
  10493. });
  10494. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10495. auto se = detail::scope_exit([&] {
  10496. svr.stop();
  10497. listen_thread.join();
  10498. ASSERT_FALSE(svr.is_running());
  10499. });
  10500. svr.wait_until_ready();
  10501. Client cli(HOST, PORT);
  10502. auto res = cli.Get("/dir/test.html");
  10503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10504. EXPECT_EQ(StatusCode::OK_200, res->status);
  10505. res = cli.Get("/api/hello");
  10506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10507. EXPECT_EQ(StatusCode::OK_200, res->status);
  10508. EXPECT_EQ("api", res->body);
  10509. }
  10510. TEST(MountTest, PathSegmentBoundary) {
  10511. Server svr;
  10512. svr.set_mount_point("/mount2", "./www2");
  10513. svr.set_mount_point("/", "./www");
  10514. auto port = svr.bind_to_any_port(HOST);
  10515. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10516. auto se = detail::scope_exit([&] {
  10517. svr.stop();
  10518. listen_thread.join();
  10519. ASSERT_FALSE(svr.is_running());
  10520. });
  10521. svr.wait_until_ready();
  10522. Client cli(HOST, port);
  10523. auto res = cli.Get("/mount2/dir/test.html");
  10524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10525. EXPECT_EQ(StatusCode::OK_200, res->status);
  10526. // "/mount2" must not match part-way through a path segment.
  10527. res = cli.Get("/mount2dir/test.html");
  10528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10530. // A mount point ending in '/' keeps matching every path below it.
  10531. res = cli.Get("/dir/test.html");
  10532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10533. EXPECT_EQ(StatusCode::OK_200, res->status);
  10534. }
  10535. TEST(MountTest, Redicect) {
  10536. Server svr;
  10537. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10538. auto se = detail::scope_exit([&] {
  10539. svr.stop();
  10540. listen_thread.join();
  10541. ASSERT_FALSE(svr.is_running());
  10542. });
  10543. svr.set_mount_point("/", "./www");
  10544. svr.wait_until_ready();
  10545. Client cli("localhost", PORT);
  10546. auto res = cli.Get("/dir/");
  10547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10548. EXPECT_EQ(StatusCode::OK_200, res->status);
  10549. res = cli.Get("/dir");
  10550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10551. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10552. res = cli.Get("/file");
  10553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10554. EXPECT_EQ(StatusCode::OK_200, res->status);
  10555. res = cli.Get("/file/");
  10556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10557. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10558. cli.set_follow_location(true);
  10559. res = cli.Get("/dir");
  10560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10561. EXPECT_EQ(StatusCode::OK_200, res->status);
  10562. }
  10563. TEST(MountTest, MultibytesPathName) {
  10564. Server svr;
  10565. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10566. auto se = detail::scope_exit([&] {
  10567. svr.stop();
  10568. listen_thread.join();
  10569. ASSERT_FALSE(svr.is_running());
  10570. });
  10571. svr.set_mount_point("/", "./www");
  10572. svr.wait_until_ready();
  10573. Client cli("localhost", PORT);
  10574. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10576. EXPECT_EQ(StatusCode::OK_200, res->status);
  10577. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10578. }
  10579. #ifdef _WIN32
  10580. // Issue #2435: mmap::open() must succeed even when another handle holds
  10581. // the file open for writing (e.g. an active log file).
  10582. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10583. const char *path = "mmap_concurrent_writer_test.txt";
  10584. const char *content = "hello";
  10585. {
  10586. std::ofstream f(path, std::ios::binary);
  10587. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10588. }
  10589. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10590. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10591. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10592. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10593. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10594. detail::mmap m(path);
  10595. ASSERT_TRUE(m.is_open());
  10596. EXPECT_EQ(strlen(content), m.size());
  10597. char buf[8];
  10598. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10599. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10600. }
  10601. #endif
  10602. #ifndef _WIN32
  10603. // A directory or a device has no size to serve.
  10604. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10605. const char *path = "./mmap_not_regular_test_dir";
  10606. ASSERT_EQ(0, ::mkdir(path, 0755));
  10607. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10608. for (auto p : {path, "/dev/null"}) {
  10609. detail::mmap m(p);
  10610. EXPECT_FALSE(m.is_open()) << p;
  10611. EXPECT_EQ(0U, m.size()) << p;
  10612. }
  10613. Server svr;
  10614. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10615. res.set_file_content("/dev/null");
  10616. });
  10617. auto port = svr.bind_to_any_port(HOST);
  10618. thread t = thread([&] { svr.listen_after_bind(); });
  10619. auto se = detail::scope_exit([&] {
  10620. svr.stop();
  10621. t.join();
  10622. });
  10623. svr.wait_until_ready();
  10624. auto res = Client(HOST, port).Get("/null");
  10625. ASSERT_TRUE(res);
  10626. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10627. }
  10628. #endif
  10629. #ifdef __linux__
  10630. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10631. TEST(MmapTest, FileIsNotMapped) {
  10632. const char *path = "mmap_not_mapped_test.txt";
  10633. {
  10634. std::ofstream f(path, std::ios::binary);
  10635. f << "hello";
  10636. }
  10637. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10638. detail::mmap m(path);
  10639. ASSERT_TRUE(m.is_open());
  10640. std::ifstream maps("/proc/self/maps");
  10641. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10642. std::istreambuf_iterator<char>());
  10643. EXPECT_EQ(std::string::npos, mappings.find(path));
  10644. }
  10645. #endif
  10646. TEST(KeepAliveTest, ReadTimeout) {
  10647. Server svr;
  10648. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10649. std::this_thread::sleep_for(std::chrono::seconds(2));
  10650. res.set_content("a", "text/plain");
  10651. });
  10652. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10653. res.set_content("b", "text/plain");
  10654. });
  10655. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10656. auto se = detail::scope_exit([&] {
  10657. svr.stop();
  10658. listen_thread.join();
  10659. ASSERT_FALSE(svr.is_running());
  10660. });
  10661. svr.wait_until_ready();
  10662. Client cli("localhost", PORT);
  10663. cli.set_keep_alive(true);
  10664. cli.set_read_timeout(std::chrono::seconds(1));
  10665. auto resa = cli.Get("/a");
  10666. ASSERT_FALSE(resa);
  10667. EXPECT_EQ(Error::Read, resa.error());
  10668. auto resb = cli.Get("/b");
  10669. ASSERT_TRUE(resb);
  10670. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10671. EXPECT_EQ("b", resb->body);
  10672. }
  10673. TEST(KeepAliveTest, MaxCount) {
  10674. size_t keep_alive_max_count = 3;
  10675. Server svr;
  10676. svr.set_keep_alive_max_count(keep_alive_max_count);
  10677. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10678. res.set_content("Hello World!", "text/plain");
  10679. });
  10680. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10681. auto se = detail::scope_exit([&] {
  10682. svr.stop();
  10683. listen_thread.join();
  10684. ASSERT_FALSE(svr.is_running());
  10685. });
  10686. svr.wait_until_ready();
  10687. Client cli(HOST, PORT);
  10688. cli.set_keep_alive(true);
  10689. for (size_t i = 0; i < 5; i++) {
  10690. auto result = cli.Get("/hi");
  10691. ASSERT_TRUE(result);
  10692. EXPECT_EQ(StatusCode::OK_200, result->status);
  10693. if (i == keep_alive_max_count - 1) {
  10694. EXPECT_EQ("close", result->get_header_value("Connection"));
  10695. } else {
  10696. EXPECT_FALSE(result->has_header("Connection"));
  10697. }
  10698. }
  10699. }
  10700. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10701. // can pull the next one into the server's buffer. The server must serve it
  10702. // without waiting for the socket to become readable again. The keep-alive
  10703. // timeout outlasts the client's read timeout, so a request left waiting for it
  10704. // shows up as a missing response.
  10705. static void serve_pipelining_routes(Server &svr,
  10706. const std::function<void(int)> &client) {
  10707. svr.set_keep_alive_timeout(5);
  10708. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10709. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10710. });
  10711. svr.Post("/echo", [](const Request &req, Response &res) {
  10712. res.set_content("echo " + req.body, "text/plain");
  10713. });
  10714. auto port = svr.bind_to_any_port(HOST);
  10715. thread t = thread([&] { svr.listen_after_bind(); });
  10716. auto se = detail::scope_exit([&] {
  10717. svr.stop();
  10718. t.join();
  10719. });
  10720. svr.wait_until_ready();
  10721. client(port);
  10722. }
  10723. static std::string
  10724. send_pipelined_requests(const std::vector<std::string> &parts) {
  10725. Server svr;
  10726. std::string res;
  10727. serve_pipelining_routes(svr, [&](int port) {
  10728. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10729. });
  10730. return res;
  10731. }
  10732. static void expect_in_order(const std::string &res,
  10733. const std::vector<std::string> &bodies) {
  10734. size_t pos = 0;
  10735. for (const auto &body : bodies) {
  10736. pos = res.find(body, pos);
  10737. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10738. pos += body.size();
  10739. }
  10740. }
  10741. TEST(KeepAliveTest, PipelinedRequests) {
  10742. auto res = send_pipelined_requests(
  10743. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10744. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10745. "Content-Length: 4\r\n\r\nbody"
  10746. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10747. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10748. }
  10749. // The second request starts in the server's buffer and ends on the socket.
  10750. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10751. auto res =
  10752. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10753. "GET /hi/2 HTTP/1.1\r\nHo",
  10754. "st: localhost\r\nConnection: close\r\n\r\n"});
  10755. expect_in_order(res, {"hi 1", "hi 2"});
  10756. }
  10757. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10758. // CRLF after a body does not turn into a 400 for the next request.
  10759. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10760. auto res = send_pipelined_requests(
  10761. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10762. "Content-Length: 4\r\n\r\nbody\r\n"
  10763. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10764. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10765. expect_in_order(res, {"echo body", "hi 2"});
  10766. }
  10767. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10768. // must not be served as the next request.
  10769. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10770. auto res = send_pipelined_requests(
  10771. {"INVALID REQUEST LINE\r\n\r\n"
  10772. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10773. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10774. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10775. }
  10776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10777. // Over TLS, the next request is held by the TLS library as already decrypted
  10778. // data rather than on the socket.
  10779. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10781. std::string res;
  10782. serve_pipelining_routes(svr, [&](int port) {
  10783. // One part, so all three requests arrive in one TLS record
  10784. EXPECT_TRUE(send_ssl_request_in_parts(
  10785. 2,
  10786. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10787. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10788. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10789. &res, port));
  10790. });
  10791. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10792. }
  10793. #endif
  10794. TEST(KeepAliveTest, Issue1041) {
  10795. Server svr;
  10796. svr.set_keep_alive_timeout(3);
  10797. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10798. res.set_content("Hello World!", "text/plain");
  10799. });
  10800. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10801. auto se = detail::scope_exit([&] {
  10802. svr.stop();
  10803. listen_thread.join();
  10804. ASSERT_FALSE(svr.is_running());
  10805. });
  10806. svr.wait_until_ready();
  10807. Client cli(HOST, PORT);
  10808. cli.set_keep_alive(true);
  10809. auto result = cli.Get("/hi");
  10810. ASSERT_TRUE(result);
  10811. EXPECT_EQ(StatusCode::OK_200, result->status);
  10812. std::this_thread::sleep_for(std::chrono::seconds(5));
  10813. result = cli.Get("/hi");
  10814. ASSERT_TRUE(result);
  10815. EXPECT_EQ(StatusCode::OK_200, result->status);
  10816. }
  10817. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10818. Server svr;
  10819. svr.set_keep_alive_max_count(0);
  10820. std::set<int> remote_ports;
  10821. svr.Get("/hi", [&](const Request &req, Response &res) {
  10822. remote_ports.insert(req.remote_port);
  10823. res.set_content("hi", "text/plain");
  10824. });
  10825. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10826. auto se = detail::scope_exit([&] {
  10827. svr.stop();
  10828. listen_thread.join();
  10829. ASSERT_FALSE(svr.is_running());
  10830. });
  10831. svr.wait_until_ready();
  10832. Client cli(HOST, PORT);
  10833. cli.set_keep_alive(true);
  10834. for (int i = 0; i < 3; i++) {
  10835. auto res = cli.Get("/hi");
  10836. ASSERT_TRUE(res);
  10837. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10838. }
  10839. // All three over one connection
  10840. EXPECT_EQ(1u, remote_ports.size());
  10841. }
  10842. TEST(KeepAliveTest, Issue1959) {
  10843. Server svr;
  10844. svr.set_keep_alive_timeout(5);
  10845. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10846. res.set_content("a", "text/plain");
  10847. });
  10848. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10849. auto se = detail::scope_exit([&] {
  10850. if (!svr.is_running()) return;
  10851. svr.stop();
  10852. listen_thread.join();
  10853. ASSERT_FALSE(svr.is_running());
  10854. });
  10855. svr.wait_until_ready();
  10856. Client cli("localhost", PORT);
  10857. cli.set_keep_alive(true);
  10858. using namespace std::chrono;
  10859. auto start = steady_clock::now();
  10860. cli.Get("/a");
  10861. svr.stop();
  10862. listen_thread.join();
  10863. auto end = steady_clock::now();
  10864. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10865. EXPECT_LT(elapsed, 5000);
  10866. }
  10867. #ifdef CPPHTTPLIB_SSL_ENABLED
  10868. TEST(KeepAliveTest, SSLClientReconnection) {
  10869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10870. ASSERT_TRUE(svr.is_valid());
  10871. svr.set_keep_alive_timeout(1);
  10872. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10873. res.set_content("Hello World!", "text/plain");
  10874. });
  10875. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10876. auto se = detail::scope_exit([&] {
  10877. svr.stop();
  10878. listen_thread.join();
  10879. ASSERT_FALSE(svr.is_running());
  10880. });
  10881. svr.wait_until_ready();
  10882. SSLClient cli(HOST, PORT);
  10883. cli.enable_server_certificate_verification(false);
  10884. cli.set_keep_alive(true);
  10885. auto result = cli.Get("/hi");
  10886. ASSERT_TRUE(result);
  10887. EXPECT_EQ(StatusCode::OK_200, result->status);
  10888. result = cli.Get("/hi");
  10889. ASSERT_TRUE(result);
  10890. EXPECT_EQ(StatusCode::OK_200, result->status);
  10891. std::this_thread::sleep_for(std::chrono::seconds(2));
  10892. // Recoonect
  10893. result = cli.Get("/hi");
  10894. ASSERT_TRUE(result);
  10895. EXPECT_EQ(StatusCode::OK_200, result->status);
  10896. result = cli.Get("/hi");
  10897. ASSERT_TRUE(result);
  10898. EXPECT_EQ(StatusCode::OK_200, result->status);
  10899. }
  10900. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10902. ASSERT_TRUE(svr.is_valid());
  10903. svr.set_keep_alive_timeout(1);
  10904. std::string content = "reconnect";
  10905. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10906. res.set_content("Hello World!", "text/plain");
  10907. });
  10908. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10909. auto se = detail::scope_exit([&] {
  10910. svr.stop();
  10911. listen_thread.join();
  10912. ASSERT_FALSE(svr.is_running());
  10913. });
  10914. svr.wait_until_ready();
  10915. SSLClient cli(HOST, PORT);
  10916. cli.enable_server_certificate_verification(false);
  10917. cli.set_keep_alive(true);
  10918. auto result = cli.Post(
  10919. "/hi", content.size(),
  10920. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10921. sink.write(content.c_str(), content.size());
  10922. return true;
  10923. },
  10924. "text/plain");
  10925. ASSERT_TRUE(result);
  10926. EXPECT_EQ(200, result->status);
  10927. std::this_thread::sleep_for(std::chrono::seconds(2));
  10928. // Recoonect
  10929. result = cli.Post(
  10930. "/hi", content.size(),
  10931. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10932. sink.write(content.c_str(), content.size());
  10933. return true;
  10934. },
  10935. "text/plain");
  10936. ASSERT_TRUE(result);
  10937. EXPECT_EQ(200, result->status);
  10938. result = cli.Post(
  10939. "/hi", content.size(),
  10940. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10941. sink.write(content.c_str(), content.size());
  10942. return true;
  10943. },
  10944. "text/plain");
  10945. ASSERT_TRUE(result);
  10946. EXPECT_EQ(200, result->status);
  10947. }
  10948. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10949. using namespace httplib::tls;
  10950. {
  10951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10952. ASSERT_TRUE(svr.is_valid());
  10953. svr.Get("/sni", [&](const Request &req, Response &res) {
  10954. std::string expected = req.sni();
  10955. EXPECT_EQ(expected, req.get_param_value("expected"));
  10956. res.set_content("ok", "text/plain");
  10957. });
  10958. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10959. auto se = detail::scope_exit([&] {
  10960. svr.stop();
  10961. listen_thread.join();
  10962. ASSERT_FALSE(svr.is_running());
  10963. });
  10964. svr.wait_until_ready();
  10965. {
  10966. SSLClient cli("localhost", PORT);
  10967. cli.enable_server_certificate_verification(false);
  10968. auto res = cli.Get("/sni?expected=localhost");
  10969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10970. }
  10971. {
  10972. SSLClient cli("::1", PORT);
  10973. cli.enable_server_certificate_verification(false);
  10974. auto res = cli.Get("/sni?expected=");
  10975. // NOTE: This may fail if the server is listening on IPv4 only
  10976. // (e.g., when localhost resolves to 127.0.0.1 only)
  10977. if (res) {
  10978. EXPECT_EQ(StatusCode::OK_200, res->status);
  10979. } else {
  10980. EXPECT_EQ(Error::Connection, res.error());
  10981. }
  10982. }
  10983. }
  10984. }
  10985. #endif
  10986. TEST(ClientProblemDetectionTest, ContentProvider) {
  10987. Server svr;
  10988. size_t content_length = 1024 * 1024;
  10989. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10990. res.set_content_provider(
  10991. content_length, "text/plain",
  10992. [&](size_t offset, size_t length, DataSink &sink) {
  10993. auto out_len = std::min(length, static_cast<size_t>(1024));
  10994. std::string out(out_len, '@');
  10995. sink.write(out.data(), out_len);
  10996. return offset < 4096;
  10997. },
  10998. [](bool success) { ASSERT_FALSE(success); });
  10999. });
  11000. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11001. res.set_content_provider(
  11002. 0, "text/plain",
  11003. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11004. EXPECT_TRUE(false);
  11005. return true;
  11006. },
  11007. [](bool success) { ASSERT_FALSE(success); });
  11008. });
  11009. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11010. auto se = detail::scope_exit([&] {
  11011. svr.stop();
  11012. listen_thread.join();
  11013. ASSERT_FALSE(svr.is_running());
  11014. });
  11015. svr.wait_until_ready();
  11016. Client cli("localhost", PORT);
  11017. {
  11018. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11019. size_t /*data_length*/) { return false; });
  11020. ASSERT_FALSE(res);
  11021. }
  11022. {
  11023. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11024. size_t /*data_length*/) { return false; });
  11025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11026. }
  11027. }
  11028. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11029. // A provider that reports success without writing anything and without
  11030. // calling done() used to be handed the same offset and length again on every
  11031. // pass, so it spun for as long as the peer stayed connected.
  11032. Server svr;
  11033. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11034. res.set_content("ok", "text/plain");
  11035. });
  11036. auto port = svr.bind_to_any_port(HOST);
  11037. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11038. auto se = detail::scope_exit([&] {
  11039. svr.stop();
  11040. listen_thread.join();
  11041. ASSERT_FALSE(svr.is_running());
  11042. });
  11043. svr.wait_until_ready();
  11044. std::atomic<int> call_count{0};
  11045. Client cli(HOST, port);
  11046. auto res = cli.Post(
  11047. "/", 1024,
  11048. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11049. // Give up after enough passes to show the spin, so that losing the
  11050. // check below fails this test instead of hanging it.
  11051. return ++call_count < 100;
  11052. },
  11053. "text/plain");
  11054. ASSERT_FALSE(res);
  11055. EXPECT_EQ(Error::Write, res.error());
  11056. EXPECT_EQ(1, call_count.load());
  11057. }
  11058. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11059. // A writer only has to assign `write`. The other three used to be left as
  11060. // empty std::functions, so a provider calling one threw
  11061. // std::bad_function_call out of the thread running it and took the whole
  11062. // process down.
  11063. DataSink sink;
  11064. std::string written;
  11065. sink.write = [&](const char *data, size_t data_len) {
  11066. written.append(data, data_len);
  11067. return true;
  11068. };
  11069. EXPECT_TRUE(sink.is_writable());
  11070. sink.done();
  11071. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11072. EXPECT_TRUE(written.empty());
  11073. }
  11074. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11075. // A sink that cannot carry trailers still has to finish.
  11076. DataSink sink;
  11077. auto done_count = 0;
  11078. sink.done = [&]() { done_count++; };
  11079. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11080. EXPECT_EQ(1, done_count);
  11081. }
  11082. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11083. Server svr;
  11084. const std::string body(4096, 'x');
  11085. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11086. res.set_content_provider(body.size(), "text/plain",
  11087. [&](size_t offset, size_t length, DataSink &sink) {
  11088. sink.write(body.data() + offset, length);
  11089. sink.done();
  11090. return true;
  11091. });
  11092. });
  11093. auto port = svr.bind_to_any_port(HOST);
  11094. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11095. auto se = detail::scope_exit([&] {
  11096. svr.stop();
  11097. listen_thread.join();
  11098. ASSERT_FALSE(svr.is_running());
  11099. });
  11100. svr.wait_until_ready();
  11101. Client cli(HOST, port);
  11102. auto res = cli.Get("/");
  11103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11104. EXPECT_EQ(StatusCode::OK_200, res->status);
  11105. EXPECT_EQ(body, res->body);
  11106. }
  11107. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11108. Server svr;
  11109. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11110. res.set_content_provider(
  11111. 1024, "text/plain",
  11112. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11113. sink.write("hello", 5);
  11114. sink.done(); // short of the 1024 bytes the response promised
  11115. return true;
  11116. });
  11117. });
  11118. auto port = svr.bind_to_any_port(HOST);
  11119. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11120. auto se = detail::scope_exit([&] {
  11121. svr.stop();
  11122. listen_thread.join();
  11123. ASSERT_FALSE(svr.is_running());
  11124. });
  11125. svr.wait_until_ready();
  11126. Client cli(HOST, port);
  11127. cli.set_read_timeout(5, 0);
  11128. // The response is short of its Content-Length, so the client cannot read a
  11129. // complete body. What matters is that this returns at all: a no-op done()
  11130. // would leave the writer looping over a provider that never makes progress.
  11131. auto res = cli.Get("/");
  11132. EXPECT_FALSE(res);
  11133. }
  11134. // Read as the next response by a peer that sees it after a framed body.
  11135. static const std::string smuggled_response =
  11136. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11137. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11138. Server svr;
  11139. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11140. res.set_content_provider(
  11141. 5, "text/plain",
  11142. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11143. auto data = "AAAAA" + smuggled_response;
  11144. sink.write(data.data(), data.size());
  11145. return true;
  11146. });
  11147. });
  11148. thread t = thread([&] { svr.listen(HOST, PORT); });
  11149. auto se = detail::scope_exit([&] {
  11150. svr.stop();
  11151. t.join();
  11152. ASSERT_FALSE(svr.is_running());
  11153. });
  11154. svr.wait_until_ready();
  11155. std::string resp;
  11156. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11157. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11158. resp.clear();
  11159. ASSERT_TRUE(send_request(
  11160. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11161. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11162. }
  11163. TEST(NoContentTest, BodyIsNotSent) {
  11164. Server svr;
  11165. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11166. res.status = StatusCode::NoContent_204;
  11167. res.set_content(smuggled_response, "text/plain");
  11168. });
  11169. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11170. res.status = StatusCode::NotModified_304;
  11171. res.set_chunked_content_provider(
  11172. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11173. sink.write(smuggled_response.data(), smuggled_response.size());
  11174. sink.done();
  11175. return true;
  11176. });
  11177. });
  11178. thread t = thread([&] { svr.listen(HOST, PORT); });
  11179. auto se = detail::scope_exit([&] {
  11180. svr.stop();
  11181. t.join();
  11182. ASSERT_FALSE(svr.is_running());
  11183. });
  11184. svr.wait_until_ready();
  11185. for (auto path : {"/204", "/304"}) {
  11186. std::string resp;
  11187. ASSERT_TRUE(send_request(
  11188. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11189. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11190. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11191. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11192. }
  11193. }
  11194. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11195. Server svr;
  11196. std::atomic<bool> smuggled(false);
  11197. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11198. res.set_content("ok", "text/plain");
  11199. });
  11200. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11201. smuggled = true;
  11202. });
  11203. auto port = svr.bind_to_any_port(HOST);
  11204. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11205. auto se = detail::scope_exit([&] {
  11206. svr.stop();
  11207. listen_thread.join();
  11208. ASSERT_FALSE(svr.is_running());
  11209. });
  11210. svr.wait_until_ready();
  11211. // What follows the body would be read as the next request.
  11212. Client cli(HOST, port);
  11213. auto res = cli.Post(
  11214. "/", 5,
  11215. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11216. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11217. sink.write(data.data(), data.size());
  11218. return true;
  11219. },
  11220. "text/plain");
  11221. ASSERT_FALSE(res);
  11222. EXPECT_EQ(Error::Write, res.error());
  11223. EXPECT_FALSE(smuggled);
  11224. }
  11225. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11226. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11227. // The compressed path builds the whole body before connecting, so this
  11228. // fails client-side and never reaches a server.
  11229. Client cli(HOST, PORT);
  11230. cli.set_compress(true);
  11231. auto res = cli.Post(
  11232. "/", 1024,
  11233. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11234. sink.write("hello", 5);
  11235. sink.done(); // short of the 1024 bytes the request announced
  11236. return true;
  11237. },
  11238. "text/plain");
  11239. ASSERT_FALSE(res);
  11240. EXPECT_EQ(Error::Write, res.error());
  11241. }
  11242. #endif
  11243. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11244. Server svr;
  11245. svr.set_error_handler([](Request const &, Response &res) -> void {
  11246. res.set_chunked_content_provider(
  11247. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11248. sink.os << "hello";
  11249. sink.os << "world";
  11250. sink.done();
  11251. return true;
  11252. });
  11253. });
  11254. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11255. auto se = detail::scope_exit([&] {
  11256. svr.stop();
  11257. listen_thread.join();
  11258. ASSERT_FALSE(svr.is_running());
  11259. });
  11260. svr.wait_until_ready();
  11261. Client cli("localhost", PORT);
  11262. auto res = cli.Get("/");
  11263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11265. EXPECT_EQ("helloworld", res->body);
  11266. }
  11267. // A body set after a content provider must replace it, not be sent through it.
  11268. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11269. Server svr;
  11270. svr.set_mount_point("/", "./www");
  11271. svr.set_file_request_handler([](const Request &req, Response &res) {
  11272. if (req.path == "/dir/test.html") {
  11273. res.status = StatusCode::Forbidden_403;
  11274. res.set_content(std::string(5000, 'D'), "text/plain");
  11275. } else if (req.path == "/file") {
  11276. res.status = StatusCode::Forbidden_403;
  11277. res.body = "Denied";
  11278. }
  11279. });
  11280. auto port = svr.bind_to_any_port(HOST);
  11281. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11282. auto se = detail::scope_exit([&] {
  11283. svr.stop();
  11284. t.join();
  11285. ASSERT_FALSE(svr.is_running());
  11286. });
  11287. svr.wait_until_ready();
  11288. Client cli(HOST, port);
  11289. {
  11290. auto res = cli.Get("/dir/test.html");
  11291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11292. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11293. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11294. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11295. }
  11296. {
  11297. auto res = cli.Get("/file");
  11298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11299. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11300. EXPECT_EQ("Denied", res->body);
  11301. }
  11302. {
  11303. auto res = cli.Get("/dir/index.html");
  11304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11305. EXPECT_EQ(StatusCode::OK_200, res->status);
  11306. EXPECT_EQ(0U, res->body.find("<html>"));
  11307. }
  11308. }
  11309. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11310. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11311. Server svr;
  11312. std::vector<bool> released;
  11313. std::mutex released_mutex;
  11314. auto releaser = [&](bool success) {
  11315. std::lock_guard<std::mutex> guard(released_mutex);
  11316. released.push_back(success);
  11317. };
  11318. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11319. return sink.write(&"hello"[offset], length);
  11320. };
  11321. svr.Get("/sized", [&](const Request &, Response &res) {
  11322. res.status = StatusCode::NotFound_404;
  11323. res.set_content_provider(5, "text/plain", provider, releaser);
  11324. });
  11325. svr.Get("/chunked", [&](const Request &, Response &res) {
  11326. res.status = StatusCode::ServiceUnavailable_503;
  11327. res.set_chunked_content_provider(
  11328. "text/plain",
  11329. [](size_t, DataSink &sink) {
  11330. sink.os << "chunk";
  11331. sink.done();
  11332. return true;
  11333. },
  11334. releaser);
  11335. });
  11336. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11337. res.set_content_provider(5, "text/plain", provider, releaser);
  11338. throw std::runtime_error("after the provider");
  11339. });
  11340. svr.set_error_handler([](const Request &req, Response &res) {
  11341. // Leave the exception handler's content to it.
  11342. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11343. res.set_content(std::string(1000, 'E'), "text/html");
  11344. return Server::HandlerResponse::Handled;
  11345. });
  11346. svr.set_exception_handler(
  11347. [](const Request &, Response &res, std::exception_ptr) {
  11348. res.status = StatusCode::InternalServerError_500;
  11349. res.set_content(std::string(1000, 'X'), "text/html");
  11350. });
  11351. auto port = svr.bind_to_any_port(HOST);
  11352. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11353. auto se = detail::scope_exit([&] {
  11354. svr.stop();
  11355. t.join();
  11356. ASSERT_FALSE(svr.is_running());
  11357. });
  11358. svr.wait_until_ready();
  11359. Client cli(HOST, port);
  11360. {
  11361. auto res = cli.Get("/sized");
  11362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11363. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11364. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11365. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11366. }
  11367. {
  11368. auto res = cli.Get("/chunked");
  11369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11370. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11371. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11372. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11373. }
  11374. {
  11375. auto res = cli.Get("/throw");
  11376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11377. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11378. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11379. }
  11380. std::lock_guard<std::mutex> guard(released_mutex);
  11381. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11382. }
  11383. #endif
  11384. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11385. Server svr;
  11386. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11387. return sink.write(&"abc"[offset], length);
  11388. };
  11389. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11390. res.set_file_content("./www/dir/test.html");
  11391. res.set_content("body", "text/plain");
  11392. });
  11393. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11394. res.set_content(std::string(100, 'B'), "text/plain");
  11395. res.set_file_content("./www/dir/test.html");
  11396. });
  11397. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11398. res.set_content(std::string(100, 'B'), "text/plain");
  11399. res.set_content_provider(3, "text/x-provider", abc);
  11400. });
  11401. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11402. res.set_content_provider(3, "text/x-provider", abc);
  11403. res.set_content(std::string(100, 'B'), "text/plain");
  11404. });
  11405. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11406. res.set_content_provider(3, "text/x-provider", abc);
  11407. res.set_file_content("./www/dir/test.html", "text/x-file");
  11408. });
  11409. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11410. res.set_file_content("./www/dir/test.html");
  11411. res.set_header("Content-Type", "text/x-handler");
  11412. });
  11413. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11414. res.set_content_provider(3, "text/plain", abc);
  11415. res.body = "direct";
  11416. });
  11417. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11418. res.set_file_content("./www/dir/test.html");
  11419. res.body = "direct";
  11420. });
  11421. auto port = svr.bind_to_any_port(HOST);
  11422. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11423. auto se = detail::scope_exit([&] {
  11424. svr.stop();
  11425. t.join();
  11426. ASSERT_FALSE(svr.is_running());
  11427. });
  11428. svr.wait_until_ready();
  11429. Client cli(HOST, port);
  11430. auto expect_body = [&](const char *path, const std::string &body,
  11431. const std::string &type) {
  11432. // Uncompressed, so Content-Length can be compared with the body.
  11433. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11434. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11435. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11436. EXPECT_EQ(body, res->body) << path;
  11437. EXPECT_EQ(std::to_string(body.size()),
  11438. res->get_header_value("Content-Length"))
  11439. << path;
  11440. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11441. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11442. };
  11443. expect_body("/file-then-body", "body", "text/plain");
  11444. expect_body("/body-then-file", "test.html", "text/html");
  11445. expect_body("/body-then-provider", "abc", "text/x-provider");
  11446. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11447. expect_body("/provider-then-file", "test.html", "text/x-file");
  11448. expect_body("/file-then-header", "test.html", "text/x-handler");
  11449. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11450. expect_body("/file-then-direct-body", "direct", "text/plain");
  11451. // Ranges are checked against the body, not the dropped provider.
  11452. {
  11453. auto res = cli.Get("/provider-then-direct-body",
  11454. Headers{{make_range_header({{1, 2}})}});
  11455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11456. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11457. EXPECT_EQ("ir", res->body);
  11458. }
  11459. {
  11460. auto res = cli.Get("/file-then-direct-body",
  11461. Headers{{make_range_header({{7, 8}})}});
  11462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11463. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11464. }
  11465. }
  11466. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11467. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11468. const char *path = "./truncated_while_served.txt";
  11469. const size_t size = 32 * 1024 * 1024;
  11470. {
  11471. std::ofstream f(path, std::ios::binary);
  11472. f << std::string(size, 'x');
  11473. }
  11474. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11475. // Over TLS, where the bytes are encrypted in this process rather than
  11476. // copied by send().
  11477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11478. svr.Get("/file", [&](const Request &, Response &res) {
  11479. res.set_file_content(path, "text/plain");
  11480. });
  11481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11482. auto se = detail::scope_exit([&] {
  11483. svr.stop();
  11484. thread.join();
  11485. ASSERT_FALSE(svr.is_running());
  11486. });
  11487. svr.wait_until_ready();
  11488. // The file shrinks once the first bytes are in, as a rewrite in place
  11489. // would, and reading the mapping past its new end used to raise SIGBUS.
  11490. SSLClient cli(HOST, PORT);
  11491. cli.enable_server_certificate_verification(false);
  11492. size_t received = 0;
  11493. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11494. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11495. received += len;
  11496. return true;
  11497. });
  11498. EXPECT_FALSE(res);
  11499. EXPECT_LT(received, size);
  11500. }
  11501. #endif
  11502. // Forward declaration (see the base64_encode note).
  11503. namespace httplib {
  11504. namespace detail {
  11505. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11506. const std::string &content_type,
  11507. EncodingType encoding);
  11508. } // namespace detail
  11509. } // namespace httplib
  11510. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11511. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11512. ASSERT_TRUE(mm->is_open());
  11513. Response res;
  11514. detail::set_file_content_provider(res, mm, "text/html",
  11515. detail::EncodingType::None);
  11516. std::string out;
  11517. DataSink sink;
  11518. sink.write = [&](const char *d, size_t l) {
  11519. out.append(d, l);
  11520. return true;
  11521. };
  11522. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11523. EXPECT_EQ("test.html", out);
  11524. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11525. EXPECT_EQ("test.html", out);
  11526. }
  11527. TEST(LongPollingTest, ClientCloseDetection) {
  11528. Server svr;
  11529. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11530. res.set_chunked_content_provider(
  11531. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11532. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11533. sink.os << "hello";
  11534. auto count = 10;
  11535. while (count > 0 && sink.is_writable()) {
  11536. this_thread::sleep_for(chrono::milliseconds(10));
  11537. count--;
  11538. }
  11539. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11540. return true;
  11541. });
  11542. });
  11543. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11544. auto se = detail::scope_exit([&] {
  11545. svr.stop();
  11546. listen_thread.join();
  11547. ASSERT_FALSE(svr.is_running());
  11548. });
  11549. svr.wait_until_ready();
  11550. Client cli("localhost", PORT);
  11551. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11552. EXPECT_EQ("hello", string(data, data_length));
  11553. return false; // close the socket immediately.
  11554. });
  11555. ASSERT_FALSE(res);
  11556. }
  11557. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11558. Server svr;
  11559. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11560. res.set_chunked_content_provider(
  11561. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11562. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11563. sink.os << "hello";
  11564. EXPECT_TRUE(sink.os.good());
  11565. // Wait for the client to close the connection
  11566. auto count = 10;
  11567. while (count > 0 && sink.is_writable()) {
  11568. this_thread::sleep_for(chrono::milliseconds(10));
  11569. count--;
  11570. }
  11571. // After client disconnect, write repeatedly until the socket
  11572. // write actually fails (small writes may be absorbed by the
  11573. // kernel buffer)
  11574. std::string chunk(1024, 'x');
  11575. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11576. sink.os << chunk;
  11577. }
  11578. EXPECT_TRUE(sink.os.fail());
  11579. return true;
  11580. });
  11581. });
  11582. auto port = svr.bind_to_any_port("localhost");
  11583. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11584. auto se = detail::scope_exit([&] {
  11585. svr.stop();
  11586. listen_thread.join();
  11587. ASSERT_FALSE(svr.is_running());
  11588. });
  11589. svr.wait_until_ready();
  11590. Client cli("localhost", port);
  11591. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11592. EXPECT_EQ("hello", string(data, data_length));
  11593. return false; // close the socket immediately.
  11594. });
  11595. ASSERT_FALSE(res);
  11596. }
  11597. TEST(GetWithParametersTest, GetWithParameters) {
  11598. Server svr;
  11599. svr.Get("/", [&](const Request &req, Response &) {
  11600. EXPECT_EQ("world", req.get_param_value("hello"));
  11601. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11602. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11603. });
  11604. svr.Get("/params", [&](const Request &req, Response &) {
  11605. EXPECT_EQ("world", req.get_param_value("hello"));
  11606. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11607. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11608. });
  11609. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11610. EXPECT_EQ("resource-id", req.matches[1]);
  11611. EXPECT_EQ("foo", req.get_param_value("param1"));
  11612. EXPECT_EQ("bar", req.get_param_value("param2"));
  11613. });
  11614. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11615. EXPECT_EQ("user-id", req.path_params.at("id"));
  11616. EXPECT_EQ("foo", req.get_param_value("param1"));
  11617. EXPECT_EQ("bar", req.get_param_value("param2"));
  11618. });
  11619. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11620. auto se = detail::scope_exit([&] {
  11621. svr.stop();
  11622. listen_thread.join();
  11623. ASSERT_FALSE(svr.is_running());
  11624. });
  11625. svr.wait_until_ready();
  11626. {
  11627. Client cli(HOST, PORT);
  11628. Params params;
  11629. params.emplace("hello", "world");
  11630. params.emplace("hello2", "world2");
  11631. params.emplace("hello3", "world3");
  11632. auto res = cli.Get("/", params, Headers{});
  11633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11634. EXPECT_EQ(StatusCode::OK_200, res->status);
  11635. }
  11636. {
  11637. Client cli(HOST, PORT);
  11638. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11640. EXPECT_EQ(StatusCode::OK_200, res->status);
  11641. }
  11642. {
  11643. Client cli(HOST, PORT);
  11644. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11646. EXPECT_EQ(StatusCode::OK_200, res->status);
  11647. }
  11648. {
  11649. Client cli(HOST, PORT);
  11650. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11652. EXPECT_EQ(StatusCode::OK_200, res->status);
  11653. }
  11654. }
  11655. TEST(GetWithParametersTest, GetWithParameters2) {
  11656. Server svr;
  11657. svr.Get("/", [&](const Request &req, Response &res) {
  11658. auto text = req.get_param_value("hello");
  11659. res.set_content(text, "text/plain");
  11660. });
  11661. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11662. auto se = detail::scope_exit([&] {
  11663. svr.stop();
  11664. listen_thread.join();
  11665. ASSERT_FALSE(svr.is_running());
  11666. });
  11667. svr.wait_until_ready();
  11668. Client cli("localhost", PORT);
  11669. Params params;
  11670. params.emplace("hello", "world");
  11671. std::string body;
  11672. auto res = cli.Get("/", params, Headers{},
  11673. [&](const char *data, size_t data_length) {
  11674. body.append(data, data_length);
  11675. return true;
  11676. });
  11677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11678. EXPECT_EQ(StatusCode::OK_200, res->status);
  11679. EXPECT_EQ("world", body);
  11680. }
  11681. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11682. Server svr;
  11683. svr.Get("/search", [&](const Request &req, Response &res) {
  11684. auto q = req.get_param_value("q");
  11685. res.set_content(q, "text/plain");
  11686. });
  11687. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11688. auto se = detail::scope_exit([&] {
  11689. svr.stop();
  11690. listen_thread.join();
  11691. ASSERT_FALSE(svr.is_running());
  11692. });
  11693. svr.wait_until_ready();
  11694. Client cli("localhost", PORT);
  11695. // Verify that Get(path, params) works without requiring Headers argument
  11696. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11698. EXPECT_EQ(StatusCode::OK_200, res->status);
  11699. EXPECT_EQ("cpp-httplib", res->body);
  11700. }
  11701. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11702. auto host = "httpbingo.org";
  11703. auto path = std::string{"/range/32"};
  11704. #ifdef CPPHTTPLIB_SSL_ENABLED
  11705. SSLClient cli(host);
  11706. #else
  11707. Client cli(host);
  11708. #endif
  11709. cli.set_default_headers({make_range_header({{1, 10}})});
  11710. cli.set_connection_timeout(5);
  11711. {
  11712. auto res = cli.Get(path);
  11713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11714. EXPECT_EQ("bcdefghijk", res->body);
  11715. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11716. }
  11717. {
  11718. auto res = cli.Get(path);
  11719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11720. EXPECT_EQ("bcdefghijk", res->body);
  11721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11722. }
  11723. }
  11724. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11725. Server svr;
  11726. svr.set_default_headers({{"Hello", "World"}});
  11727. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11728. res.set_content("ok", "text/plain");
  11729. });
  11730. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11731. auto se = detail::scope_exit([&] {
  11732. svr.stop();
  11733. listen_thread.join();
  11734. ASSERT_FALSE(svr.is_running());
  11735. });
  11736. svr.wait_until_ready();
  11737. Client cli("localhost", PORT);
  11738. auto res = cli.Get("/");
  11739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11740. EXPECT_EQ(StatusCode::OK_200, res->status);
  11741. EXPECT_EQ("ok", res->body);
  11742. EXPECT_EQ("World", res->get_header_value("Hello"));
  11743. }
  11744. #ifdef CPPHTTPLIB_SSL_ENABLED
  11745. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11747. ASSERT_TRUE(svr.is_valid());
  11748. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11749. std::this_thread::sleep_for(std::chrono::seconds(2));
  11750. res.set_content("a", "text/plain");
  11751. });
  11752. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11753. res.set_content("b", "text/plain");
  11754. });
  11755. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11756. auto se = detail::scope_exit([&] {
  11757. svr.stop();
  11758. listen_thread.join();
  11759. ASSERT_FALSE(svr.is_running());
  11760. });
  11761. svr.wait_until_ready();
  11762. SSLClient cli("localhost", PORT);
  11763. cli.enable_server_certificate_verification(false);
  11764. cli.set_keep_alive(true);
  11765. cli.set_read_timeout(std::chrono::seconds(1));
  11766. auto resa = cli.Get("/a");
  11767. ASSERT_TRUE(!resa);
  11768. EXPECT_EQ(Error::Read, resa.error());
  11769. auto resb = cli.Get("/b");
  11770. ASSERT_TRUE(resb);
  11771. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11772. EXPECT_EQ("b", resb->body);
  11773. }
  11774. // Closing an idle keep-alive connection sends close_notify and returns. The
  11775. // server must not wait for the client's close_notify: an idle client never
  11776. // sends one, so the worker would be held until the read timeout expires, and
  11777. // stop() would wait for it.
  11778. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11780. ASSERT_TRUE(svr.is_valid());
  11781. svr.set_keep_alive_timeout(1);
  11782. svr.set_read_timeout(10, 0);
  11783. svr.Get("/", [](const Request &, Response &res) {
  11784. res.set_content("ok", "text/plain");
  11785. });
  11786. auto port = svr.bind_to_any_port(HOST);
  11787. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11788. auto se = detail::scope_exit([&] {
  11789. if (listen_thread.joinable()) {
  11790. svr.stop();
  11791. listen_thread.join();
  11792. }
  11793. });
  11794. svr.wait_until_ready();
  11795. SSLClient cli(HOST, port);
  11796. cli.enable_server_certificate_verification(false);
  11797. cli.set_keep_alive(true);
  11798. auto res = cli.Get("/");
  11799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11800. EXPECT_EQ(StatusCode::OK_200, res->status);
  11801. // Stay idle past the keep-alive timeout so the server closes the connection.
  11802. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11803. auto start = std::chrono::steady_clock::now();
  11804. svr.stop();
  11805. listen_thread.join();
  11806. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11807. std::chrono::steady_clock::now() - start)
  11808. .count();
  11809. EXPECT_LT(elapsed, 3000);
  11810. }
  11811. #endif
  11812. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11813. protected:
  11814. ServerTestWithAI_PASSIVE()
  11815. : cli_(HOST, PORT)
  11816. #ifdef CPPHTTPLIB_SSL_ENABLED
  11817. ,
  11818. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11819. #endif
  11820. {
  11821. #ifdef CPPHTTPLIB_SSL_ENABLED
  11822. cli_.enable_server_certificate_verification(false);
  11823. #endif
  11824. }
  11825. virtual void SetUp() {
  11826. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11827. res.set_content("Hello World!", "text/plain");
  11828. });
  11829. t_ = thread(
  11830. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11831. svr_.wait_until_ready();
  11832. }
  11833. virtual void TearDown() {
  11834. svr_.stop();
  11835. t_.join();
  11836. }
  11837. #ifdef CPPHTTPLIB_SSL_ENABLED
  11838. SSLClient cli_;
  11839. SSLServer svr_;
  11840. #else
  11841. Client cli_;
  11842. Server svr_;
  11843. #endif
  11844. thread t_;
  11845. };
  11846. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11847. auto res = cli_.Get("/hi");
  11848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11849. EXPECT_EQ(StatusCode::OK_200, res->status);
  11850. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11851. EXPECT_EQ("Hello World!", res->body);
  11852. }
  11853. class ServerUpDownTest : public ::testing::Test {
  11854. protected:
  11855. ServerUpDownTest() : cli_(HOST, PORT) {}
  11856. virtual void SetUp() {
  11857. t_ = thread([&]() {
  11858. svr_.bind_to_any_port(HOST);
  11859. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11860. ASSERT_TRUE(svr_.listen_after_bind());
  11861. });
  11862. svr_.wait_until_ready();
  11863. }
  11864. virtual void TearDown() {
  11865. svr_.stop();
  11866. t_.join();
  11867. }
  11868. Client cli_;
  11869. Server svr_;
  11870. thread t_;
  11871. };
  11872. TEST_F(ServerUpDownTest, QuickStartStop) {
  11873. // Should not crash, especially when run with
  11874. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11875. }
  11876. class PayloadMaxLengthTest : public ::testing::Test {
  11877. protected:
  11878. PayloadMaxLengthTest()
  11879. : cli_(HOST, PORT)
  11880. #ifdef CPPHTTPLIB_SSL_ENABLED
  11881. ,
  11882. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11883. #endif
  11884. {
  11885. #ifdef CPPHTTPLIB_SSL_ENABLED
  11886. cli_.enable_server_certificate_verification(false);
  11887. #endif
  11888. }
  11889. virtual void SetUp() {
  11890. svr_.set_payload_max_length(8);
  11891. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11892. res.set_content("test", "text/plain");
  11893. });
  11894. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11895. svr_.wait_until_ready();
  11896. }
  11897. virtual void TearDown() {
  11898. svr_.stop();
  11899. t_.join();
  11900. }
  11901. #ifdef CPPHTTPLIB_SSL_ENABLED
  11902. SSLClient cli_;
  11903. SSLServer svr_;
  11904. #else
  11905. Client cli_;
  11906. Server svr_;
  11907. #endif
  11908. thread t_;
  11909. };
  11910. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11911. auto res = cli_.Post("/test", "123456789", "text/plain");
  11912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11913. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11914. res = cli_.Post("/test", "12345678", "text/plain");
  11915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11916. EXPECT_EQ(StatusCode::OK_200, res->status);
  11917. }
  11918. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11919. // Test chunked encoding with payload exceeding the 8-byte limit
  11920. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11921. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11923. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11924. }
  11925. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11926. // Test chunked encoding with payload within the 8-byte limit
  11927. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11928. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11930. EXPECT_EQ(StatusCode::OK_200, res->status);
  11931. }
  11932. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11933. // Test using send_request to send chunked data exceeding payload limit
  11934. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11935. "Host: " +
  11936. std::string(HOST) + ":" + std::to_string(PORT) +
  11937. "\r\n"
  11938. "Transfer-Encoding: chunked\r\n"
  11939. "Connection: close\r\n"
  11940. "\r\n"
  11941. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11942. "0123456789\r\n"
  11943. "0\r\n" // End chunk
  11944. "\r\n";
  11945. std::string response;
  11946. bool result = send_request(1, chunked_request, &response);
  11947. if (!result) {
  11948. // If send_request fails, it might be because the server closed the
  11949. // connection due to payload limit enforcement, which is acceptable
  11950. SUCCEED()
  11951. << "Server rejected oversized chunked request (connection closed)";
  11952. } else {
  11953. // If we got a response, check if it's an error response or connection was
  11954. // closed early Short response length indicates connection was closed due to
  11955. // payload limit
  11956. if (response.length() <= 10) {
  11957. SUCCEED() << "Server closed connection for oversized chunked request";
  11958. } else {
  11959. // Check for error status codes
  11960. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11961. response.find("Payload Too Large") != std::string::npos ||
  11962. response.find("400") != std::string::npos);
  11963. }
  11964. }
  11965. }
  11966. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11967. // Test request without Content-Length header exceeding payload limit
  11968. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11969. "Host: " +
  11970. std::string(HOST) + ":" +
  11971. std::to_string(PORT) +
  11972. "\r\n"
  11973. "Connection: close\r\n"
  11974. "\r\n";
  11975. // Add payload exceeding the 8-byte limit
  11976. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11977. request_without_content_length += large_payload;
  11978. std::string response;
  11979. bool result = send_request(1, request_without_content_length, &response);
  11980. if (!result) {
  11981. // If send_request fails, server likely closed connection due to payload
  11982. // limit
  11983. SUCCEED() << "Server rejected oversized request without Content-Length "
  11984. "(connection closed)";
  11985. } else {
  11986. // Check if server responded with error or closed connection early
  11987. if (response.length() <= 10) {
  11988. SUCCEED() << "Server closed connection for oversized request without "
  11989. "Content-Length";
  11990. } else {
  11991. // Check for error status codes
  11992. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11993. response.find("Payload Too Large") != std::string::npos ||
  11994. response.find("400") != std::string::npos);
  11995. }
  11996. }
  11997. }
  11998. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11999. // Test request without Content-Length header within payload limit
  12000. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12001. "Host: " +
  12002. std::string(HOST) + ":" +
  12003. std::to_string(PORT) +
  12004. "\r\n"
  12005. "Connection: close\r\n"
  12006. "\r\n";
  12007. // Add payload within the 8-byte limit
  12008. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12009. request_without_content_length += small_payload;
  12010. std::string response;
  12011. bool result = send_request(1, request_without_content_length, &response);
  12012. // For requests without Content-Length, the server may have different behavior
  12013. // The key is that it should not reject due to payload limit for small
  12014. // payloads
  12015. if (result) {
  12016. // Check for any HTTP response (success or error, but not connection closed)
  12017. if (response.length() > 10) {
  12018. SUCCEED()
  12019. << "Server processed request without Content-Length within limit";
  12020. } else {
  12021. // Short response might indicate connection closed, which is acceptable
  12022. SUCCEED() << "Server closed connection for request without "
  12023. "Content-Length (acceptable behavior)";
  12024. }
  12025. } else {
  12026. // Connection failure might be due to protocol requirements
  12027. SUCCEED() << "Connection issue with request without Content-Length "
  12028. "(environment-specific)";
  12029. }
  12030. }
  12031. class LargePayloadMaxLengthTest : public ::testing::Test {
  12032. protected:
  12033. LargePayloadMaxLengthTest()
  12034. : cli_(HOST, PORT)
  12035. #ifdef CPPHTTPLIB_SSL_ENABLED
  12036. ,
  12037. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12038. #endif
  12039. {
  12040. #ifdef CPPHTTPLIB_SSL_ENABLED
  12041. cli_.enable_server_certificate_verification(false);
  12042. #endif
  12043. }
  12044. virtual void SetUp() {
  12045. // Set 10MB payload limit
  12046. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12047. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12048. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12049. res.set_content("Large payload test", "text/plain");
  12050. });
  12051. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12052. svr_.wait_until_ready();
  12053. }
  12054. virtual void TearDown() {
  12055. svr_.stop();
  12056. t_.join();
  12057. }
  12058. #ifdef CPPHTTPLIB_SSL_ENABLED
  12059. SSLClient cli_;
  12060. SSLServer svr_;
  12061. #else
  12062. Client cli_;
  12063. Server svr_;
  12064. #endif
  12065. thread t_;
  12066. };
  12067. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12068. // Test chunked encoding with payload within 10MB limit
  12069. std::string medium_payload(5 * 1024 * 1024,
  12070. 'A'); // 5MB payload, within 10MB limit
  12071. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12073. EXPECT_EQ(StatusCode::OK_200, res->status);
  12074. }
  12075. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12076. // Test chunked encoding with payload exceeding 10MB limit
  12077. std::string large_payload(12 * 1024 * 1024,
  12078. 'B'); // 12MB payload, exceeds 10MB limit
  12079. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12080. // Server may either return 413 or close the connection
  12081. if (res) {
  12082. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12083. } else {
  12084. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12085. }
  12086. }
  12087. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12088. // Test request without Content-Length header within 10MB limit
  12089. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12090. "Host: " +
  12091. std::string(HOST) + ":" +
  12092. std::to_string(PORT) +
  12093. "\r\n"
  12094. "Connection: close\r\n"
  12095. "\r\n";
  12096. // Add 1MB payload (within 10MB limit)
  12097. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12098. request_without_content_length += medium_payload;
  12099. std::string response;
  12100. bool result = send_request(5, request_without_content_length, &response);
  12101. if (result) {
  12102. // Should get a proper HTTP response for payloads within limit
  12103. if (response.length() > 10) {
  12104. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12105. "10MB limit";
  12106. } else {
  12107. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12108. "Content-Length)";
  12109. }
  12110. } else {
  12111. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12112. }
  12113. }
  12114. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12115. // Test request without Content-Length header exceeding 10MB limit
  12116. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12117. "Host: " +
  12118. std::string(HOST) + ":" +
  12119. std::to_string(PORT) +
  12120. "\r\n"
  12121. "Connection: close\r\n"
  12122. "\r\n";
  12123. // Add 12MB payload (exceeds 10MB limit)
  12124. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12125. request_without_content_length += large_payload;
  12126. std::string response;
  12127. bool result = send_request(10, request_without_content_length, &response);
  12128. if (!result) {
  12129. // Server should close connection due to payload limit
  12130. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12131. "(connection closed)";
  12132. } else {
  12133. // Check for error response
  12134. if (response.length() <= 10) {
  12135. SUCCEED()
  12136. << "Server closed connection for 12MB request exceeding 10MB limit";
  12137. } else {
  12138. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12139. response.find("Payload Too Large") != std::string::npos ||
  12140. response.find("400") != std::string::npos);
  12141. }
  12142. }
  12143. }
  12144. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12145. Server svr;
  12146. svr.Get("/", [](const Request &, Response &res) {
  12147. // Claims the most the client accepts, far more than it sends, then drops
  12148. // the connection.
  12149. res.set_content_provider(std::string().max_size(), "text/plain",
  12150. [](size_t, size_t, DataSink &sink) {
  12151. sink.write("abc", 3);
  12152. return false;
  12153. });
  12154. });
  12155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12156. auto se = detail::scope_exit([&] {
  12157. svr.stop();
  12158. thread.join();
  12159. ASSERT_FALSE(svr.is_running());
  12160. });
  12161. svr.wait_until_ready();
  12162. Client cli(HOST, PORT);
  12163. cli.set_payload_max_length(0);
  12164. EXPECT_FALSE(cli.Get("/"));
  12165. }
  12166. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12167. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12168. // path.
  12169. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12170. Server svr;
  12171. const size_t LIMIT = 64 * 1024; // 64KB
  12172. svr.set_payload_max_length(LIMIT);
  12173. size_t total = 0;
  12174. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12175. const ContentReader &content_reader) {
  12176. content_reader([&](const char * /*data*/, size_t len) {
  12177. total += len;
  12178. return true;
  12179. });
  12180. res.status = 200;
  12181. res.set_content("stream_ok", "text/plain");
  12182. });
  12183. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12184. auto se = detail::scope_exit([&] {
  12185. svr.stop();
  12186. thread.join();
  12187. ASSERT_FALSE(svr.is_running());
  12188. });
  12189. svr.wait_until_ready();
  12190. // Prepare 256KB raw data and gzip-compress it
  12191. std::string raw(256 * 1024, 'A');
  12192. std::string gz;
  12193. {
  12194. z_stream zs{};
  12195. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12196. Z_DEFAULT_STRATEGY);
  12197. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12198. zs.avail_in = static_cast<uInt>(raw.size());
  12199. char outbuf[4096];
  12200. int ret;
  12201. do {
  12202. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12203. zs.avail_out = sizeof(outbuf);
  12204. ret = deflate(&zs, Z_FINISH);
  12205. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12206. } while (ret != Z_STREAM_END);
  12207. deflateEnd(&zs);
  12208. }
  12209. Client cli(HOST, PORT);
  12210. cli.set_connection_timeout(std::chrono::seconds(5));
  12211. Headers headers = {{"Content-Encoding", "gzip"}};
  12212. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12213. "application/octet-stream");
  12214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12215. // Server must reject oversized decompressed payloads with 413.
  12216. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12217. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12218. EXPECT_LE(total, LIMIT);
  12219. }
  12220. #ifndef CPPHTTPLIB_SSL_ENABLED
  12221. // For a request with neither Content-Length nor Transfer-Encoding, the
  12222. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12223. // compressed wire bytes straight to the ContentReader without ever routing
  12224. // them through the decompressor, so payload_max_length_ only bounded the
  12225. // compressed size on the wire, not the decompressed size.
  12226. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12227. Server svr;
  12228. const size_t LIMIT = 64 * 1024; // 64KB
  12229. svr.set_payload_max_length(LIMIT);
  12230. size_t total = 0;
  12231. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12232. const ContentReader &content_reader) {
  12233. content_reader([&](const char * /*data*/, size_t len) {
  12234. total += len;
  12235. return true;
  12236. });
  12237. res.status = 200;
  12238. res.set_content("stream_ok", "text/plain");
  12239. });
  12240. auto port = svr.bind_to_any_port(HOST);
  12241. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12242. auto se = detail::scope_exit([&] {
  12243. svr.stop();
  12244. thread.join();
  12245. ASSERT_FALSE(svr.is_running());
  12246. });
  12247. svr.wait_until_ready();
  12248. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12249. // StreamingGzipDecompression test above.
  12250. std::string raw(256 * 1024, 'A');
  12251. std::string gz;
  12252. {
  12253. httplib::detail::gzip_compressor compressor;
  12254. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12255. [&](const char *chunk, size_t len) {
  12256. gz.append(chunk, len);
  12257. return true;
  12258. });
  12259. ASSERT_TRUE(result);
  12260. }
  12261. // Send the gzip body over raw TCP with neither Content-Length nor
  12262. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12263. // kicks in.
  12264. std::string req = "POST /stream HTTP/1.1\r\n"
  12265. "Host: " +
  12266. std::string(HOST) + ":" + std::to_string(port) +
  12267. "\r\n"
  12268. "Content-Encoding: gzip\r\n"
  12269. "Connection: close\r\n"
  12270. "\r\n" +
  12271. gz;
  12272. std::string response;
  12273. ASSERT_TRUE(send_request(5, req, &response, port));
  12274. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12275. EXPECT_LE(total, LIMIT);
  12276. }
  12277. #endif
  12278. #endif
  12279. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12280. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12281. // the payload must be passed through untouched instead of being rejected.
  12282. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12283. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12284. Server svr;
  12285. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12286. res.set_content(body, "image/jpeg");
  12287. res.set_header("Content-Encoding", "UTF-8");
  12288. });
  12289. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12290. res.set_content(body, "image/jpeg");
  12291. res.set_header("Content-Encoding", "identity");
  12292. });
  12293. svr.Post("/echo", [](const Request &req, Response &res) {
  12294. res.set_content(req.body, "image/jpeg");
  12295. });
  12296. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12297. auto se = detail::scope_exit([&] {
  12298. svr.stop();
  12299. t.join();
  12300. ASSERT_FALSE(svr.is_running());
  12301. });
  12302. svr.wait_until_ready();
  12303. Client cli(HOST, PORT);
  12304. {
  12305. auto res = cli.Get("/image");
  12306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12307. EXPECT_EQ(StatusCode::OK_200, res->status);
  12308. EXPECT_EQ(body, res->body);
  12309. }
  12310. {
  12311. auto res = cli.Get("/identity");
  12312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12313. EXPECT_EQ(StatusCode::OK_200, res->status);
  12314. EXPECT_EQ(body, res->body);
  12315. }
  12316. {
  12317. // The same applies to a request body reaching the server.
  12318. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12319. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12321. EXPECT_EQ(StatusCode::OK_200, res->status);
  12322. EXPECT_EQ(body, res->body);
  12323. }
  12324. }
  12325. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12326. // gzip-encoded response even when the build has no zlib support.
  12327. static const char GZIPPED_HELLO_WORLD[] = {
  12328. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12329. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12330. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12331. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12332. // A content coding is a whole token, not something the field value merely
  12333. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12334. // as "fibre" look like Brotli, and turned a multi-coding value like
  12335. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12336. // it was never meant to see.
  12337. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12338. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12339. Server svr;
  12340. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12341. res.set_content(body, "image/jpeg");
  12342. res.set_header("Content-Encoding", "fibre");
  12343. });
  12344. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12345. res.set_content(body, "image/jpeg");
  12346. res.set_header("Content-Encoding", "gzip, br");
  12347. });
  12348. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12349. res.set_content(body, "image/jpeg");
  12350. res.set_header("Content-Encoding", "x-zstd-ish");
  12351. });
  12352. auto port = svr.bind_to_any_port(HOST);
  12353. thread t = thread([&]() { svr.listen_after_bind(); });
  12354. auto se = detail::scope_exit([&] {
  12355. svr.stop();
  12356. t.join();
  12357. ASSERT_FALSE(svr.is_running());
  12358. });
  12359. svr.wait_until_ready();
  12360. Client cli(HOST, port);
  12361. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12362. auto res = cli.Get(path);
  12363. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12364. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12365. // Not a coding we recognize, so the payload comes back untouched
  12366. EXPECT_EQ(body, res->body) << path;
  12367. }
  12368. }
  12369. // A content coding cpp-httplib recognizes but was not built with must be
  12370. // reported as such. Handing the still-compressed payload back to the caller
  12371. // would silently corrupt it.
  12372. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12373. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12374. Server svr;
  12375. // "image/jpeg" keeps the server from applying a content coding of its own,
  12376. // so the hand-crafted Content-Encoding below survives.
  12377. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12378. res.set_content(gzipped, "image/jpeg");
  12379. res.set_header("Content-Encoding", "gzip");
  12380. });
  12381. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12382. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12383. res.set_content(gzipped, "image/jpeg");
  12384. res.set_header("Content-Encoding", "GZIP");
  12385. });
  12386. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12387. auto se = detail::scope_exit([&] {
  12388. svr.stop();
  12389. t.join();
  12390. ASSERT_FALSE(svr.is_running());
  12391. });
  12392. svr.wait_until_ready();
  12393. Client cli(HOST, PORT);
  12394. {
  12395. auto res = cli.Get("/gzipped");
  12396. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12398. EXPECT_EQ("Hello World!", res->body);
  12399. #else
  12400. ASSERT_FALSE(res);
  12401. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12402. #endif
  12403. }
  12404. {
  12405. // open_stream() must behave the same way.
  12406. auto handle = cli.open_stream("GET", "/gzipped");
  12407. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12408. ASSERT_TRUE(handle.is_valid());
  12409. std::string received;
  12410. char buf[256];
  12411. ssize_t n;
  12412. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12413. received.append(buf, static_cast<size_t>(n));
  12414. }
  12415. EXPECT_EQ("Hello World!", received);
  12416. #else
  12417. EXPECT_FALSE(handle.is_valid());
  12418. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12419. #endif
  12420. }
  12421. {
  12422. // A differently-cased coding must not be mistaken for an unknown one, or
  12423. // the body would be handed back still compressed.
  12424. auto res = cli.Get("/gzipped-uppercase");
  12425. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12427. EXPECT_EQ("Hello World!", res->body);
  12428. #else
  12429. ASSERT_FALSE(res);
  12430. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12431. #endif
  12432. }
  12433. }
  12434. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12435. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12436. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12437. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12438. // body a second time and appending a second Content-Encoding field line, so
  12439. // clients that decode one coding per listed value handed back raw gzip bytes.
  12440. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12441. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12442. Server svr;
  12443. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12444. // keeps the server from applying a coding of its own.
  12445. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12446. res.set_content(gzipped, "text/plain");
  12447. res.set_header("Content-Encoding", "gzip");
  12448. });
  12449. auto port = svr.bind_to_any_port(HOST);
  12450. thread t = thread([&]() { svr.listen_after_bind(); });
  12451. auto se = detail::scope_exit([&] {
  12452. svr.stop();
  12453. t.join();
  12454. ASSERT_FALSE(svr.is_running());
  12455. });
  12456. svr.wait_until_ready();
  12457. Client cli(HOST, port);
  12458. Headers headers = {{"Accept-Encoding", "gzip"}};
  12459. auto res = cli.Get("/pre-gzipped", headers);
  12460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12461. EXPECT_EQ(StatusCode::OK_200, res->status);
  12462. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12463. EXPECT_EQ("Hello World!", res->body);
  12464. }
  12465. // A chunked provider settles its coding where the headers are written and
  12466. // reuses it at write time. Both ends of that have to hold: a handler's own
  12467. // Content-Encoding suppresses the coding, and a response without one is still
  12468. // compressed as it always was.
  12469. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12470. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12471. const std::string plain = "Hello World! Hello World! Hello World!";
  12472. Server svr;
  12473. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12474. res.set_header("Content-Encoding", "gzip");
  12475. res.set_chunked_content_provider(
  12476. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12477. sink.write(gzipped.data(), gzipped.size());
  12478. sink.done();
  12479. return true;
  12480. });
  12481. });
  12482. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12483. res.set_chunked_content_provider(
  12484. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12485. sink.write(plain.data(), plain.size());
  12486. sink.done();
  12487. return true;
  12488. });
  12489. });
  12490. auto port = svr.bind_to_any_port(HOST);
  12491. thread t = thread([&]() { svr.listen_after_bind(); });
  12492. auto se = detail::scope_exit([&] {
  12493. svr.stop();
  12494. t.join();
  12495. ASSERT_FALSE(svr.is_running());
  12496. });
  12497. svr.wait_until_ready();
  12498. Client cli(HOST, port);
  12499. Headers headers = {{"Accept-Encoding", "gzip"}};
  12500. {
  12501. auto res = cli.Get("/pre-gzipped", headers);
  12502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12503. EXPECT_EQ(StatusCode::OK_200, res->status);
  12504. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12505. EXPECT_EQ("Hello World!", res->body);
  12506. }
  12507. {
  12508. auto res = cli.Get("/negotiated", headers);
  12509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12510. EXPECT_EQ(StatusCode::OK_200, res->status);
  12511. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12512. EXPECT_EQ(plain, res->body);
  12513. }
  12514. }
  12515. #endif
  12516. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12517. // the same message as the comma-joined one, so both have to be read the same
  12518. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12519. // single gzip coding, and a body the sender says was encoded twice was handed
  12520. // back after one pass, still compressed but presented as decoded.
  12521. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12522. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12523. Server svr;
  12524. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12525. res.set_content(body, "image/jpeg");
  12526. res.headers.emplace("Content-Encoding", "gzip");
  12527. res.headers.emplace("Content-Encoding", "gzip");
  12528. });
  12529. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12530. res.set_content(body, "image/jpeg");
  12531. res.set_header("Content-Encoding", "gzip, gzip");
  12532. });
  12533. auto port = svr.bind_to_any_port(HOST);
  12534. thread t = thread([&]() { svr.listen_after_bind(); });
  12535. auto se = detail::scope_exit([&] {
  12536. svr.stop();
  12537. t.join();
  12538. ASSERT_FALSE(svr.is_running());
  12539. });
  12540. svr.wait_until_ready();
  12541. Client cli(HOST, port);
  12542. // Two codings is not something cpp-httplib decodes, so both representations
  12543. // take the pass-through path rather than one of them being gunzipped once.
  12544. for (const char *path : {"/split", "/joined"}) {
  12545. auto res = cli.Get(path);
  12546. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12547. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12548. EXPECT_EQ(body, res->body) << path;
  12549. }
  12550. }
  12551. // Regression test for DoS vulnerability: a malicious server sending a response
  12552. // without Content-Length header must not cause unbounded memory consumption on
  12553. // the client side. The client should stop reading after a reasonable limit,
  12554. // similar to the server-side set_payload_max_length protection.
  12555. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12556. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12557. #ifndef _WIN32
  12558. signal(SIGPIPE, SIG_IGN);
  12559. #endif
  12560. auto server_thread = std::thread([] {
  12561. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12562. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12563. default_socket_options(srv);
  12564. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12565. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12566. sockaddr_in addr{};
  12567. addr.sin_family = AF_INET;
  12568. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12569. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12570. int opt = 1;
  12571. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12572. #ifdef _WIN32
  12573. reinterpret_cast<const char *>(&opt),
  12574. #else
  12575. &opt,
  12576. #endif
  12577. sizeof(opt));
  12578. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12579. ::listen(srv, 1);
  12580. sockaddr_in cli_addr{};
  12581. socklen_t cli_len = sizeof(cli_addr);
  12582. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12583. if (cli != INVALID_SOCKET) {
  12584. char buf[4096];
  12585. ::recv(cli, buf, sizeof(buf), 0);
  12586. // Malicious response: no Content-Length, no chunked encoding
  12587. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12588. "Connection: close\r\n"
  12589. "\r\n";
  12590. ::send(cli,
  12591. #ifdef _WIN32
  12592. static_cast<const char *>(response_header.c_str()),
  12593. static_cast<int>(response_header.size()),
  12594. #else
  12595. response_header.c_str(), response_header.size(),
  12596. #endif
  12597. 0);
  12598. // Send 10MB of data
  12599. std::string chunk(64 * 1024, 'A');
  12600. size_t total_sent = 0;
  12601. while (total_sent < MALICIOUS_DATA_SIZE) {
  12602. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12603. auto sent = ::send(cli,
  12604. #ifdef _WIN32
  12605. static_cast<const char *>(chunk.c_str()),
  12606. static_cast<int>(to_send),
  12607. #else
  12608. chunk.c_str(), to_send,
  12609. #endif
  12610. 0);
  12611. if (sent <= 0) break;
  12612. total_sent += static_cast<size_t>(sent);
  12613. }
  12614. detail::close_socket(cli);
  12615. }
  12616. detail::close_socket(srv);
  12617. });
  12618. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12619. size_t total_read = 0;
  12620. {
  12621. Client cli("127.0.0.1", PORT + 2);
  12622. cli.set_read_timeout(5, 0);
  12623. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12624. auto stream = cli.open_stream("GET", "/malicious");
  12625. ASSERT_TRUE(stream.is_valid());
  12626. char buffer[64 * 1024];
  12627. ssize_t n;
  12628. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12629. total_read += static_cast<size_t>(n);
  12630. }
  12631. } // StreamHandle and Client destroyed here, closing the socket
  12632. server_thread.join();
  12633. // With set_payload_max_length, the client must stop reading before consuming
  12634. // all 10MB. The read loop should be cut off at or near the configured limit.
  12635. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12636. << "Client read " << total_read << " bytes, exceeding the configured "
  12637. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12638. }
  12639. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12640. // the entire response body without truncation.
  12641. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12642. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12643. #ifndef _WIN32
  12644. signal(SIGPIPE, SIG_IGN);
  12645. #endif
  12646. auto server_thread = std::thread([] {
  12647. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12648. default_socket_options(srv);
  12649. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12650. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12651. sockaddr_in addr{};
  12652. addr.sin_family = AF_INET;
  12653. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12654. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12655. int opt = 1;
  12656. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12657. #ifdef _WIN32
  12658. reinterpret_cast<const char *>(&opt),
  12659. #else
  12660. &opt,
  12661. #endif
  12662. sizeof(opt));
  12663. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12664. ::listen(srv, 1);
  12665. sockaddr_in cli_addr{};
  12666. socklen_t cli_len = sizeof(cli_addr);
  12667. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12668. if (cli != INVALID_SOCKET) {
  12669. char buf[4096];
  12670. ::recv(cli, buf, sizeof(buf), 0);
  12671. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12672. "Connection: close\r\n"
  12673. "\r\n";
  12674. ::send(cli,
  12675. #ifdef _WIN32
  12676. static_cast<const char *>(response_header.c_str()),
  12677. static_cast<int>(response_header.size()),
  12678. #else
  12679. response_header.c_str(), response_header.size(),
  12680. #endif
  12681. 0);
  12682. std::string chunk(64 * 1024, 'A');
  12683. size_t total_sent = 0;
  12684. while (total_sent < DATA_SIZE) {
  12685. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12686. auto sent = ::send(cli,
  12687. #ifdef _WIN32
  12688. static_cast<const char *>(chunk.c_str()),
  12689. static_cast<int>(to_send),
  12690. #else
  12691. chunk.c_str(), to_send,
  12692. #endif
  12693. 0);
  12694. if (sent <= 0) break;
  12695. total_sent += static_cast<size_t>(sent);
  12696. }
  12697. #ifdef _WIN32
  12698. ::shutdown(cli, SD_SEND);
  12699. #else
  12700. ::shutdown(cli, SHUT_WR);
  12701. #endif
  12702. // Drain until the client closes its end, ensuring all data is delivered
  12703. char drain[1024];
  12704. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12705. detail::close_socket(cli);
  12706. }
  12707. detail::close_socket(srv);
  12708. });
  12709. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12710. size_t total_read = 0;
  12711. {
  12712. Client cli("127.0.0.1", PORT + 2);
  12713. cli.set_read_timeout(5, 0);
  12714. cli.set_payload_max_length(0); // 0 means no limit
  12715. auto stream = cli.open_stream("GET", "/data");
  12716. ASSERT_TRUE(stream.is_valid());
  12717. char buffer[64 * 1024];
  12718. ssize_t n;
  12719. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12720. total_read += static_cast<size_t>(n);
  12721. }
  12722. }
  12723. server_thread.join();
  12724. EXPECT_EQ(total_read, DATA_SIZE)
  12725. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12726. << " bytes without truncation, but only read " << total_read << " bytes.";
  12727. }
  12728. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12729. // enormous Content-Length must not cause the client to pre-allocate a huge
  12730. // response body buffer. The reservation is capped at payload_max_length_, and
  12731. // the read itself fails when the body exceeds the limit.
  12732. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12733. #ifndef _WIN32
  12734. signal(SIGPIPE, SIG_IGN);
  12735. #endif
  12736. auto server_thread = std::thread([] {
  12737. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12738. default_socket_options(srv);
  12739. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12740. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12741. sockaddr_in addr{};
  12742. addr.sin_family = AF_INET;
  12743. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12744. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12745. int opt = 1;
  12746. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12747. #ifdef _WIN32
  12748. reinterpret_cast<const char *>(&opt),
  12749. #else
  12750. &opt,
  12751. #endif
  12752. sizeof(opt));
  12753. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12754. ::listen(srv, 1);
  12755. sockaddr_in cli_addr{};
  12756. socklen_t cli_len = sizeof(cli_addr);
  12757. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12758. if (cli != INVALID_SOCKET) {
  12759. char buf[4096];
  12760. ::recv(cli, buf, sizeof(buf), 0);
  12761. // Malicious response: claim a 20GB body but send only a tiny payload.
  12762. std::string response = "HTTP/1.1 200 OK\r\n"
  12763. "Content-Length: 20000000000\r\n"
  12764. "\r\n"
  12765. "abc";
  12766. ::send(cli,
  12767. #ifdef _WIN32
  12768. static_cast<const char *>(response.c_str()),
  12769. static_cast<int>(response.size()),
  12770. #else
  12771. response.c_str(), response.size(),
  12772. #endif
  12773. 0);
  12774. detail::close_socket(cli);
  12775. }
  12776. detail::close_socket(srv);
  12777. });
  12778. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12779. {
  12780. Client cli("127.0.0.1", PORT + 2);
  12781. cli.set_read_timeout(5, 0);
  12782. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12783. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12784. // (server claims more bytes than payload_max_length permits), but it must
  12785. // not exhaust memory before getting there.
  12786. auto res = cli.Get("/malicious");
  12787. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12788. }
  12789. server_thread.join();
  12790. }
  12791. // Verify that content_receiver bypasses the default payload_max_length,
  12792. // allowing streaming downloads larger than 100MB without requiring an explicit
  12793. // set_payload_max_length call.
  12794. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12795. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12796. #ifndef _WIN32
  12797. signal(SIGPIPE, SIG_IGN);
  12798. #endif
  12799. auto server_thread = std::thread([] {
  12800. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12801. default_socket_options(srv);
  12802. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12803. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12804. sockaddr_in addr{};
  12805. addr.sin_family = AF_INET;
  12806. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12807. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12808. int opt = 1;
  12809. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12810. #ifdef _WIN32
  12811. reinterpret_cast<const char *>(&opt),
  12812. #else
  12813. &opt,
  12814. #endif
  12815. sizeof(opt));
  12816. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12817. ::listen(srv, 1);
  12818. sockaddr_in cli_addr{};
  12819. socklen_t cli_len = sizeof(cli_addr);
  12820. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12821. if (cli != INVALID_SOCKET) {
  12822. char buf[4096];
  12823. ::recv(cli, buf, sizeof(buf), 0);
  12824. // Response with Content-Length larger than default 100MB limit
  12825. auto content_length = std::to_string(DATA_SIZE);
  12826. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12827. "Content-Length: " +
  12828. content_length +
  12829. "\r\n"
  12830. "Connection: close\r\n"
  12831. "\r\n";
  12832. ::send(cli,
  12833. #ifdef _WIN32
  12834. static_cast<const char *>(response_header.c_str()),
  12835. static_cast<int>(response_header.size()),
  12836. #else
  12837. response_header.c_str(), response_header.size(),
  12838. #endif
  12839. 0);
  12840. std::string chunk(64 * 1024, 'A');
  12841. size_t total_sent = 0;
  12842. while (total_sent < DATA_SIZE) {
  12843. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12844. auto sent = ::send(cli,
  12845. #ifdef _WIN32
  12846. static_cast<const char *>(chunk.c_str()),
  12847. static_cast<int>(to_send),
  12848. #else
  12849. chunk.c_str(), to_send,
  12850. #endif
  12851. 0);
  12852. if (sent <= 0) break;
  12853. total_sent += static_cast<size_t>(sent);
  12854. }
  12855. detail::close_socket(cli);
  12856. }
  12857. detail::close_socket(srv);
  12858. });
  12859. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12860. size_t total_received = 0;
  12861. {
  12862. Client cli("127.0.0.1", PORT + 2);
  12863. cli.set_read_timeout(10, 0);
  12864. // Do NOT call set_payload_max_length — use the default 100MB limit
  12865. auto res =
  12866. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12867. total_received += data_length;
  12868. return true;
  12869. });
  12870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12871. EXPECT_EQ(StatusCode::OK_200, res->status);
  12872. }
  12873. server_thread.join();
  12874. EXPECT_EQ(total_received, DATA_SIZE)
  12875. << "With content_receiver, the client should read all " << DATA_SIZE
  12876. << " bytes despite the default 100MB payload_max_length, but only read "
  12877. << total_received << " bytes.";
  12878. }
  12879. // Verify that an explicit set_payload_max_length smaller than the response is
  12880. // enforced even when a content_receiver is used.
  12881. TEST(ClientVulnerabilityTest,
  12882. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12883. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12884. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12885. #ifndef _WIN32
  12886. signal(SIGPIPE, SIG_IGN);
  12887. #endif
  12888. auto server_thread = std::thread([] {
  12889. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12890. default_socket_options(srv);
  12891. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12892. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12893. sockaddr_in addr{};
  12894. addr.sin_family = AF_INET;
  12895. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12896. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12897. int opt = 1;
  12898. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12899. #ifdef _WIN32
  12900. reinterpret_cast<const char *>(&opt),
  12901. #else
  12902. &opt,
  12903. #endif
  12904. sizeof(opt));
  12905. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12906. ::listen(srv, 1);
  12907. sockaddr_in cli_addr{};
  12908. socklen_t cli_len = sizeof(cli_addr);
  12909. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12910. if (cli != INVALID_SOCKET) {
  12911. char buf[4096];
  12912. ::recv(cli, buf, sizeof(buf), 0);
  12913. auto content_length = std::to_string(DATA_SIZE);
  12914. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12915. "Content-Length: " +
  12916. content_length +
  12917. "\r\n"
  12918. "Connection: close\r\n"
  12919. "\r\n";
  12920. ::send(cli,
  12921. #ifdef _WIN32
  12922. static_cast<const char *>(response_header.c_str()),
  12923. static_cast<int>(response_header.size()),
  12924. #else
  12925. response_header.c_str(), response_header.size(),
  12926. #endif
  12927. 0);
  12928. std::string chunk(64 * 1024, 'A');
  12929. size_t total_sent = 0;
  12930. while (total_sent < DATA_SIZE) {
  12931. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12932. auto sent = ::send(cli,
  12933. #ifdef _WIN32
  12934. static_cast<const char *>(chunk.c_str()),
  12935. static_cast<int>(to_send),
  12936. #else
  12937. chunk.c_str(), to_send,
  12938. #endif
  12939. 0);
  12940. if (sent <= 0) break;
  12941. total_sent += static_cast<size_t>(sent);
  12942. }
  12943. detail::close_socket(cli);
  12944. }
  12945. detail::close_socket(srv);
  12946. });
  12947. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12948. size_t total_received = 0;
  12949. {
  12950. Client cli("127.0.0.1", PORT + 2);
  12951. cli.set_read_timeout(10, 0);
  12952. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12953. auto res =
  12954. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12955. total_received += data_length;
  12956. return true;
  12957. });
  12958. // Should fail because 200MB exceeds the explicit 150MB limit
  12959. EXPECT_FALSE(res);
  12960. }
  12961. server_thread.join();
  12962. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12963. << "Client with content_receiver should respect the explicit "
  12964. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12965. << total_received << " bytes.";
  12966. }
  12967. // Verify that an explicit set_payload_max_length larger than the response
  12968. // allows the content_receiver to read all data successfully.
  12969. TEST(ClientVulnerabilityTest,
  12970. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12971. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12972. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12973. #ifndef _WIN32
  12974. signal(SIGPIPE, SIG_IGN);
  12975. #endif
  12976. auto server_thread = std::thread([] {
  12977. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12978. default_socket_options(srv);
  12979. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12980. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12981. sockaddr_in addr{};
  12982. addr.sin_family = AF_INET;
  12983. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12984. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12985. int opt = 1;
  12986. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12987. #ifdef _WIN32
  12988. reinterpret_cast<const char *>(&opt),
  12989. #else
  12990. &opt,
  12991. #endif
  12992. sizeof(opt));
  12993. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12994. ::listen(srv, 1);
  12995. sockaddr_in cli_addr{};
  12996. socklen_t cli_len = sizeof(cli_addr);
  12997. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12998. if (cli != INVALID_SOCKET) {
  12999. char buf[4096];
  13000. ::recv(cli, buf, sizeof(buf), 0);
  13001. auto content_length = std::to_string(DATA_SIZE);
  13002. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13003. "Content-Length: " +
  13004. content_length +
  13005. "\r\n"
  13006. "Connection: close\r\n"
  13007. "\r\n";
  13008. ::send(cli,
  13009. #ifdef _WIN32
  13010. static_cast<const char *>(response_header.c_str()),
  13011. static_cast<int>(response_header.size()),
  13012. #else
  13013. response_header.c_str(), response_header.size(),
  13014. #endif
  13015. 0);
  13016. std::string chunk(64 * 1024, 'A');
  13017. size_t total_sent = 0;
  13018. while (total_sent < DATA_SIZE) {
  13019. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13020. auto sent = ::send(cli,
  13021. #ifdef _WIN32
  13022. static_cast<const char *>(chunk.c_str()),
  13023. static_cast<int>(to_send),
  13024. #else
  13025. chunk.c_str(), to_send,
  13026. #endif
  13027. 0);
  13028. if (sent <= 0) break;
  13029. total_sent += static_cast<size_t>(sent);
  13030. }
  13031. #ifdef _WIN32
  13032. ::shutdown(cli, SD_SEND);
  13033. #else
  13034. ::shutdown(cli, SHUT_WR);
  13035. #endif
  13036. char drain[1024];
  13037. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13038. detail::close_socket(cli);
  13039. }
  13040. detail::close_socket(srv);
  13041. });
  13042. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13043. size_t total_received = 0;
  13044. {
  13045. Client cli("127.0.0.1", PORT + 2);
  13046. cli.set_read_timeout(10, 0);
  13047. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13048. auto res =
  13049. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13050. total_received += data_length;
  13051. return true;
  13052. });
  13053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13054. EXPECT_EQ(StatusCode::OK_200, res->status);
  13055. }
  13056. server_thread.join();
  13057. EXPECT_EQ(total_received, DATA_SIZE)
  13058. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13059. << " bytes (larger than " << DATA_SIZE
  13060. << " bytes response), content_receiver should read all data, but only "
  13061. "read "
  13062. << total_received << " bytes.";
  13063. }
  13064. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13065. // Regression test for "zip bomb" attack on the client side: a malicious server
  13066. // sends a small gzip-compressed response that decompresses to a huge payload.
  13067. // The client must enforce payload_max_length on the decompressed size.
  13068. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13069. constexpr size_t DECOMPRESSED_SIZE =
  13070. 10 * 1024 * 1024; // 10MB after decompression
  13071. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13072. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13073. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13074. std::string compressed;
  13075. {
  13076. httplib::detail::gzip_compressor compressor;
  13077. bool ok =
  13078. compressor.compress(uncompressed.data(), uncompressed.size(),
  13079. /*last=*/true, [&](const char *buf, size_t len) {
  13080. compressed.append(buf, len);
  13081. return true;
  13082. });
  13083. ASSERT_TRUE(ok);
  13084. }
  13085. // Sanity: compressed data should be much smaller than the decompressed size
  13086. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13087. #ifndef _WIN32
  13088. signal(SIGPIPE, SIG_IGN);
  13089. #endif
  13090. // Set up the listening socket in the main thread so the server is guaranteed
  13091. // to be ready before the client connects (eliminates race condition).
  13092. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13093. default_socket_options(srv);
  13094. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13095. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13096. sockaddr_in addr{};
  13097. addr.sin_family = AF_INET;
  13098. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13099. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13100. int opt = 1;
  13101. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13102. #ifdef _WIN32
  13103. reinterpret_cast<const char *>(&opt),
  13104. #else
  13105. &opt,
  13106. #endif
  13107. sizeof(opt));
  13108. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13109. ASSERT_EQ(0, ::listen(srv, 1));
  13110. auto server_thread = std::thread([&compressed, srv] {
  13111. sockaddr_in cli_addr{};
  13112. socklen_t cli_len = sizeof(cli_addr);
  13113. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13114. if (cli != INVALID_SOCKET) {
  13115. // Read the full HTTP request (until \r\n\r\n)
  13116. char buf[4096];
  13117. size_t total = 0;
  13118. while (total < sizeof(buf)) {
  13119. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13120. if (n <= 0) break;
  13121. total += static_cast<size_t>(n);
  13122. // Check for end of headers
  13123. if (total >= 4) {
  13124. std::string req(buf, total);
  13125. if (req.find("\r\n\r\n") != std::string::npos) break;
  13126. }
  13127. }
  13128. // Malicious response: gzip-compressed body, no Content-Length
  13129. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13130. "Content-Encoding: gzip\r\n"
  13131. "Connection: close\r\n"
  13132. "\r\n";
  13133. ::send(cli,
  13134. #ifdef _WIN32
  13135. static_cast<const char *>(response_header.c_str()),
  13136. static_cast<int>(response_header.size()),
  13137. #else
  13138. response_header.c_str(), response_header.size(),
  13139. #endif
  13140. 0);
  13141. // Send the compressed payload (small on the wire, huge when decompressed)
  13142. size_t total_sent = 0;
  13143. while (total_sent < compressed.size()) {
  13144. auto to_send = std::min(compressed.size() - total_sent,
  13145. static_cast<size_t>(64 * 1024));
  13146. auto sent =
  13147. ::send(cli,
  13148. #ifdef _WIN32
  13149. static_cast<const char *>(compressed.c_str() + total_sent),
  13150. static_cast<int>(to_send),
  13151. #else
  13152. compressed.c_str() + total_sent, to_send,
  13153. #endif
  13154. 0);
  13155. if (sent <= 0) break;
  13156. total_sent += static_cast<size_t>(sent);
  13157. }
  13158. detail::close_socket(cli);
  13159. }
  13160. });
  13161. auto se = detail::scope_exit([&] {
  13162. detail::close_socket(srv);
  13163. server_thread.join();
  13164. });
  13165. size_t total_decompressed = 0;
  13166. {
  13167. Client cli("127.0.0.1", PORT + 3);
  13168. cli.set_read_timeout(5, 0);
  13169. cli.set_decompress(true);
  13170. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13171. auto stream = cli.open_stream("GET", "/zipbomb");
  13172. ASSERT_TRUE(stream.is_valid());
  13173. char buffer[64 * 1024];
  13174. ssize_t n;
  13175. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13176. total_decompressed += static_cast<size_t>(n);
  13177. }
  13178. }
  13179. // The decompressed size must be capped by payload_max_length. Without
  13180. // protection, the client would decompress the full 10MB from a tiny
  13181. // compressed payload, enabling a zip bomb DoS attack.
  13182. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13183. << "Client decompressed " << total_decompressed
  13184. << " bytes from a gzip response. The decompressed size should be "
  13185. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13186. }
  13187. #endif
  13188. TEST(HostAndPortPropertiesTest, NoSSL) {
  13189. httplib::Client cli("www.google.com", 1234);
  13190. ASSERT_EQ("www.google.com", cli.host());
  13191. ASSERT_EQ(1234, cli.port());
  13192. }
  13193. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13194. httplib::Client cli("www.google.com:1234");
  13195. ASSERT_EQ("www.google.com", cli.host());
  13196. ASSERT_EQ(1234, cli.port());
  13197. }
  13198. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13199. // Port number that overflows int — should not crash, client becomes invalid
  13200. httplib::Client cli("http://www.google.com:99999999999999999999");
  13201. ASSERT_FALSE(cli.is_valid());
  13202. }
  13203. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13204. // Port 99999 exceeds valid range (1-65535) — should not crash
  13205. httplib::Client cli("http://www.google.com:99999");
  13206. ASSERT_FALSE(cli.is_valid());
  13207. auto res = cli.Get("/");
  13208. EXPECT_FALSE(res);
  13209. EXPECT_EQ(Error::Connection, res.error());
  13210. }
  13211. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13212. httplib::Client cli("http://user:pass@localhost:1234");
  13213. ASSERT_FALSE(cli.is_valid());
  13214. EXPECT_FALSE(cli.Get("/"));
  13215. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13216. }
  13217. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13218. httplib::Client cli("http://www.google.com:80abc");
  13219. ASSERT_FALSE(cli.is_valid());
  13220. }
  13221. #ifdef CPPHTTPLIB_SSL_ENABLED
  13222. TEST(HostAndPortPropertiesTest, SSL) {
  13223. httplib::SSLClient cli("www.google.com");
  13224. ASSERT_EQ("www.google.com", cli.host());
  13225. ASSERT_EQ(443, cli.port());
  13226. }
  13227. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13228. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13229. std::string cert;
  13230. read_file(CA_CERT_FILE, cert);
  13231. httplib::SSLClient httplib_client("www.google.com");
  13232. // Load CA store first time
  13233. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13234. // Load CA store second time (update)
  13235. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13236. // Verify client is still valid and can make connections
  13237. httplib_client.enable_server_certificate_verification(true);
  13238. auto res = httplib_client.Get("/");
  13239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13240. // Google may return 200 or 301 depending on various factors
  13241. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13242. res->status == StatusCode::MovedPermanently_301);
  13243. }
  13244. TEST(SSLClientTest, ServerNameIndication_Online) {
  13245. auto host = "httpbingo.org";
  13246. auto path = std::string{"/get"};
  13247. SSLClient cli(host, 443);
  13248. auto res = cli.Get(path);
  13249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13250. ASSERT_EQ(StatusCode::OK_200, res->status);
  13251. }
  13252. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13253. // Use a site that will cause SSL verification failure due to self-signed cert
  13254. SSLClient cli("self-signed.badssl.com", 443);
  13255. cli.enable_server_certificate_verification(true);
  13256. auto res = cli.Get("/");
  13257. ASSERT_TRUE(!res);
  13258. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13259. // Verify backend error is captured for SSLServerVerification
  13260. // This occurs when certificate verification fails
  13261. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13262. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13263. EXPECT_NE(0UL, res.ssl_backend_error());
  13264. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13265. // For OpenSSL, ssl_error is 0 for verification errors
  13266. EXPECT_EQ(0, res.ssl_error());
  13267. #if !defined(_WIN32) || \
  13268. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13269. // On non-Windows or when Windows Schannel is disabled, the error comes
  13270. // from OpenSSL's verification
  13271. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13272. res.ssl_backend_error());
  13273. #endif
  13274. #endif
  13275. }
  13276. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13277. // Use a site where hostname doesn't match the certificate
  13278. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13279. SSLClient cli("wrong.host.badssl.com", 443);
  13280. cli.enable_server_certificate_verification(true);
  13281. cli.enable_server_hostname_verification(true);
  13282. auto res = cli.Get("/");
  13283. ASSERT_TRUE(!res);
  13284. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13285. // Verify backend error is captured for hostname verification failure
  13286. EXPECT_NE(0UL, res.ssl_backend_error());
  13287. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13288. // For OpenSSL, ssl_error is 0 for verification errors
  13289. EXPECT_EQ(0, res.ssl_error());
  13290. #if !defined(_WIN32) || \
  13291. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13292. // On non-Windows or when Windows Schannel is disabled, the error comes
  13293. // from OpenSSL's hostname verification
  13294. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13295. res.ssl_backend_error());
  13296. #endif
  13297. #endif
  13298. }
  13299. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13300. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13301. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13302. SSLClient cli("www.google.com", 443);
  13303. cli.enable_server_certificate_verification(true);
  13304. auto res = cli.Get("/");
  13305. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13306. }
  13307. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13308. SSLClient cli("www.google.com", 443);
  13309. cli.enable_server_certificate_verification(true);
  13310. cli.enable_windows_certificate_verification(false);
  13311. auto res = cli.Get("/");
  13312. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13313. }
  13314. // The server sends an intermediate cross-signed by a root Windows trusts,
  13315. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13316. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13317. SSLClient cli("accounts.spotify.com", 443);
  13318. auto res = cli.Get("/");
  13319. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13320. << " ssl_backend_error=" << res.ssl_backend_error();
  13321. }
  13322. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13323. // policy status, which no backend reports for a self-signed certificate.
  13324. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13325. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13326. ASSERT_TRUE(svr.is_valid());
  13327. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13328. auto se = detail::scope_exit([&] {
  13329. svr.stop();
  13330. t.join();
  13331. ASSERT_FALSE(svr.is_running());
  13332. });
  13333. svr.wait_until_ready();
  13334. SSLClient cli("127.0.0.1", PORT);
  13335. cli.set_connection_timeout(30);
  13336. auto res = cli.Get("/");
  13337. ASSERT_FALSE(res);
  13338. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13339. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13340. }
  13341. #endif
  13342. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13343. Client cli("https://google.com");
  13344. auto res = cli.Get("/");
  13345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13346. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13347. }
  13348. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13349. SSLClient cli("google.com");
  13350. cli.set_ca_cert_path(CA_CERT_FILE);
  13351. auto res = cli.Get("/");
  13352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13353. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13354. }
  13355. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13356. SSLClient cli("google.com");
  13357. cli.enable_server_certificate_verification(true);
  13358. cli.set_ca_cert_path("hello");
  13359. auto res = cli.Get("/");
  13360. ASSERT_TRUE(!res);
  13361. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13362. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13363. // should be set
  13364. EXPECT_EQ(0, res.ssl_error());
  13365. // Verify backend error is captured for SSLLoadingCerts
  13366. // This error occurs when loading CA certificates fails
  13367. EXPECT_NE(0UL, res.ssl_backend_error());
  13368. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13369. // OpenSSL specific error codes:
  13370. // > openssl errstr 0x80000002
  13371. // error:80000002:system library::No such file or directory
  13372. // > openssl errstr 0xA000126
  13373. // error:0A000126:SSL routines::unexpected eof while reading
  13374. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13375. res.ssl_backend_error() == 0xA000126);
  13376. #endif
  13377. }
  13378. TEST(SSLClientTest, ServerCertificateVerification4) {
  13379. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13380. ASSERT_TRUE(svr.is_valid());
  13381. svr.Get("/test", [&](const Request &, Response &res) {
  13382. res.set_content("test", "text/plain");
  13383. svr.stop();
  13384. ASSERT_TRUE(true);
  13385. });
  13386. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13387. auto se = detail::scope_exit([&] {
  13388. t.join();
  13389. ASSERT_FALSE(svr.is_running());
  13390. });
  13391. svr.wait_until_ready();
  13392. SSLClient cli("127.0.0.1", PORT);
  13393. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13394. cli.enable_server_certificate_verification(true);
  13395. cli.set_connection_timeout(30);
  13396. auto res = cli.Get("/test");
  13397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13398. ASSERT_EQ(StatusCode::OK_200, res->status);
  13399. }
  13400. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13401. std::string cert;
  13402. read_file(CA_CERT_FILE, cert);
  13403. SSLClient cli("google.com");
  13404. cli.load_ca_cert_store(cert.data(), cert.size());
  13405. const auto res = cli.Get("/");
  13406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13407. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13408. }
  13409. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13410. // clang-format off
  13411. static constexpr char cert[] =
  13412. "GlobalSign Root CA\n"
  13413. "==================\n"
  13414. "-----BEGIN CERTIFICATE-----\n"
  13415. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13416. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13417. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13418. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13419. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13420. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13421. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13422. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13423. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13424. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13425. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13426. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13427. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13428. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13429. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13430. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13431. "-----END CERTIFICATE-----\n";
  13432. // clang-format on
  13433. SSLClient cli("google.com");
  13434. cli.load_ca_cert_store(cert, sizeof(cert));
  13435. const auto res = cli.Get("/");
  13436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13437. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13438. }
  13439. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13440. SSLClient cli("www.youtube.com");
  13441. cli.set_ca_cert_path(CA_CERT_FILE);
  13442. cli.enable_server_certificate_verification(true);
  13443. cli.set_follow_location(true);
  13444. auto res = cli.Get("/");
  13445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13446. ASSERT_EQ(StatusCode::OK_200, res->status);
  13447. }
  13448. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13449. SSLClient cli("wWw.YouTube.Com");
  13450. cli.set_ca_cert_path(CA_CERT_FILE);
  13451. cli.enable_server_certificate_verification(true);
  13452. cli.enable_server_hostname_verification(true);
  13453. cli.set_follow_location(true);
  13454. auto res = cli.Get("/");
  13455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13456. ASSERT_EQ(StatusCode::OK_200, res->status);
  13457. }
  13458. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13459. SSLClient cli("gOoGlE.COm");
  13460. cli.enable_server_certificate_verification(true);
  13461. cli.enable_server_hostname_verification(true);
  13462. cli.set_follow_location(true);
  13463. auto res = cli.Get("/");
  13464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13465. ASSERT_EQ(StatusCode::OK_200, res->status);
  13466. }
  13467. TEST(SSLClientTest, Issue2004_Online) {
  13468. Client client("https://google.com");
  13469. client.set_follow_location(true);
  13470. auto res = client.Get("/");
  13471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13472. ASSERT_EQ(StatusCode::OK_200, res->status);
  13473. auto body = res->body;
  13474. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13475. }
  13476. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13477. // Create SSLClient with invalid cert/key to make is_valid() return false
  13478. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13479. "nonexistent_key.pem");
  13480. // is_valid() should be false due to cert loading failure
  13481. ASSERT_FALSE(cli.is_valid());
  13482. auto res = cli.Get("/");
  13483. ASSERT_FALSE(res);
  13484. EXPECT_EQ(Error::SSLConnection, res.error());
  13485. }
  13486. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13487. // Test for Issue #2251: SSL error not properly reported when client cert
  13488. // and key paths are swapped or mismatched
  13489. // This simulates the scenario where user accidentally swaps the cert and key
  13490. // files
  13491. // Using client cert file as private key and vice versa (completely wrong)
  13492. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13493. // Should fail validation due to cert/key mismatch
  13494. ASSERT_FALSE(cli.is_valid());
  13495. // Attempt to make a request should fail with proper error
  13496. auto res = cli.Get("/");
  13497. ASSERT_FALSE(res);
  13498. EXPECT_EQ(Error::SSLConnection, res.error());
  13499. // SSL error should be recorded in the Result object (this is the key fix for
  13500. // Issue #2251)
  13501. auto backend_error = res.ssl_backend_error();
  13502. EXPECT_NE(0u, backend_error);
  13503. }
  13504. // Tests cert/key mismatch detection at the TLS context level
  13505. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13506. // Test that using mismatched cert/key causes connection failure.
  13507. // We verify this at the SSLClient level rather than through internal
  13508. // TLS API functions.
  13509. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13510. cli.enable_server_certificate_verification(false);
  13511. cli.set_connection_timeout(2);
  13512. // The mismatch should cause a connection or handshake error
  13513. auto res = cli.Get("/test");
  13514. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13515. // Either way, the request should fail
  13516. EXPECT_FALSE(res);
  13517. }
  13518. #endif
  13519. #if 0
  13520. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13521. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13522. ASSERT_TRUE(cli != nullptr);
  13523. cli->set_address_family(AF_INET6);
  13524. cli->set_interface("en0");
  13525. auto res = cli->Get("/get");
  13526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13527. ASSERT_EQ(StatusCode::OK_200, res->status);
  13528. }
  13529. #endif
  13530. // Client certificate tests - work with all TLS backends
  13531. #ifdef CPPHTTPLIB_SSL_ENABLED
  13532. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13533. void ClientCertPresent(
  13534. const std::string &client_cert_file,
  13535. const std::string &client_private_key_file,
  13536. const std::string &client_encrypted_private_key_pass = std::string(),
  13537. const ClientCertServerSetup &setup = nullptr) {
  13538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13539. ASSERT_TRUE(svr.is_valid());
  13540. if (setup) { setup(svr); }
  13541. svr.Get("/test", [&](const Request &req, Response &res) {
  13542. res.set_content("test", "text/plain");
  13543. auto cert = req.peer_cert();
  13544. ASSERT_TRUE(static_cast<bool>(cert));
  13545. std::string common_name = cert.subject_cn();
  13546. EXPECT_EQ("Common Name", common_name);
  13547. });
  13548. auto port = svr.bind_to_any_port(HOST);
  13549. ASSERT_LT(0, port);
  13550. thread t = thread([&]() { svr.listen_after_bind(); });
  13551. auto se = detail::scope_exit([&] {
  13552. svr.stop();
  13553. t.join();
  13554. ASSERT_FALSE(svr.is_running());
  13555. });
  13556. svr.wait_until_ready();
  13557. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13558. client_encrypted_private_key_pass);
  13559. cli.enable_server_certificate_verification(false);
  13560. cli.set_connection_timeout(30);
  13561. auto res = cli.Get("/test");
  13562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13563. ASSERT_EQ(StatusCode::OK_200, res->status);
  13564. }
  13565. TEST(SSLClientServerTest, ClientCertPresent) {
  13566. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13567. }
  13568. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13569. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13570. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13571. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13572. }
  13573. // Expects svr, which must require client certificates, to reject a client
  13574. // that has none
  13575. void RejectsClientWithoutCert(SSLServer &svr) {
  13576. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13577. auto port = svr.bind_to_any_port(HOST);
  13578. ASSERT_LT(0, port);
  13579. thread t = thread([&]() { svr.listen_after_bind(); });
  13580. auto se = detail::scope_exit([&] {
  13581. svr.stop();
  13582. t.join();
  13583. ASSERT_FALSE(svr.is_running());
  13584. });
  13585. svr.wait_until_ready();
  13586. SSLClient cli(HOST, port);
  13587. cli.set_connection_timeout(30);
  13588. // Skip the server certificate check, so that the request fails because the
  13589. // client certificate is missing rather than because cert.pem is not trusted
  13590. cli.enable_server_certificate_verification(false);
  13591. auto res = cli.Get("/test");
  13592. ASSERT_FALSE(res);
  13593. // The server rejects the client during the handshake, or on TLS 1.3 right
  13594. // after it, which the client notices on its first write or read
  13595. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13596. res.error() == Error::Write || res.error() == Error::Read)
  13597. << to_string(res.error());
  13598. if (res.error() == Error::SSLConnection) {
  13599. EXPECT_NE(0UL, res.ssl_backend_error());
  13600. }
  13601. // A rejection noticed on the write keeps the TLS error the write hit
  13602. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13603. }
  13604. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13605. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13606. ASSERT_TRUE(svr.is_valid());
  13607. if (setup) { setup(svr); }
  13608. RejectsClientWithoutCert(svr);
  13609. }
  13610. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13611. // A server that requires client certificates must keep requiring them after
  13612. // setup changes it, and keep accepting a client that has one
  13613. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13614. ClientCertMissing(setup);
  13615. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13616. setup);
  13617. }
  13618. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13619. ClientCertStillRequired([](SSLServer &svr) {
  13620. ASSERT_TRUE(tls::set_verify_callback(
  13621. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13622. });
  13623. }
  13624. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13625. ClientCertStillRequired([](SSLServer &svr) {
  13626. ASSERT_TRUE(tls::set_verify_callback(
  13627. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13628. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13629. });
  13630. }
  13631. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13632. ClientCertStillRequired([](SSLServer &svr) {
  13633. std::string cert_pem, key_pem, ca_pem;
  13634. read_file(SERVER_CERT_FILE, cert_pem);
  13635. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13636. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13637. ASSERT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  13638. ca_pem.c_str()));
  13639. });
  13640. }
  13641. // A TLS error from one request must not show up in a later request's Result
  13642. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13644. ASSERT_TRUE(svr.is_valid());
  13645. svr.Get("/test", [](const Request &, Response &res) {
  13646. res.set_content("test", "text/plain");
  13647. });
  13648. auto port = svr.bind_to_any_port(HOST);
  13649. ASSERT_LT(0, port);
  13650. thread t = thread([&]() { svr.listen_after_bind(); });
  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. SSLClient cli(HOST, port);
  13658. cli.set_connection_timeout(30);
  13659. cli.enable_server_hostname_verification(false);
  13660. // cert.pem is not trusted, so the handshake fails
  13661. ASSERT_FALSE(cli.Get("/test"));
  13662. cli.enable_server_certificate_verification(false);
  13663. auto res = cli.Get("/test");
  13664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13665. EXPECT_EQ(0, res.ssl_error());
  13666. EXPECT_EQ(0UL, res.ssl_backend_error());
  13667. }
  13668. // PEM memory-based constructor tests (works with all TLS backends).
  13669. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13670. // terminator after it.
  13671. void PemMemoryClientCertPresent(
  13672. const std::string &client_cert_file,
  13673. const std::string &client_private_key_file,
  13674. const std::string &client_encrypted_private_key_pass = std::string(),
  13675. bool exact_size = false) {
  13676. // Read PEM files into memory
  13677. std::string server_cert_pem, server_key_pem;
  13678. std::string client_ca_pem;
  13679. std::string client_cert_pem, client_key_pem;
  13680. read_file(SERVER_CERT_FILE, server_cert_pem);
  13681. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13682. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13683. read_file(client_cert_file, client_cert_pem);
  13684. read_file(client_private_key_file, client_key_pem);
  13685. std::list<std::vector<char>> exact_copies;
  13686. auto data = [&](const std::string &pem) -> const char * {
  13687. if (!exact_size) { return pem.c_str(); }
  13688. exact_copies.emplace_back(pem.begin(), pem.end());
  13689. return exact_copies.back().data();
  13690. };
  13691. // Create server with PEM memory
  13692. SSLServer::PemMemory server_pem = {
  13693. data(server_cert_pem),
  13694. server_cert_pem.size(),
  13695. data(server_key_pem),
  13696. server_key_pem.size(),
  13697. data(client_ca_pem),
  13698. client_ca_pem.size(),
  13699. nullptr // no password for server key
  13700. };
  13701. SSLServer svr(server_pem);
  13702. ASSERT_TRUE(svr.is_valid());
  13703. svr.Get("/test", [&](const Request &req, Response &res) {
  13704. res.set_content("test", "text/plain");
  13705. auto cert = req.peer_cert();
  13706. ASSERT_TRUE(static_cast<bool>(cert));
  13707. EXPECT_EQ("Common Name", cert.subject_cn());
  13708. });
  13709. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13710. auto se = detail::scope_exit([&] {
  13711. svr.stop();
  13712. t.join();
  13713. ASSERT_FALSE(svr.is_running());
  13714. });
  13715. svr.wait_until_ready();
  13716. // Create client with PEM memory
  13717. const char *password = client_encrypted_private_key_pass.empty()
  13718. ? nullptr
  13719. : client_encrypted_private_key_pass.c_str();
  13720. SSLClient::PemMemory client_pem = {
  13721. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13722. client_key_pem.size(), password};
  13723. SSLClient cli(HOST, PORT, client_pem);
  13724. cli.enable_server_certificate_verification(false);
  13725. cli.set_connection_timeout(30);
  13726. auto res = cli.Get("/test");
  13727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13728. ASSERT_EQ(StatusCode::OK_200, res->status);
  13729. }
  13730. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13731. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13732. }
  13733. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13734. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13735. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13736. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13737. }
  13738. // A server built from PEM memory with a client CA requires client certificates
  13739. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13740. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13741. read_file(SERVER_CERT_FILE, server_cert_pem);
  13742. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13743. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13744. SSLServer::PemMemory server_pem = {
  13745. server_cert_pem.c_str(),
  13746. server_cert_pem.size(),
  13747. server_key_pem.c_str(),
  13748. server_key_pem.size(),
  13749. client_ca_pem.c_str(),
  13750. client_ca_pem.size(),
  13751. nullptr // no password for server key
  13752. };
  13753. SSLServer svr(server_pem);
  13754. ASSERT_TRUE(svr.is_valid());
  13755. RejectsClientWithoutCert(svr);
  13756. }
  13757. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13758. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13759. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13760. true);
  13761. }
  13762. // A length shorter than the PEM cuts it short, so it no longer loads
  13763. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13764. std::string cert, key;
  13765. read_file(SERVER_CERT_FILE, cert);
  13766. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13767. for (auto cut_cert : {true, false}) {
  13768. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13769. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13770. SSLServer::PemMemory server_pem = {
  13771. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13772. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13773. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13774. key_len, nullptr};
  13775. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13776. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13777. key.c_str(), key_len, nullptr};
  13778. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13779. }
  13780. }
  13781. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13782. class NoListenSSLServer : public SSLServer {
  13783. public:
  13784. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13785. const char *client_ca_cert_file_path,
  13786. const char *client_ca_cert_dir_path = nullptr)
  13787. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13788. client_ca_cert_dir_path),
  13789. stop_(false) {}
  13790. std::atomic_bool stop_;
  13791. private:
  13792. bool process_and_close_socket(socket_t /*sock*/) override {
  13793. // Don't create SSL context
  13794. while (!stop_.load()) {
  13795. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13796. }
  13797. return true;
  13798. }
  13799. };
  13800. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13801. CLIENT_CA_CERT_FILE);
  13802. ASSERT_TRUE(svr.is_valid());
  13803. svr.Get("/test", [&](const Request &, Response &res) {
  13804. res.set_content("test", "text/plain");
  13805. });
  13806. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13807. auto se = detail::scope_exit([&] {
  13808. svr.stop_ = true;
  13809. svr.stop();
  13810. t.join();
  13811. ASSERT_FALSE(svr.is_running());
  13812. });
  13813. svr.wait_until_ready();
  13814. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13815. cli.enable_server_certificate_verification(false);
  13816. cli.set_connection_timeout(1);
  13817. auto res = cli.Get("/test");
  13818. ASSERT_TRUE(!res);
  13819. EXPECT_EQ(Error::SSLConnection, res.error());
  13820. // Timeout results in WantRead error code (maps to backend-specific value)
  13821. EXPECT_NE(0, res.ssl_error());
  13822. }
  13823. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13824. // Test SSLServer with client certificate verification using the standard
  13825. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13826. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13827. CLIENT_CA_CERT_DIR);
  13828. ASSERT_TRUE(svr.is_valid());
  13829. svr.Get("/test", [&](const Request &req, Response &res) {
  13830. res.set_content("test", "text/plain");
  13831. auto cert = req.peer_cert();
  13832. ASSERT_TRUE(static_cast<bool>(cert));
  13833. auto common_name = cert.subject_cn();
  13834. EXPECT_EQ("Common Name", common_name);
  13835. });
  13836. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13837. auto se = detail::scope_exit([&] {
  13838. svr.stop();
  13839. t.join();
  13840. ASSERT_FALSE(svr.is_running());
  13841. });
  13842. svr.wait_until_ready();
  13843. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13844. cli.enable_server_certificate_verification(false);
  13845. cli.set_connection_timeout(30);
  13846. auto res = cli.Get("/test");
  13847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13848. ASSERT_EQ(StatusCode::OK_200, res->status);
  13849. }
  13850. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13851. // Verifies that wildcard matching and exact matching work consistently
  13852. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13853. using namespace httplib::tls;
  13854. // We need a running server to test against
  13855. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13856. ASSERT_TRUE(svr.is_valid());
  13857. svr.Get("/test", [](const Request &, Response &res) {
  13858. res.set_content("ok", "text/plain");
  13859. });
  13860. thread t([&]() { svr.listen(HOST, PORT); });
  13861. auto se = detail::scope_exit([&] {
  13862. svr.stop();
  13863. t.join();
  13864. });
  13865. svr.wait_until_ready();
  13866. bool verify_callback_called = false;
  13867. bool verify_result_wrong = false;
  13868. SSLClient cli(HOST, PORT);
  13869. cli.enable_server_certificate_verification(true);
  13870. cli.set_ca_cert_path(CA_CERT_FILE);
  13871. cli.set_connection_timeout(5);
  13872. // Note: Test certificate has CN="Common Name", not "localhost"
  13873. bool verify_result_cn = false;
  13874. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13875. verify_callback_called = true;
  13876. if (!ctx.cert) return false;
  13877. // Test 1: "Common Name" should match (our test server cert CN)
  13878. verify_result_cn = ctx.check_hostname("Common Name");
  13879. // Test 2: wrong hostname should not match
  13880. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13881. return true; // Accept for the purpose of this test
  13882. });
  13883. auto res = cli.Get("/test");
  13884. // The request may succeed or fail depending on cert configuration
  13885. // but the callback should have been called
  13886. ASSERT_TRUE(verify_callback_called)
  13887. << "Verify callback should have been called";
  13888. // CN="Common Name" should match our test certificate
  13889. //
  13890. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13891. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13892. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13893. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13894. // <openssl/base.h>, which is included transitively when
  13895. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13896. #if defined(OPENSSL_IS_BORINGSSL)
  13897. EXPECT_FALSE(verify_result_cn)
  13898. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13899. #else
  13900. EXPECT_TRUE(verify_result_cn)
  13901. << "verify_hostname should match 'Common Name' (certificate CN)";
  13902. #endif
  13903. // Wrong hostname should not match
  13904. EXPECT_FALSE(verify_result_wrong)
  13905. << "verify_hostname should not match 'wronghost.example.com'";
  13906. }
  13907. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13908. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13909. // X509_check_ip behavior and must hold for every backend.
  13910. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13911. using namespace httplib::tls;
  13912. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13913. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13914. ASSERT_TRUE(svr.is_valid());
  13915. svr.Get("/test", [](const Request &, Response &res) {
  13916. res.set_content("ok", "text/plain");
  13917. });
  13918. thread t([&]() { svr.listen(HOST, PORT); });
  13919. auto se = detail::scope_exit([&] {
  13920. svr.stop();
  13921. t.join();
  13922. });
  13923. svr.wait_until_ready();
  13924. bool verify_callback_called = false;
  13925. bool ip_matched_via_cn = true;
  13926. SSLClient cli(HOST, PORT);
  13927. cli.enable_server_certificate_verification(true);
  13928. cli.set_ca_cert_path(CA_CERT_FILE);
  13929. cli.set_connection_timeout(5);
  13930. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13931. verify_callback_called = true;
  13932. if (!ctx.cert) return false;
  13933. // The IP appears only in the CN, so it must NOT be accepted.
  13934. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13935. return true; // Accept for the purpose of this test
  13936. });
  13937. cli.Get("/test");
  13938. ASSERT_TRUE(verify_callback_called)
  13939. << "Verify callback should have been called";
  13940. EXPECT_FALSE(ip_matched_via_cn)
  13941. << "An IP host must not be authenticated via the certificate CN";
  13942. }
  13943. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13944. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13945. using namespace httplib::tls;
  13946. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13947. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13948. ASSERT_TRUE(svr.is_valid());
  13949. svr.Get("/test", [](const Request &, Response &res) {
  13950. res.set_content("ok", "text/plain");
  13951. });
  13952. thread t([&]() { svr.listen(HOST, PORT); });
  13953. auto se = detail::scope_exit([&] {
  13954. svr.stop();
  13955. t.join();
  13956. });
  13957. svr.wait_until_ready();
  13958. bool verify_callback_called = false;
  13959. bool san_matched = false;
  13960. bool wrong_ipv6_matched = true;
  13961. bool cn_ipv6_matched = true;
  13962. SSLClient cli(HOST, PORT);
  13963. cli.enable_server_certificate_verification(true);
  13964. cli.set_ca_cert_path(CA_CERT_FILE);
  13965. cli.set_connection_timeout(5);
  13966. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13967. verify_callback_called = true;
  13968. if (!ctx.cert) return false;
  13969. // Matches the IPv6 iPAddress SAN.
  13970. san_matched = ctx.check_hostname("2001:db8::1");
  13971. // A different IPv6 address must not match.
  13972. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13973. // "::1" lives only in the CN, so it must not be accepted.
  13974. cn_ipv6_matched = ctx.check_hostname("::1");
  13975. return true; // Accept for the purpose of this test
  13976. });
  13977. cli.Get("/test");
  13978. ASSERT_TRUE(verify_callback_called)
  13979. << "Verify callback should have been called";
  13980. EXPECT_TRUE(san_matched)
  13981. << "verify_hostname should match an IPv6 iPAddress SAN";
  13982. EXPECT_FALSE(wrong_ipv6_matched)
  13983. << "verify_hostname should not match a non-matching IPv6 address";
  13984. EXPECT_FALSE(cn_ipv6_matched)
  13985. << "An IPv6 host must not be authenticated via the certificate CN";
  13986. }
  13987. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13988. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13989. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13990. using namespace httplib::tls;
  13991. // SANs: DNS:a.zz, IP:42.46.122.122
  13992. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13993. ASSERT_TRUE(svr.is_valid());
  13994. svr.Get("/test", [](const Request &, Response &res) {
  13995. res.set_content("ok", "text/plain");
  13996. });
  13997. auto port = svr.bind_to_any_port(HOST);
  13998. thread t([&]() { svr.listen_after_bind(); });
  13999. auto se = detail::scope_exit([&] {
  14000. svr.stop();
  14001. t.join();
  14002. });
  14003. svr.wait_until_ready();
  14004. bool verify_callback_called = false;
  14005. bool dns_san_matched = false;
  14006. bool ip_san_matched = false;
  14007. bool ip_matched_via_dns_san = true;
  14008. bool dns_matched_via_ip_san = true;
  14009. bool cn_matched_next_to_dns_san = true;
  14010. SSLClient cli(HOST, port);
  14011. cli.enable_server_certificate_verification(true);
  14012. cli.set_ca_cert_path(CA_CERT_FILE);
  14013. cli.set_connection_timeout(5);
  14014. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14015. verify_callback_called = true;
  14016. if (!ctx.cert) return false;
  14017. dns_san_matched = ctx.check_hostname("a.zz");
  14018. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14019. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14020. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14021. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14022. return true; // Accept for the purpose of this test
  14023. });
  14024. cli.Get("/test");
  14025. ASSERT_TRUE(verify_callback_called)
  14026. << "Verify callback should have been called";
  14027. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14028. EXPECT_TRUE(ip_san_matched)
  14029. << "verify_hostname should match an iPAddress SAN";
  14030. EXPECT_FALSE(ip_matched_via_dns_san)
  14031. << "An IP host must not be authenticated via a dNSName SAN";
  14032. EXPECT_FALSE(dns_matched_via_ip_san)
  14033. << "A DNS host must not be authenticated via an iPAddress SAN";
  14034. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14035. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14036. }
  14037. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14038. // "www.*.example.test" names one host and not every host under example.test.
  14039. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14040. using namespace httplib::tls;
  14041. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14042. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14043. ASSERT_TRUE(svr.is_valid());
  14044. svr.Get("/test", [](const Request &, Response &res) {
  14045. res.set_content("ok", "text/plain");
  14046. });
  14047. auto port = svr.bind_to_any_port(HOST);
  14048. thread t([&]() { svr.listen_after_bind(); });
  14049. auto se = detail::scope_exit([&] {
  14050. svr.stop();
  14051. t.join();
  14052. });
  14053. svr.wait_until_ready();
  14054. bool verify_callback_called = false;
  14055. bool leftmost_wildcard_matched = false;
  14056. bool wildcard_spanned_labels = true;
  14057. bool inner_wildcard_matched = true;
  14058. SSLClient cli(HOST, port);
  14059. cli.enable_server_certificate_verification(true);
  14060. cli.set_ca_cert_path(CA_CERT_FILE);
  14061. cli.set_connection_timeout(5);
  14062. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14063. verify_callback_called = true;
  14064. if (!ctx.cert) return false;
  14065. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14066. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14067. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14068. return true; // Accept for the purpose of this test
  14069. });
  14070. cli.Get("/test");
  14071. ASSERT_TRUE(verify_callback_called)
  14072. << "Verify callback should have been called";
  14073. EXPECT_TRUE(leftmost_wildcard_matched)
  14074. << "A leftmost wildcard should match a single label";
  14075. EXPECT_FALSE(wildcard_spanned_labels)
  14076. << "A wildcard label must not match more than one label";
  14077. EXPECT_FALSE(inner_wildcard_matched)
  14078. << "A wildcard outside the leftmost label must not be honoured";
  14079. }
  14080. // sans() must report each SAN entry under its own type.
  14081. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14082. using namespace httplib::tls;
  14083. // SANs: DNS:a.zz, IP:42.46.122.122
  14084. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14085. ASSERT_TRUE(svr.is_valid());
  14086. svr.Get("/test", [](const Request &, Response &res) {
  14087. res.set_content("ok", "text/plain");
  14088. });
  14089. auto port = svr.bind_to_any_port(HOST);
  14090. thread t([&]() { svr.listen_after_bind(); });
  14091. auto se = detail::scope_exit([&] {
  14092. svr.stop();
  14093. t.join();
  14094. });
  14095. svr.wait_until_ready();
  14096. bool verify_callback_called = false;
  14097. std::vector<SanEntry> sans;
  14098. SSLClient cli(HOST, port);
  14099. cli.enable_server_certificate_verification(true);
  14100. cli.set_ca_cert_path(CA_CERT_FILE);
  14101. cli.set_connection_timeout(5);
  14102. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14103. verify_callback_called = true;
  14104. if (!ctx.cert) return false;
  14105. sans = ctx.sans();
  14106. return true; // Accept for the purpose of this test
  14107. });
  14108. cli.Get("/test");
  14109. ASSERT_TRUE(verify_callback_called)
  14110. << "Verify callback should have been called";
  14111. auto has_san = [&](SanType type, const std::string &value) {
  14112. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14113. return san.type == type && san.value == value;
  14114. });
  14115. };
  14116. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14117. << "sans() should report the dNSName SAN";
  14118. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14119. << "sans() should report the iPAddress SAN";
  14120. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14121. << "sans() must not report the dNSName SAN as an address";
  14122. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14123. << "sans() must not report the iPAddress SAN as a DNS name";
  14124. }
  14125. #endif
  14126. // mbedTLS-specific callback constructor test
  14127. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14128. #ifdef CPPHTTPLIB_SSL_ENABLED
  14129. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14130. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14131. ASSERT_TRUE(svr.is_valid());
  14132. // Set up a handler to verify client certificate is present
  14133. bool client_cert_verified = false;
  14134. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14135. // Verify that client certificate was provided
  14136. client_cert_verified = true;
  14137. res.set_content("success", "text/plain");
  14138. });
  14139. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14140. auto se = detail::scope_exit([&] {
  14141. svr.stop();
  14142. t.join();
  14143. ASSERT_FALSE(svr.is_running());
  14144. });
  14145. svr.wait_until_ready();
  14146. // Client with certificate
  14147. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14148. cli.enable_server_certificate_verification(false);
  14149. cli.set_connection_timeout(30);
  14150. auto res = cli.Get("/test");
  14151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14152. ASSERT_EQ(StatusCode::OK_200, res->status);
  14153. ASSERT_TRUE(client_cert_verified);
  14154. EXPECT_EQ("success", res->body);
  14155. }
  14156. #endif
  14157. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14158. // backends
  14159. #ifdef CPPHTTPLIB_SSL_ENABLED
  14160. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14161. using namespace httplib::tls;
  14162. // Test that when client CA cert file is provided,
  14163. // the server properly requests and validates client certificates
  14164. // Create a server with client authentication
  14165. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14166. ASSERT_TRUE(svr.is_valid());
  14167. bool handler_called = false;
  14168. svr.Get("/test", [&](const Request &req, Response &res) {
  14169. handler_called = true;
  14170. // Verify that a client certificate was provided
  14171. auto cert = req.peer_cert();
  14172. ASSERT_TRUE(static_cast<bool>(cert));
  14173. // Get the issuer name
  14174. std::string issuer_str = cert.issuer_name();
  14175. ASSERT_FALSE(issuer_str.empty());
  14176. // The client certificate should be issued by our test CA
  14177. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14178. res.set_content("authenticated", "text/plain");
  14179. });
  14180. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14181. auto se = detail::scope_exit([&] {
  14182. svr.stop();
  14183. t.join();
  14184. ASSERT_FALSE(svr.is_running());
  14185. });
  14186. svr.wait_until_ready();
  14187. // Connect with a client certificate issued by the CA
  14188. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14189. cli.enable_server_certificate_verification(false);
  14190. cli.set_connection_timeout(30);
  14191. auto res = cli.Get("/test");
  14192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14193. ASSERT_EQ(StatusCode::OK_200, res->status);
  14194. ASSERT_TRUE(handler_called);
  14195. EXPECT_EQ("authenticated", res->body);
  14196. }
  14197. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14198. using namespace httplib::tls;
  14199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14200. ASSERT_TRUE(svr.is_valid());
  14201. svr.Get("/test", [](const Request &, Response &res) {
  14202. res.set_content("ok", "text/plain");
  14203. });
  14204. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14205. auto se = detail::scope_exit([&] {
  14206. svr.stop();
  14207. t.join();
  14208. });
  14209. svr.wait_until_ready();
  14210. SSLClient cli(HOST, PORT);
  14211. cli.enable_server_certificate_verification(false);
  14212. cli.set_connection_timeout(30);
  14213. bool cert_checked = false;
  14214. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14215. if (ctx.cert) {
  14216. auto sans = ctx.sans();
  14217. // Test certificate may or may not have SANs - just verify the API
  14218. // works If SANs exist, verify the types are valid
  14219. for (const auto &san : sans) {
  14220. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14221. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14222. san.type == SanType::OTHER);
  14223. EXPECT_FALSE(san.value.empty());
  14224. }
  14225. cert_checked = true;
  14226. }
  14227. return true;
  14228. });
  14229. auto res = cli.Get("/test");
  14230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14231. EXPECT_TRUE(cert_checked);
  14232. }
  14233. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14234. using namespace httplib::tls;
  14235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14236. ASSERT_TRUE(svr.is_valid());
  14237. svr.Get("/test", [](const Request &, Response &res) {
  14238. res.set_content("ok", "text/plain");
  14239. });
  14240. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14241. auto se = detail::scope_exit([&] {
  14242. svr.stop();
  14243. t.join();
  14244. });
  14245. svr.wait_until_ready();
  14246. SSLClient cli(HOST, PORT);
  14247. cli.enable_server_certificate_verification(false);
  14248. cli.set_connection_timeout(30);
  14249. bool validity_checked = false;
  14250. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14251. if (ctx.cert) {
  14252. time_t not_before = 0, not_after = 0;
  14253. bool result = ctx.validity(not_before, not_after);
  14254. EXPECT_TRUE(result);
  14255. // Verify that not_before < now < not_after for a valid cert
  14256. time_t now = time(nullptr);
  14257. EXPECT_LT(not_before, now);
  14258. EXPECT_GT(not_after, now);
  14259. validity_checked = true;
  14260. }
  14261. return true;
  14262. });
  14263. auto res = cli.Get("/test");
  14264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14265. EXPECT_TRUE(validity_checked);
  14266. }
  14267. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14268. using namespace httplib::tls;
  14269. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14270. ASSERT_TRUE(svr.is_valid());
  14271. svr.Get("/test", [](const Request &, Response &res) {
  14272. res.set_content("ok", "text/plain");
  14273. });
  14274. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14275. auto se = detail::scope_exit([&] {
  14276. svr.stop();
  14277. t.join();
  14278. });
  14279. svr.wait_until_ready();
  14280. SSLClient cli(HOST, PORT);
  14281. cli.enable_server_certificate_verification(false);
  14282. cli.set_connection_timeout(30);
  14283. bool serial_checked = false;
  14284. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14285. if (ctx.cert) {
  14286. std::string serial = ctx.serial();
  14287. EXPECT_FALSE(serial.empty());
  14288. // Serial should be a hex string
  14289. for (char c : serial) {
  14290. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14291. (c >= 'a' && c <= 'f'));
  14292. }
  14293. serial_checked = true;
  14294. }
  14295. return true;
  14296. });
  14297. auto res = cli.Get("/test");
  14298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14299. EXPECT_TRUE(serial_checked);
  14300. }
  14301. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14302. // Test 1: Valid CA file - no error should be recorded
  14303. {
  14304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14305. CLIENT_CA_CERT_FILE);
  14306. ASSERT_TRUE(svr.is_valid());
  14307. // With valid setup, last_ssl_error should be 0
  14308. EXPECT_EQ(0, svr.ssl_last_error());
  14309. }
  14310. // Test 2: Invalid CA file content
  14311. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14312. {
  14313. // Create a temporary file with completely invalid content
  14314. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14315. {
  14316. std::ofstream ofs(temp_invalid_ca);
  14317. ofs << "This is not a certificate file at all\n";
  14318. ofs << "Just plain text content\n";
  14319. }
  14320. // Create server with invalid CA file
  14321. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14322. // Clean up temporary file
  14323. std::remove(temp_invalid_ca);
  14324. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14325. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14326. // Note: SSL_CTX_load_verify_locations typically fails first,
  14327. // but our error handling code path is still exercised
  14328. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14329. }
  14330. }
  14331. TEST(VerifyCallbackTest, VerifyContextFields) {
  14332. using namespace httplib::tls;
  14333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14334. ASSERT_TRUE(svr.is_valid());
  14335. svr.Get("/test", [](const Request &, Response &res) {
  14336. res.set_content("ok", "text/plain");
  14337. });
  14338. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14339. auto se = detail::scope_exit([&] {
  14340. svr.stop();
  14341. t.join();
  14342. });
  14343. svr.wait_until_ready();
  14344. SSLClient cli(HOST, PORT);
  14345. cli.enable_server_certificate_verification(false);
  14346. cli.set_connection_timeout(30);
  14347. int callback_count = 0;
  14348. bool saw_leaf_cert = false;
  14349. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14350. if (ctx.cert) {
  14351. callback_count++;
  14352. // We should see at least one certificate (the leaf)
  14353. std::string cn = ctx.subject_cn();
  14354. if (!cn.empty()) { saw_leaf_cert = true; }
  14355. // Verify context fields are populated
  14356. EXPECT_NE(ctx.session, nullptr);
  14357. EXPECT_GE(ctx.depth, 0);
  14358. }
  14359. return true;
  14360. });
  14361. auto res = cli.Get("/test");
  14362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14363. EXPECT_GT(callback_count, 0);
  14364. EXPECT_TRUE(saw_leaf_cert);
  14365. }
  14366. // A verifier that accepts runs alongside the built-in verification, and is the
  14367. // only check once that is turned off.
  14368. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14369. using namespace httplib::tls;
  14370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14371. ASSERT_TRUE(svr.is_valid());
  14372. svr.Get("/test", [](const Request &, Response &res) {
  14373. res.set_content("ok", "text/plain");
  14374. });
  14375. auto port = svr.bind_to_any_port(HOST);
  14376. thread t([&]() { svr.listen_after_bind(); });
  14377. auto se = detail::scope_exit([&] {
  14378. svr.stop();
  14379. t.join();
  14380. });
  14381. svr.wait_until_ready();
  14382. SSLClient cli(HOST, port);
  14383. cli.enable_server_hostname_verification(false);
  14384. auto calls = 0;
  14385. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14386. calls++;
  14387. return true;
  14388. });
  14389. // cert.pem is not trusted
  14390. auto res = cli.Get("/test");
  14391. ASSERT_FALSE(res);
  14392. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14393. EXPECT_GT(calls, 0);
  14394. cli.enable_server_certificate_verification(false);
  14395. res = cli.Get("/test");
  14396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14397. EXPECT_EQ("ok", res->body);
  14398. }
  14399. // A verifier belongs to the client that set it, not to the thread that set it.
  14400. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14401. using namespace httplib::tls;
  14402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14403. ASSERT_TRUE(svr.is_valid());
  14404. svr.Get("/test", [](const Request &, Response &res) {
  14405. res.set_content("ok", "text/plain");
  14406. });
  14407. auto port = svr.bind_to_any_port(HOST);
  14408. thread t([&]() { svr.listen_after_bind(); });
  14409. auto se = detail::scope_exit([&] {
  14410. svr.stop();
  14411. t.join();
  14412. });
  14413. svr.wait_until_ready();
  14414. auto rejecting_calls = 0;
  14415. SSLClient rejecting(HOST, port);
  14416. rejecting.enable_server_certificate_verification(false);
  14417. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14418. rejecting_calls++;
  14419. return false;
  14420. });
  14421. auto accepting_calls = 0;
  14422. SSLClient accepting(HOST, port);
  14423. accepting.enable_server_certificate_verification(false);
  14424. // Set on another thread than the requests below.
  14425. thread([&]() {
  14426. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14427. accepting_calls++;
  14428. return true;
  14429. });
  14430. }).join();
  14431. // Requested on another thread than the verifier was set on.
  14432. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14433. EXPECT_GT(rejecting_calls, 0);
  14434. auto res = accepting.Get("/test");
  14435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14436. EXPECT_GT(accepting_calls, 0);
  14437. }
  14438. // A verifier replaced while a handshake runs it lives until it returns.
  14439. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14440. using namespace httplib::tls;
  14441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14442. ASSERT_TRUE(svr.is_valid());
  14443. svr.Get("/test", [](const Request &, Response &res) {
  14444. res.set_content("ok", "text/plain");
  14445. });
  14446. auto port = svr.bind_to_any_port(HOST);
  14447. thread t([&]() { svr.listen_after_bind(); });
  14448. auto se = detail::scope_exit([&] {
  14449. svr.stop();
  14450. t.join();
  14451. });
  14452. svr.wait_until_ready();
  14453. SSLClient cli(HOST, port);
  14454. cli.enable_server_certificate_verification(false);
  14455. std::promise<void> entered;
  14456. std::promise<void> replaced;
  14457. auto replaced_future = replaced.get_future();
  14458. auto first_call = true;
  14459. // Long enough to live on the heap
  14460. std::string expected(64, 'v');
  14461. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14462. if (first_call) {
  14463. first_call = false;
  14464. entered.set_value();
  14465. replaced_future.wait();
  14466. }
  14467. return expected == std::string(64, 'v');
  14468. });
  14469. thread request([&]() {
  14470. auto res = cli.Get("/test");
  14471. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14472. });
  14473. entered.get_future().wait();
  14474. cli.set_server_certificate_verifier(
  14475. [](const VerifyContext &) { return true; });
  14476. replaced.set_value();
  14477. request.join();
  14478. }
  14479. // VerifyContext::session is the same handle the other tls:: functions take.
  14480. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14481. using namespace httplib::tls;
  14482. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14483. ASSERT_TRUE(svr.is_valid());
  14484. svr.Get("/test", [](const Request &, Response &res) {
  14485. res.set_content("ok", "text/plain");
  14486. });
  14487. auto port = svr.bind_to_any_port(HOST);
  14488. thread t([&]() { svr.listen_after_bind(); });
  14489. auto se = detail::scope_exit([&] {
  14490. svr.stop();
  14491. t.join();
  14492. });
  14493. svr.wait_until_ready();
  14494. SSLClient cli(HOST, port);
  14495. cli.enable_server_certificate_verification(false);
  14496. session_t verifier_session = nullptr;
  14497. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14498. verifier_session = ctx.session;
  14499. return true;
  14500. });
  14501. session_t session_verifier_session = nullptr;
  14502. cli.set_session_verifier([&](session_t session) {
  14503. session_verifier_session = session;
  14504. return SSLVerifierResponse::NoDecisionMade;
  14505. });
  14506. auto res = cli.Get("/test");
  14507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14508. EXPECT_NE(nullptr, verifier_session);
  14509. EXPECT_EQ(session_verifier_session, verifier_session);
  14510. }
  14511. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14512. using httplib::tls::TlsError;
  14513. // Test that verify_error_to_string returns empty for success
  14514. std::string success_str = TlsError::verify_error_to_string(0);
  14515. EXPECT_TRUE(success_str.empty());
  14516. // Test that verify_error_to_string returns non-empty for error codes
  14517. // Using a common error code (certificate expired)
  14518. std::string error_str =
  14519. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14520. EXPECT_FALSE(error_str.empty());
  14521. }
  14522. TEST(SessionVerifierTest, CertificateAccepted) {
  14523. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14524. ASSERT_TRUE(svr.is_valid());
  14525. svr.Get("/test", [](const Request &, Response &res) {
  14526. res.set_content("ok", "text/plain");
  14527. });
  14528. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14529. auto se = detail::scope_exit([&] {
  14530. svr.stop();
  14531. t.join();
  14532. });
  14533. svr.wait_until_ready();
  14534. SSLClient cli(HOST, PORT);
  14535. cli.enable_server_certificate_verification(false);
  14536. cli.set_connection_timeout(30);
  14537. bool callback_called = false;
  14538. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14539. EXPECT_NE(session, nullptr);
  14540. callback_called = true;
  14541. return SSLVerifierResponse::CertificateAccepted;
  14542. });
  14543. auto res = cli.Get("/test");
  14544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14545. EXPECT_EQ(200, res->status);
  14546. EXPECT_TRUE(callback_called);
  14547. }
  14548. TEST(SessionVerifierTest, CertificateRejected) {
  14549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14550. ASSERT_TRUE(svr.is_valid());
  14551. svr.Get("/test", [](const Request &, Response &res) {
  14552. res.set_content("ok", "text/plain");
  14553. });
  14554. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14555. auto se = detail::scope_exit([&] {
  14556. svr.stop();
  14557. t.join();
  14558. });
  14559. svr.wait_until_ready();
  14560. SSLClient cli(HOST, PORT);
  14561. cli.enable_server_certificate_verification(false);
  14562. cli.set_connection_timeout(30);
  14563. bool callback_called = false;
  14564. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14565. EXPECT_NE(session, nullptr);
  14566. callback_called = true;
  14567. return SSLVerifierResponse::CertificateRejected;
  14568. });
  14569. auto res = cli.Get("/test");
  14570. EXPECT_FALSE(res);
  14571. EXPECT_TRUE(callback_called);
  14572. }
  14573. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14575. ASSERT_TRUE(svr.is_valid());
  14576. svr.Get("/test", [](const Request &, Response &res) {
  14577. res.set_content("ok", "text/plain");
  14578. });
  14579. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14580. auto se = detail::scope_exit([&] {
  14581. svr.stop();
  14582. t.join();
  14583. });
  14584. svr.wait_until_ready();
  14585. // NoDecisionMade with verification disabled should succeed (no default check)
  14586. SSLClient cli(HOST, PORT);
  14587. cli.enable_server_certificate_verification(false);
  14588. cli.set_connection_timeout(30);
  14589. bool callback_called = false;
  14590. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14591. EXPECT_NE(session, nullptr);
  14592. callback_called = true;
  14593. return SSLVerifierResponse::NoDecisionMade;
  14594. });
  14595. auto res = cli.Get("/test");
  14596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14597. EXPECT_EQ(200, res->status);
  14598. EXPECT_TRUE(callback_called);
  14599. }
  14600. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14602. ASSERT_TRUE(svr.is_valid());
  14603. svr.Get("/test", [](const Request &, Response &res) {
  14604. res.set_content("ok", "text/plain");
  14605. });
  14606. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14607. auto se = detail::scope_exit([&] {
  14608. svr.stop();
  14609. t.join();
  14610. });
  14611. svr.wait_until_ready();
  14612. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14613. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14614. // so we only check that the request fails, not whether the callback was
  14615. // called.
  14616. SSLClient cli(HOST, PORT);
  14617. cli.enable_server_certificate_verification(true);
  14618. cli.set_connection_timeout(30);
  14619. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14620. EXPECT_NE(session, nullptr);
  14621. return SSLVerifierResponse::NoDecisionMade;
  14622. });
  14623. auto res = cli.Get("/test");
  14624. EXPECT_FALSE(res);
  14625. }
  14626. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14627. // Test SSL server using PemMemory constructor with client CA certificates
  14628. // Read PEM files
  14629. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14630. read_file(SERVER_CERT_FILE, server_cert_pem);
  14631. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14632. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14633. // Create SSLServer with PemMemory constructor including client CA
  14634. SSLServer::PemMemory server_pem = {
  14635. server_cert_pem.c_str(),
  14636. server_cert_pem.size(),
  14637. server_key_pem.c_str(),
  14638. server_key_pem.size(),
  14639. client_ca_pem.c_str(),
  14640. client_ca_pem.size(),
  14641. nullptr // no password for server key
  14642. };
  14643. SSLServer svr(server_pem);
  14644. ASSERT_TRUE(svr.is_valid());
  14645. // No SSL error should be recorded for valid setup
  14646. EXPECT_EQ(0, svr.ssl_last_error());
  14647. // Set up server endpoints
  14648. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14649. res.set_content("ok", "text/plain");
  14650. });
  14651. // Start server in a thread
  14652. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14653. svr.wait_until_ready();
  14654. // Connect with client certificate (using constructor with paths)
  14655. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14656. cli.enable_server_certificate_verification(false);
  14657. auto res = cli.Get("/test-pem-ca");
  14658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14659. EXPECT_EQ(200, res->status);
  14660. EXPECT_EQ("ok", res->body);
  14661. svr.stop();
  14662. server_thread.join();
  14663. }
  14664. #endif
  14665. #ifdef _WIN32
  14666. TEST(CleanupTest, WSACleanup) {
  14667. int ret = WSACleanup();
  14668. ASSERT_EQ(0, ret);
  14669. }
  14670. #endif
  14671. #ifndef CPPHTTPLIB_SSL_ENABLED
  14672. TEST(NoSSLSupport, SimpleInterface) {
  14673. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14674. }
  14675. #endif
  14676. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14677. TEST(InvalidScheme, SimpleInterface) {
  14678. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14679. }
  14680. #endif
  14681. TEST(NoScheme, SimpleInterface) {
  14682. Client cli("yahoo.com:80");
  14683. ASSERT_TRUE(cli.is_valid());
  14684. }
  14685. TEST(SendAPI, SimpleInterface_Online) {
  14686. Client cli("http://yahoo.com");
  14687. Request req;
  14688. req.method = "GET";
  14689. req.path = "/";
  14690. auto res = cli.send(req);
  14691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14692. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14693. }
  14694. TEST(SendAPI, WithParamsInRequest) {
  14695. Server svr;
  14696. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14697. EXPECT_TRUE(req.has_param("test"));
  14698. EXPECT_EQ("test_value", req.get_param_value("test"));
  14699. });
  14700. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14701. auto se = detail::scope_exit([&] {
  14702. svr.stop();
  14703. t.join();
  14704. ASSERT_FALSE(svr.is_running());
  14705. });
  14706. svr.wait_until_ready();
  14707. Client cli(HOST, PORT);
  14708. {
  14709. Request req;
  14710. req.method = "GET";
  14711. req.path = "/";
  14712. req.params.emplace("test", "test_value");
  14713. auto res = cli.send(req);
  14714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14715. }
  14716. {
  14717. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14719. }
  14720. }
  14721. TEST(ClientImplMethods, GetSocketTest) {
  14722. httplib::Server svr;
  14723. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14724. res.status = StatusCode::OK_200;
  14725. });
  14726. auto port = svr.bind_to_any_port("127.0.0.1");
  14727. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14728. auto se = detail::scope_exit([&] {
  14729. svr.stop();
  14730. thread.join();
  14731. ASSERT_FALSE(svr.is_running());
  14732. });
  14733. svr.wait_until_ready();
  14734. {
  14735. httplib::Client cli("127.0.0.1", port);
  14736. cli.set_keep_alive(true);
  14737. // Use the behavior of cpp-httplib of opening the connection
  14738. // only when the first request happens. If that changes,
  14739. // this test would be obsolete.
  14740. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14741. // This also implicitly tests the server. But other tests would fail much
  14742. // earlier than this one to be considered.
  14743. auto res = cli.Get("/");
  14744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14745. EXPECT_EQ(StatusCode::OK_200, res->status);
  14746. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14747. }
  14748. }
  14749. #ifdef CPPHTTPLIB_SSL_ENABLED
  14750. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14751. Client cli("http://yahoo.com");
  14752. auto res = cli.Get("/");
  14753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14754. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14755. cli.set_follow_location(true);
  14756. res = cli.Get("/");
  14757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14758. EXPECT_EQ(StatusCode::OK_200, res->status);
  14759. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14760. }
  14761. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14762. Client cli("https://yahoo.com");
  14763. auto res = cli.Get("/");
  14764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14765. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14766. cli.set_follow_location(true);
  14767. res = cli.Get("/");
  14768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14769. EXPECT_EQ(StatusCode::OK_200, res->status);
  14770. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14771. }
  14772. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14773. Client cli("https://yahoo.com");
  14774. auto res = cli.Get("/");
  14775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14776. ASSERT_FALSE(!res);
  14777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14778. ASSERT_FALSE(res == nullptr);
  14779. ASSERT_TRUE(res != nullptr);
  14780. EXPECT_EQ(Error::Success, res.error());
  14781. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14782. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14783. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14784. cli.set_follow_location(true);
  14785. res = cli.Get("/");
  14786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14787. EXPECT_EQ(Error::Success, res.error());
  14788. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14789. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14790. EXPECT_EQ(StatusCode::OK_200, res->status);
  14791. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14792. }
  14793. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14794. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14795. Client cli("https://cdnjs.cloudflare.com");
  14796. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14797. Headers{{"Accept-Encoding", "br"}});
  14798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14799. EXPECT_EQ(StatusCode::OK_200, res->status);
  14800. EXPECT_EQ(287630U, res->body.size());
  14801. EXPECT_EQ("application/javascript; charset=utf-8",
  14802. res->get_header_value("Content-Type"));
  14803. }
  14804. #endif
  14805. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14806. #undef REDIR_HOST // Silence compiler warning
  14807. #define REDIR_HOST "https://httpbingo.org"
  14808. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14809. Client cli(REDIR_HOST);
  14810. cli.set_follow_location(true);
  14811. auto res =
  14812. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14814. EXPECT_EQ(StatusCode::OK_200, res->status);
  14815. }
  14816. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14817. Client cli(REDIR_HOST);
  14818. cli.set_follow_location(true);
  14819. Params params;
  14820. params.emplace("url", "http://example.com");
  14821. params.emplace("status_code", "302");
  14822. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14824. EXPECT_EQ(StatusCode::OK_200, res->status);
  14825. }
  14826. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14827. Client cli(REDIR_HOST);
  14828. cli.set_follow_location(true);
  14829. Params params;
  14830. params.emplace("url", "http://example.com");
  14831. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14833. EXPECT_EQ(StatusCode::OK_200, res->status);
  14834. }
  14835. TEST(HttpToHttpsRedirectTest, CertFile) {
  14836. auto ssl_port = PORT + 1;
  14837. Server svr;
  14838. ASSERT_TRUE(svr.is_valid());
  14839. svr.Get("/index", [&](const Request &, Response &res) {
  14840. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14841. "/index");
  14842. svr.stop();
  14843. });
  14844. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14845. ASSERT_TRUE(ssl_svr.is_valid());
  14846. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14847. res.set_content("test", "text/plain");
  14848. ssl_svr.stop();
  14849. });
  14850. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14851. thread t2 =
  14852. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14853. auto se = detail::scope_exit([&] {
  14854. t2.join();
  14855. t.join();
  14856. ASSERT_FALSE(svr.is_running());
  14857. });
  14858. svr.wait_until_ready();
  14859. ssl_svr.wait_until_ready();
  14860. Client cli("127.0.0.1", PORT);
  14861. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14862. cli.enable_server_certificate_verification(true);
  14863. cli.set_follow_location(true);
  14864. cli.set_connection_timeout(30);
  14865. auto res = cli.Get("/index");
  14866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14867. ASSERT_EQ(StatusCode::OK_200, res->status);
  14868. }
  14869. TEST(SSLClientRedirectTest, CertFile) {
  14870. auto ssl_port = PORT + 1;
  14871. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14872. ASSERT_TRUE(ssl_svr1.is_valid());
  14873. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14874. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14875. "/index");
  14876. ssl_svr1.stop();
  14877. });
  14878. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14879. ASSERT_TRUE(ssl_svr2.is_valid());
  14880. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14881. res.set_content("test", "text/plain");
  14882. ssl_svr2.stop();
  14883. });
  14884. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14885. thread t2 =
  14886. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14887. auto se = detail::scope_exit([&] {
  14888. t2.join();
  14889. t.join();
  14890. ASSERT_FALSE(ssl_svr1.is_running());
  14891. });
  14892. ssl_svr1.wait_until_ready();
  14893. ssl_svr2.wait_until_ready();
  14894. SSLClient cli("127.0.0.1", PORT);
  14895. std::string cert;
  14896. read_file(SERVER_CERT2_FILE, cert);
  14897. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14898. cli.enable_server_certificate_verification(true);
  14899. cli.set_follow_location(true);
  14900. cli.set_connection_timeout(30);
  14901. auto res = cli.Get("/index");
  14902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14903. ASSERT_EQ(StatusCode::OK_200, res->status);
  14904. }
  14905. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14906. // another port, so the client follows it with a new client.
  14907. static Result GetThroughTlsRedirectToDifferentPort(
  14908. const std::function<void(SSLClient &)> &setup,
  14909. const char *target_cert = SERVER_CERT2_FILE,
  14910. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14911. auto ssl_port = PORT + 1;
  14912. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14913. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14914. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14915. "/index");
  14916. });
  14917. SSLServer ssl_svr2(target_cert, target_key);
  14918. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14919. res.set_content("test", "text/plain");
  14920. });
  14921. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14922. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14923. auto se = detail::scope_exit([&] {
  14924. ssl_svr2.stop();
  14925. ssl_svr1.stop();
  14926. t2.join();
  14927. t.join();
  14928. });
  14929. ssl_svr1.wait_until_ready();
  14930. ssl_svr2.wait_until_ready();
  14931. SSLClient cli("127.0.0.1", PORT);
  14932. cli.set_follow_location(true);
  14933. cli.set_connection_timeout(30);
  14934. setup(cli);
  14935. return cli.Get("/index");
  14936. }
  14937. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14938. auto calls = 0;
  14939. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14940. cli.enable_server_certificate_verification(false);
  14941. // Accept the first server only.
  14942. cli.set_session_verifier([&](tls::session_t) {
  14943. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14944. : SSLVerifierResponse::CertificateRejected;
  14945. });
  14946. });
  14947. ASSERT_FALSE(res);
  14948. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14949. EXPECT_EQ(2, calls);
  14950. }
  14951. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14952. std::string pinned;
  14953. auto res = GetThroughTlsRedirectToDifferentPort(
  14954. [&](SSLClient &cli) {
  14955. cli.enable_server_certificate_verification(false);
  14956. // Pin the first certificate seen.
  14957. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14958. if (pinned.empty()) { pinned = ctx.serial(); }
  14959. return ctx.serial() == pinned;
  14960. });
  14961. },
  14962. // A certificate other than the first server's.
  14963. SERVER_CERT_FILE);
  14964. EXPECT_FALSE(res);
  14965. EXPECT_FALSE(pinned.empty());
  14966. }
  14967. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14968. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14969. std::string cert;
  14970. read_file(SERVER_CERT2_FILE, cert);
  14971. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14972. });
  14973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14974. EXPECT_EQ(StatusCode::OK_200, res->status);
  14975. }
  14976. // The target's certificate is signed by the root CA, which the first server's
  14977. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  14978. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  14979. auto res = GetThroughTlsRedirectToDifferentPort(
  14980. [](SSLClient &cli) {
  14981. std::string root_ca, cert;
  14982. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14983. read_file(SERVER_CERT2_FILE, cert);
  14984. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14985. cli.load_ca_cert_store(cert.data(), cert.size());
  14986. cli.enable_server_hostname_verification(false);
  14987. },
  14988. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14990. EXPECT_EQ(StatusCode::OK_200, res->status);
  14991. }
  14992. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  14993. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  14994. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  14995. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  14996. auto res = GetThroughTlsRedirectToDifferentPort(
  14997. [](SSLClient &cli) {
  14998. std::string root_ca, cert;
  14999. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15000. read_file(SERVER_CERT2_FILE, cert);
  15001. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15002. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15003. cli.enable_server_hostname_verification(false);
  15004. },
  15005. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15006. ASSERT_FALSE(res);
  15007. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15008. }
  15009. #endif
  15010. #endif
  15011. #ifdef CPPHTTPLIB_SSL_ENABLED
  15012. // Test that set_ca_cert_store() skips system certs (consistent with
  15013. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15014. // should be trusted - system certs should NOT be loaded.
  15015. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15016. // Load a specific cert that is NOT a system CA cert
  15017. std::string cert;
  15018. read_file(SERVER_CERT2_FILE, cert);
  15019. SSLClient cli("google.com");
  15020. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15021. cli.enable_server_certificate_verification(true);
  15022. // This should FAIL because:
  15023. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15024. // 2. System certs should NOT be loaded when custom store is set
  15025. // If system certs WERE loaded, this would succeed
  15026. auto res = cli.Get("/");
  15027. ASSERT_FALSE(res);
  15028. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15029. }
  15030. // Same as above, but through the native store handle path. Regression test:
  15031. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15032. // merged system certs into the user-provided store.
  15033. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15034. std::string cert;
  15035. read_file(SERVER_CERT2_FILE, cert);
  15036. SSLClient cli("google.com");
  15037. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15038. cli.enable_server_certificate_verification(true);
  15039. auto res = cli.Get("/");
  15040. ASSERT_FALSE(res);
  15041. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15042. }
  15043. // A custom store set via the native handle must still verify a server whose
  15044. // cert it does contain.
  15045. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15046. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15047. ASSERT_TRUE(svr.is_valid());
  15048. svr.Get("/test", [&](const Request &, Response &res) {
  15049. res.set_content("test", "text/plain");
  15050. });
  15051. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15052. auto se = detail::scope_exit([&] {
  15053. svr.stop();
  15054. t.join();
  15055. ASSERT_FALSE(svr.is_running());
  15056. });
  15057. svr.wait_until_ready();
  15058. SSLClient cli("127.0.0.1", PORT);
  15059. std::string cert;
  15060. read_file(SERVER_CERT2_FILE, cert);
  15061. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15062. cli.enable_server_certificate_verification(true);
  15063. cli.set_connection_timeout(30);
  15064. auto res = cli.Get("/test");
  15065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15066. ASSERT_EQ(StatusCode::OK_200, res->status);
  15067. }
  15068. // CA certs loaded through the universal Client must be transferred to the
  15069. // client created internally for following an HTTPS redirect. Regression test:
  15070. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15071. // the CA data for redirect transfer.
  15072. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15073. auto ssl_port = PORT + 1;
  15074. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15075. ASSERT_TRUE(ssl_svr1.is_valid());
  15076. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15077. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15078. "/index");
  15079. });
  15080. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15081. ASSERT_TRUE(ssl_svr2.is_valid());
  15082. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15083. res.set_content("test", "text/plain");
  15084. });
  15085. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15086. thread t2 =
  15087. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15088. auto se = detail::scope_exit([&] {
  15089. ssl_svr2.stop();
  15090. ssl_svr1.stop();
  15091. t2.join();
  15092. t.join();
  15093. ASSERT_FALSE(ssl_svr1.is_running());
  15094. });
  15095. ssl_svr1.wait_until_ready();
  15096. ssl_svr2.wait_until_ready();
  15097. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15098. std::string cert;
  15099. read_file(SERVER_CERT2_FILE, cert);
  15100. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15101. cli.enable_server_certificate_verification(true);
  15102. cli.set_follow_location(true);
  15103. cli.set_connection_timeout(30);
  15104. auto res = cli.Get("/index");
  15105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15106. ASSERT_EQ(StatusCode::OK_200, res->status);
  15107. }
  15108. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15109. // so a host signed by a system CA verifies even though a custom CA is set
  15110. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15111. std::string cert;
  15112. read_file(SERVER_CERT2_FILE, cert);
  15113. SSLClient cli("google.com");
  15114. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15115. cli.enable_system_ca(true);
  15116. cli.enable_server_certificate_verification(true);
  15117. auto res = cli.Get("/");
  15118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15119. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15120. }
  15121. // The custom CA remains effective when combined with the system CA
  15122. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15123. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15124. ASSERT_TRUE(svr.is_valid());
  15125. svr.Get("/test", [&](const Request &, Response &res) {
  15126. res.set_content("test", "text/plain");
  15127. });
  15128. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15129. auto se = detail::scope_exit([&] {
  15130. svr.stop();
  15131. t.join();
  15132. ASSERT_FALSE(svr.is_running());
  15133. });
  15134. svr.wait_until_ready();
  15135. SSLClient cli("127.0.0.1", PORT);
  15136. std::string cert;
  15137. read_file(SERVER_CERT2_FILE, cert);
  15138. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15139. cli.enable_system_ca(true);
  15140. cli.enable_server_certificate_verification(true);
  15141. cli.set_connection_timeout(30);
  15142. auto res = cli.Get("/test");
  15143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15144. ASSERT_EQ(StatusCode::OK_200, res->status);
  15145. }
  15146. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15147. // skip chain verification entirely (only the certificate identity was
  15148. // checked), so a server presenting an untrusted certificate with a matching
  15149. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15150. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15151. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15152. ASSERT_TRUE(svr.is_valid());
  15153. svr.Get("/test", [&](const Request &, Response &res) {
  15154. res.set_content("test", "text/plain");
  15155. });
  15156. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15157. auto se = detail::scope_exit([&] {
  15158. svr.stop();
  15159. t.join();
  15160. ASSERT_FALSE(svr.is_running());
  15161. });
  15162. svr.wait_until_ready();
  15163. SSLClient cli("127.0.0.1", PORT);
  15164. std::string cert;
  15165. // A trusted CA that did not sign the server certificate. The server cert
  15166. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15167. // this connection.
  15168. read_file(CLIENT_CA_CERT_FILE, cert);
  15169. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15170. cli.enable_server_certificate_verification(true);
  15171. cli.set_connection_timeout(30);
  15172. auto res = cli.Get("/test");
  15173. ASSERT_FALSE(res);
  15174. }
  15175. // enable_system_ca(false) prevents system CA loading entirely
  15176. TEST(SSLClientTest, DisableSystemCa_Online) {
  15177. SSLClient cli("google.com");
  15178. cli.enable_system_ca(false);
  15179. cli.enable_server_certificate_verification(true);
  15180. auto res = cli.Get("/");
  15181. ASSERT_FALSE(res);
  15182. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15183. // itself when the CA chain is empty
  15184. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15185. res.error() == Error::SSLConnection);
  15186. }
  15187. // The universal Client forwards enable_system_ca()
  15188. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15189. std::string cert;
  15190. read_file(SERVER_CERT2_FILE, cert);
  15191. Client cli("https://google.com");
  15192. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15193. cli.enable_system_ca(true);
  15194. cli.enable_server_certificate_verification(true);
  15195. auto res = cli.Get("/");
  15196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15197. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15198. }
  15199. // The system CA policy must carry over to the client created internally for
  15200. // following a cross-host HTTPS redirect
  15201. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15202. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15203. ASSERT_TRUE(svr.is_valid());
  15204. svr.Get("/index", [&](const Request &, Response &res) {
  15205. res.set_redirect("https://www.google.com/");
  15206. });
  15207. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15208. auto se = detail::scope_exit([&] {
  15209. svr.stop();
  15210. t.join();
  15211. ASSERT_FALSE(svr.is_running());
  15212. });
  15213. svr.wait_until_ready();
  15214. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15215. std::string cert;
  15216. read_file(SERVER_CERT2_FILE, cert);
  15217. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15218. cli.enable_system_ca(true);
  15219. cli.enable_server_certificate_verification(true);
  15220. cli.set_follow_location(true);
  15221. cli.set_connection_timeout(30);
  15222. // Receiving any response proves the redirect client completed the TLS
  15223. // handshake with a system-CA-signed host
  15224. auto res = cli.Get("/index");
  15225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15226. }
  15227. TEST(MultipartFormDataTest, LargeData) {
  15228. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15229. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15230. const ContentReader &content_reader) {
  15231. if (req.is_multipart_form_data()) {
  15232. std::vector<FormData> items;
  15233. content_reader(
  15234. [&](const FormData &file) {
  15235. items.push_back(file);
  15236. return true;
  15237. },
  15238. [&](const char *data, size_t data_length) {
  15239. items.back().content.append(data, data_length);
  15240. return true;
  15241. });
  15242. EXPECT_TRUE(std::string(items[0].name) == "document");
  15243. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15244. EXPECT_TRUE(items[0].filename == "2MB_data");
  15245. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15246. EXPECT_TRUE(items[1].name == "hello");
  15247. EXPECT_TRUE(items[1].content == "world");
  15248. EXPECT_TRUE(items[1].filename == "");
  15249. EXPECT_TRUE(items[1].content_type == "");
  15250. } else {
  15251. std::string body;
  15252. content_reader([&](const char *data, size_t data_length) {
  15253. body.append(data, data_length);
  15254. return true;
  15255. });
  15256. }
  15257. });
  15258. auto port = svr.bind_to_any_port(HOST);
  15259. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15260. auto se = detail::scope_exit([&] {
  15261. svr.stop();
  15262. t.join();
  15263. ASSERT_FALSE(svr.is_running());
  15264. });
  15265. svr.wait_until_ready();
  15266. {
  15267. std::string data(1024 * 1024 * 2, '.');
  15268. std::stringstream buffer;
  15269. buffer << data;
  15270. SSLClient cli(HOST, port);
  15271. cli.enable_server_certificate_verification(false);
  15272. UploadFormDataItems items{
  15273. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15274. {"hello", "world", "", ""},
  15275. };
  15276. auto res = cli.Post("/post", items);
  15277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15278. ASSERT_EQ(StatusCode::OK_200, res->status);
  15279. }
  15280. }
  15281. TEST(MultipartFormDataTest, DataProviderItems) {
  15282. std::random_device seed_gen;
  15283. std::mt19937 random(seed_gen());
  15284. std::string rand1;
  15285. rand1.resize(1000);
  15286. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15287. std::string rand2;
  15288. rand2.resize(3000);
  15289. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15290. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15291. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15292. const ContentReader &content_reader) {
  15293. ASSERT_FALSE(req.is_multipart_form_data());
  15294. std::string body;
  15295. content_reader([&](const char *data, size_t data_length) {
  15296. body.append(data, data_length);
  15297. return true;
  15298. });
  15299. EXPECT_EQ(body, "");
  15300. });
  15301. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15302. const ContentReader &content_reader) {
  15303. ASSERT_TRUE(req.is_multipart_form_data());
  15304. std::vector<FormData> items;
  15305. content_reader(
  15306. [&](const FormData &file) {
  15307. items.push_back(file);
  15308. return true;
  15309. },
  15310. [&](const char *data, size_t data_length) {
  15311. items.back().content.append(data, data_length);
  15312. return true;
  15313. });
  15314. ASSERT_TRUE(items.size() == 2);
  15315. EXPECT_EQ(std::string(items[0].name), "name1");
  15316. EXPECT_EQ(items[0].content, "Testing123");
  15317. EXPECT_EQ(items[0].filename, "filename1");
  15318. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15319. EXPECT_EQ(items[1].name, "name2");
  15320. EXPECT_EQ(items[1].content, "Testing456");
  15321. EXPECT_EQ(items[1].filename, "");
  15322. EXPECT_EQ(items[1].content_type, "");
  15323. });
  15324. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15325. const ContentReader &content_reader) {
  15326. ASSERT_TRUE(req.is_multipart_form_data());
  15327. std::vector<FormData> items;
  15328. content_reader(
  15329. [&](const FormData &file) {
  15330. items.push_back(file);
  15331. return true;
  15332. },
  15333. [&](const char *data, size_t data_length) {
  15334. items.back().content.append(data, data_length);
  15335. return true;
  15336. });
  15337. ASSERT_TRUE(items.size() == 2);
  15338. EXPECT_EQ(items[0].name, "name3");
  15339. EXPECT_EQ(items[0].content, rand1);
  15340. EXPECT_EQ(items[0].filename, "filename3");
  15341. EXPECT_EQ(items[0].content_type, "");
  15342. EXPECT_EQ(items[1].name, "name4");
  15343. EXPECT_EQ(items[1].content, rand2);
  15344. EXPECT_EQ(items[1].filename, "filename4");
  15345. EXPECT_EQ(items[1].content_type, "");
  15346. });
  15347. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15348. const ContentReader &content_reader) {
  15349. ASSERT_TRUE(req.is_multipart_form_data());
  15350. std::vector<FormData> items;
  15351. content_reader(
  15352. [&](const FormData &file) {
  15353. items.push_back(file);
  15354. return true;
  15355. },
  15356. [&](const char *data, size_t data_length) {
  15357. items.back().content.append(data, data_length);
  15358. return true;
  15359. });
  15360. ASSERT_TRUE(items.size() == 4);
  15361. EXPECT_EQ(std::string(items[0].name), "name1");
  15362. EXPECT_EQ(items[0].content, "Testing123");
  15363. EXPECT_EQ(items[0].filename, "filename1");
  15364. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15365. EXPECT_EQ(items[1].name, "name2");
  15366. EXPECT_EQ(items[1].content, "Testing456");
  15367. EXPECT_EQ(items[1].filename, "");
  15368. EXPECT_EQ(items[1].content_type, "");
  15369. EXPECT_EQ(items[2].name, "name3");
  15370. EXPECT_EQ(items[2].content, rand1);
  15371. EXPECT_EQ(items[2].filename, "filename3");
  15372. EXPECT_EQ(items[2].content_type, "");
  15373. EXPECT_EQ(items[3].name, "name4");
  15374. EXPECT_EQ(items[3].content, rand2);
  15375. EXPECT_EQ(items[3].filename, "filename4");
  15376. EXPECT_EQ(items[3].content_type, "");
  15377. });
  15378. auto port = svr.bind_to_any_port("localhost");
  15379. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15380. auto se = detail::scope_exit([&] {
  15381. svr.stop();
  15382. t.join();
  15383. ASSERT_FALSE(svr.is_running());
  15384. });
  15385. svr.wait_until_ready();
  15386. {
  15387. SSLClient cli("localhost", port);
  15388. cli.enable_server_certificate_verification(false);
  15389. UploadFormDataItems items{
  15390. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15391. {"name2", "Testing456", "", ""}, // not a file
  15392. };
  15393. {
  15394. auto res = cli.Post("/post-none", {}, {}, {});
  15395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15396. ASSERT_EQ(StatusCode::OK_200, res->status);
  15397. }
  15398. FormDataProviderItems providers;
  15399. {
  15400. auto res =
  15401. cli.Post("/post-items", {}, items, providers); // empty providers
  15402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15403. ASSERT_EQ(StatusCode::OK_200, res->status);
  15404. }
  15405. providers.push_back({"name3",
  15406. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15407. // test the offset is given correctly at each step
  15408. if (!offset)
  15409. sink.os.write(rand1.data(), 30);
  15410. else if (offset == 30)
  15411. sink.os.write(rand1.data() + 30, 300);
  15412. else if (offset == 330)
  15413. sink.os.write(rand1.data() + 330, 670);
  15414. else if (offset == rand1.size())
  15415. sink.done();
  15416. return true;
  15417. },
  15418. "filename3",
  15419. {}});
  15420. providers.push_back({"name4",
  15421. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15422. // test the offset is given correctly at each step
  15423. if (!offset)
  15424. sink.os.write(rand2.data(), 2000);
  15425. else if (offset == 2000)
  15426. sink.os.write(rand2.data() + 2000, 1);
  15427. else if (offset == 2001)
  15428. sink.os.write(rand2.data() + 2001, 999);
  15429. else if (offset == rand2.size())
  15430. sink.done();
  15431. return true;
  15432. },
  15433. "filename4",
  15434. {}});
  15435. {
  15436. auto res = cli.Post("/post-providers", {}, {}, providers);
  15437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15438. ASSERT_EQ(StatusCode::OK_200, res->status);
  15439. }
  15440. {
  15441. auto res = cli.Post("/post-both", {}, items, providers);
  15442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15443. ASSERT_EQ(StatusCode::OK_200, res->status);
  15444. }
  15445. }
  15446. }
  15447. TEST(MultipartFormDataTest, BadHeader) {
  15448. Server svr;
  15449. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15450. res.set_content("ok", "text/plain");
  15451. });
  15452. thread t = thread([&] { svr.listen(HOST, PORT); });
  15453. auto se = detail::scope_exit([&] {
  15454. svr.stop();
  15455. t.join();
  15456. ASSERT_FALSE(svr.is_running());
  15457. });
  15458. svr.wait_until_ready();
  15459. const std::string body =
  15460. "This is the preamble. It is to be ignored, though it\r\n"
  15461. "is a handy place for composition agents to include an\r\n"
  15462. "explanatory note to non-MIME conformant readers.\r\n"
  15463. "\r\n"
  15464. "\r\n"
  15465. "--simple boundary\r\n"
  15466. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15467. ": BAD...\r\n"
  15468. "\r\n"
  15469. "value1\r\n"
  15470. "--simple boundary\r\n"
  15471. "Content-Disposition: form-data; name=\"field2\"; "
  15472. "filename=\"example.txt\"\r\n"
  15473. "\r\n"
  15474. "value2\r\n"
  15475. "--simple boundary--\r\n"
  15476. "This is the epilogue. It is also to be ignored.\r\n";
  15477. std::string content_type =
  15478. R"(multipart/form-data; boundary="simple boundary")";
  15479. Client cli(HOST, PORT);
  15480. auto res = cli.Post("/post", body, content_type.c_str());
  15481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15482. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15483. }
  15484. TEST(MultipartFormDataTest, WithPreamble) {
  15485. Server svr;
  15486. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15487. res.set_content("ok", "text/plain");
  15488. });
  15489. thread t = thread([&] { svr.listen(HOST, PORT); });
  15490. auto se = detail::scope_exit([&] {
  15491. svr.stop();
  15492. t.join();
  15493. ASSERT_FALSE(svr.is_running());
  15494. });
  15495. svr.wait_until_ready();
  15496. const std::string body =
  15497. "This is the preamble. It is to be ignored, though it\r\n"
  15498. "is a handy place for composition agents to include an\r\n"
  15499. "explanatory note to non-MIME conformant readers.\r\n"
  15500. "\r\n"
  15501. "\r\n"
  15502. "--simple boundary\r\n"
  15503. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15504. "\r\n"
  15505. "value1\r\n"
  15506. "--simple boundary\r\n"
  15507. "Content-Disposition: form-data; name=\"field2\"; "
  15508. "filename=\"example.txt\"\r\n"
  15509. "\r\n"
  15510. "value2\r\n"
  15511. "--simple boundary--\r\n"
  15512. "This is the epilogue. It is also to be ignored.\r\n";
  15513. std::string content_type =
  15514. R"(multipart/form-data; boundary="simple boundary")";
  15515. Client cli(HOST, PORT);
  15516. auto res = cli.Post("/post", body, content_type.c_str());
  15517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15518. EXPECT_EQ(StatusCode::OK_200, res->status);
  15519. }
  15520. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15522. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15523. const ContentReader &content_reader) {
  15524. if (req.is_multipart_form_data()) {
  15525. std::vector<FormData> items;
  15526. content_reader(
  15527. [&](const FormData &file) {
  15528. items.push_back(file);
  15529. return true;
  15530. },
  15531. [&](const char *data, size_t data_length) {
  15532. items.back().content.append(data, data_length);
  15533. return true;
  15534. });
  15535. EXPECT_TRUE(std::string(items[0].name) == "document");
  15536. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15537. EXPECT_TRUE(items[0].filename == "2MB_data");
  15538. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15539. EXPECT_TRUE(items[1].name == "hello");
  15540. EXPECT_TRUE(items[1].content == "world");
  15541. EXPECT_TRUE(items[1].filename == "");
  15542. EXPECT_TRUE(items[1].content_type == "");
  15543. } else {
  15544. std::string body;
  15545. content_reader([&](const char *data, size_t data_length) {
  15546. body.append(data, data_length);
  15547. return true;
  15548. });
  15549. }
  15550. });
  15551. auto port = svr.bind_to_any_port("localhost");
  15552. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15553. auto se = detail::scope_exit([&] {
  15554. svr.stop();
  15555. t.join();
  15556. ASSERT_FALSE(svr.is_running());
  15557. });
  15558. svr.wait_until_ready();
  15559. {
  15560. std::string data(1024 * 1024 * 2, '.');
  15561. std::stringstream buffer;
  15562. buffer << data;
  15563. SSLClient cli("localhost", port);
  15564. cli.enable_server_certificate_verification(false);
  15565. UploadFormDataItems items{
  15566. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15567. {"hello", "world", "", ""},
  15568. };
  15569. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15571. ASSERT_EQ(StatusCode::OK_200, res->status);
  15572. }
  15573. }
  15574. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15575. std::string data(1024 * 1024 * 2, '&');
  15576. std::stringstream buffer;
  15577. buffer << data;
  15578. Client cli("https://localhost:8080");
  15579. UploadFormDataItems items{
  15580. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15581. {"hello", "world", "", ""},
  15582. };
  15583. for (const char &c : " \t\r\n") {
  15584. auto res =
  15585. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15586. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15587. ASSERT_FALSE(res);
  15588. }
  15589. }
  15590. TEST(MultipartFormDataTest, PutFormData) {
  15591. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15592. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15593. const ContentReader &content_reader) {
  15594. if (req.is_multipart_form_data()) {
  15595. std::vector<FormData> items;
  15596. content_reader(
  15597. [&](const FormData &file) {
  15598. items.push_back(file);
  15599. return true;
  15600. },
  15601. [&](const char *data, size_t data_length) {
  15602. items.back().content.append(data, data_length);
  15603. return true;
  15604. });
  15605. EXPECT_TRUE(std::string(items[0].name) == "document");
  15606. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15607. EXPECT_TRUE(items[0].filename == "2MB_data");
  15608. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15609. EXPECT_TRUE(items[1].name == "hello");
  15610. EXPECT_TRUE(items[1].content == "world");
  15611. EXPECT_TRUE(items[1].filename == "");
  15612. EXPECT_TRUE(items[1].content_type == "");
  15613. } else {
  15614. std::string body;
  15615. content_reader([&](const char *data, size_t data_length) {
  15616. body.append(data, data_length);
  15617. return true;
  15618. });
  15619. }
  15620. });
  15621. auto port = svr.bind_to_any_port("localhost");
  15622. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15623. auto se = detail::scope_exit([&] {
  15624. svr.stop();
  15625. t.join();
  15626. ASSERT_FALSE(svr.is_running());
  15627. });
  15628. svr.wait_until_ready();
  15629. {
  15630. std::string data(1024 * 1024 * 2, '&');
  15631. std::stringstream buffer;
  15632. buffer << data;
  15633. SSLClient cli("localhost", port);
  15634. cli.enable_server_certificate_verification(false);
  15635. UploadFormDataItems items{
  15636. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15637. {"hello", "world", "", ""},
  15638. };
  15639. auto res = cli.Put("/put", items);
  15640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15641. ASSERT_EQ(StatusCode::OK_200, res->status);
  15642. }
  15643. }
  15644. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15645. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15646. svr.Put("/put_customboundary",
  15647. [&](const Request &req, const Response & /*res*/,
  15648. const ContentReader &content_reader) {
  15649. if (req.is_multipart_form_data()) {
  15650. std::vector<FormData> items;
  15651. content_reader(
  15652. [&](const FormData &file) {
  15653. items.push_back(file);
  15654. return true;
  15655. },
  15656. [&](const char *data, size_t data_length) {
  15657. items.back().content.append(data, data_length);
  15658. return true;
  15659. });
  15660. EXPECT_TRUE(std::string(items[0].name) == "document");
  15661. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15662. EXPECT_TRUE(items[0].filename == "2MB_data");
  15663. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15664. EXPECT_TRUE(items[1].name == "hello");
  15665. EXPECT_TRUE(items[1].content == "world");
  15666. EXPECT_TRUE(items[1].filename == "");
  15667. EXPECT_TRUE(items[1].content_type == "");
  15668. } else {
  15669. std::string body;
  15670. content_reader([&](const char *data, size_t data_length) {
  15671. body.append(data, data_length);
  15672. return true;
  15673. });
  15674. }
  15675. });
  15676. auto port = svr.bind_to_any_port("localhost");
  15677. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15678. auto se = detail::scope_exit([&] {
  15679. svr.stop();
  15680. t.join();
  15681. ASSERT_FALSE(svr.is_running());
  15682. });
  15683. svr.wait_until_ready();
  15684. {
  15685. std::string data(1024 * 1024 * 2, '&');
  15686. std::stringstream buffer;
  15687. buffer << data;
  15688. SSLClient cli("localhost", port);
  15689. cli.enable_server_certificate_verification(false);
  15690. UploadFormDataItems items{
  15691. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15692. {"hello", "world", "", ""},
  15693. };
  15694. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15696. ASSERT_EQ(StatusCode::OK_200, res->status);
  15697. }
  15698. }
  15699. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15700. std::string data(1024 * 1024 * 2, '&');
  15701. std::stringstream buffer;
  15702. buffer << data;
  15703. Client cli("https://localhost:8080");
  15704. cli.enable_server_certificate_verification(false);
  15705. UploadFormDataItems items{
  15706. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15707. {"hello", "world", "", ""},
  15708. };
  15709. for (const char &c : " \t\r\n") {
  15710. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15711. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15712. ASSERT_FALSE(res);
  15713. }
  15714. }
  15715. TEST(MultipartFormDataTest, AlternateFilename) {
  15716. auto handled = false;
  15717. Server svr;
  15718. svr.Post("/test", [&](const Request &req, Response &res) {
  15719. ASSERT_EQ(2u, req.form.files.size());
  15720. ASSERT_EQ(1u, req.form.fields.size());
  15721. // Test files
  15722. const auto &file1 = req.form.get_file("file1");
  15723. ASSERT_EQ("file1", file1.name);
  15724. ASSERT_EQ("A.txt", file1.filename);
  15725. ASSERT_EQ("text/plain", file1.content_type);
  15726. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15727. const auto &file2 = req.form.get_file("file2");
  15728. ASSERT_EQ("file2", file2.name);
  15729. ASSERT_EQ("a.html", file2.filename);
  15730. ASSERT_EQ("text/html", file2.content_type);
  15731. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15732. file2.content);
  15733. // Test text field
  15734. const auto &text = req.form.get_field("text");
  15735. ASSERT_EQ("text default", text);
  15736. res.set_content("ok", "text/plain");
  15737. handled = true;
  15738. });
  15739. thread t = thread([&] { svr.listen(HOST, PORT); });
  15740. auto se = detail::scope_exit([&] {
  15741. svr.stop();
  15742. t.join();
  15743. ASSERT_FALSE(svr.is_running());
  15744. ASSERT_TRUE(handled);
  15745. });
  15746. svr.wait_until_ready();
  15747. auto req = "POST /test HTTP/1.1\r\n"
  15748. "Host: localhost\r\n"
  15749. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15750. "Content-Length: 399\r\n"
  15751. "\r\n"
  15752. "----------\r\n"
  15753. "Content-Disposition: form-data; name=\"text\"\r\n"
  15754. "\r\n"
  15755. "text default\r\n"
  15756. "----------\r\n"
  15757. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15758. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15759. "Content-Type: text/plain\r\n"
  15760. "\r\n"
  15761. "Content of a.txt.\r\n"
  15762. "\r\n"
  15763. "----------\r\n"
  15764. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15765. "\"a.html\"\r\n"
  15766. "Content-Type: text/html\r\n"
  15767. "\r\n"
  15768. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15769. "\r\n"
  15770. "------------\r\n";
  15771. ASSERT_TRUE(send_request(1, req));
  15772. }
  15773. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15774. auto handled = false;
  15775. Server svr;
  15776. svr.Post("/test", [&](const Request &req, Response &res) {
  15777. // Case-insensitive "utf-8''" prefix with a long value
  15778. const auto &file = req.form.get_file("file1");
  15779. ASSERT_EQ("file1", file.name);
  15780. // 8000 chars exercises both the Content-Disposition parser and the
  15781. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15782. // Prior to the fix, std::regex_match on this header would cause O(N)
  15783. // stack recursion in libstdc++, leading to SIGSEGV.
  15784. std::string expected_filename(8000, 'A');
  15785. ASSERT_EQ(expected_filename, file.filename);
  15786. res.set_content("ok", "text/plain");
  15787. handled = true;
  15788. });
  15789. thread t = thread([&] { svr.listen(HOST, PORT); });
  15790. auto se = detail::scope_exit([&] {
  15791. svr.stop();
  15792. t.join();
  15793. ASSERT_FALSE(svr.is_running());
  15794. ASSERT_TRUE(handled);
  15795. });
  15796. svr.wait_until_ready();
  15797. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15798. // Regression test for GHSA-qq6v-r583-3h69
  15799. std::string long_filename(8000, 'A');
  15800. std::string body = "----------\r\n"
  15801. "Content-Disposition: form-data; name=\"file1\"; "
  15802. "filename*=\"Utf-8''" +
  15803. long_filename +
  15804. "\"\r\n"
  15805. "\r\n"
  15806. "hello\r\n"
  15807. "------------\r\n";
  15808. auto req = "POST /test HTTP/1.1\r\n"
  15809. "Host: localhost\r\n"
  15810. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15811. "Content-Length: " +
  15812. std::to_string(body.size()) + "\r\n\r\n" + body;
  15813. ASSERT_TRUE(send_request(1, req));
  15814. }
  15815. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15816. auto handled = false;
  15817. Server svr;
  15818. svr.Post("/test", [&](const Request &req, Response &) {
  15819. ASSERT_EQ(2u, req.form.fields.size());
  15820. const auto &text1 = req.form.get_field("text1");
  15821. ASSERT_EQ("text1", text1);
  15822. const auto &text2 = req.form.get_field("text2");
  15823. ASSERT_EQ("text2", text2);
  15824. handled = true;
  15825. });
  15826. thread t = thread([&] { svr.listen(HOST, PORT); });
  15827. auto se = detail::scope_exit([&] {
  15828. svr.stop();
  15829. t.join();
  15830. ASSERT_FALSE(svr.is_running());
  15831. ASSERT_TRUE(handled);
  15832. });
  15833. svr.wait_until_ready();
  15834. auto req = "POST /test HTTP/1.1\r\n"
  15835. "Host: localhost\r\n"
  15836. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15837. "Content-Length: 146\r\n"
  15838. "\r\n----------\r\n"
  15839. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15840. "\r\n"
  15841. "text1"
  15842. "\r\n----------\r\n"
  15843. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15844. "\r\n"
  15845. "text2"
  15846. "\r\n------------";
  15847. std::string response;
  15848. ASSERT_TRUE(send_request(1, req, &response));
  15849. ASSERT_EQ("200", response.substr(9, 3));
  15850. }
  15851. TEST(MultipartFormDataTest, ContentLength) {
  15852. auto handled = false;
  15853. Server svr;
  15854. svr.Post("/test", [&](const Request &req, Response &) {
  15855. ASSERT_EQ(2u, req.form.fields.size());
  15856. const auto &text1 = req.form.get_field("text1");
  15857. ASSERT_EQ("text1", text1);
  15858. const auto &text2 = req.form.get_field("text2");
  15859. ASSERT_EQ("text2", text2);
  15860. handled = true;
  15861. });
  15862. thread t = thread([&] { svr.listen(HOST, PORT); });
  15863. auto se = detail::scope_exit([&] {
  15864. svr.stop();
  15865. t.join();
  15866. ASSERT_FALSE(svr.is_running());
  15867. ASSERT_TRUE(handled);
  15868. });
  15869. svr.wait_until_ready();
  15870. auto req = "POST /test HTTP/1.1\r\n"
  15871. "Host: localhost\r\n"
  15872. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15873. "Content-Length: 167\r\n"
  15874. "\r\n----------\r\n"
  15875. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15876. "Content-Length: 5\r\n"
  15877. "\r\n"
  15878. "text1"
  15879. "\r\n----------\r\n"
  15880. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15881. "\r\n"
  15882. "text2"
  15883. "\r\n------------\r\n";
  15884. std::string response;
  15885. ASSERT_TRUE(send_request(1, req, &response));
  15886. ASSERT_EQ("200", response.substr(9, 3));
  15887. }
  15888. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15889. auto handled = false;
  15890. Server svr;
  15891. svr.Post("/test", [&](const Request &req, Response &) {
  15892. ASSERT_EQ(2u, req.form.fields.size());
  15893. const auto &text1 = req.form.get_field("text1");
  15894. ASSERT_EQ("text1", text1);
  15895. // TODO: Add header access for text fields if needed
  15896. const auto &text2 = req.form.get_field("text2");
  15897. ASSERT_EQ("text2", text2);
  15898. // TODO: Header access for text fields needs to be implemented
  15899. // auto &headers = it->second.headers;
  15900. // ASSERT_EQ(3U, headers.size());
  15901. // auto custom_header = headers.find("x-whatever");
  15902. // ASSERT_TRUE(custom_header != headers.end());
  15903. // ASSERT_NE("customvalue", custom_header->second);
  15904. // ASSERT_EQ("CustomValue", custom_header->second);
  15905. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15906. handled = true;
  15907. });
  15908. thread t = thread([&] { svr.listen(HOST, PORT); });
  15909. auto se = detail::scope_exit([&] {
  15910. svr.stop();
  15911. t.join();
  15912. ASSERT_FALSE(svr.is_running());
  15913. ASSERT_TRUE(handled);
  15914. });
  15915. svr.wait_until_ready();
  15916. auto req = "POST /test HTTP/1.1\r\n"
  15917. "Host: localhost\r\n"
  15918. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15919. "Content-Length: 232\r\n"
  15920. "\r\n----------\r\n"
  15921. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15922. "Content-Length: 5\r\n"
  15923. "X-Test: 1\r\n"
  15924. "\r\n"
  15925. "text1"
  15926. "\r\n----------\r\n"
  15927. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15928. "Content-Type: text/plain\r\n"
  15929. "X-Whatever: CustomValue\r\n"
  15930. "\r\n"
  15931. "text2"
  15932. "\r\n------------\r\n"
  15933. "That should be disregarded. Not even read";
  15934. std::string response;
  15935. ASSERT_TRUE(send_request(1, req, &response));
  15936. ASSERT_EQ("200", response.substr(9, 3));
  15937. }
  15938. TEST(MultipartFormDataTest, LargeHeader) {
  15939. auto handled = false;
  15940. Server svr;
  15941. svr.Post("/test", [&](const Request &req, Response &) {
  15942. ASSERT_EQ(1u, req.form.fields.size());
  15943. const auto &text = req.form.get_field("name1");
  15944. ASSERT_EQ("text1", text);
  15945. handled = true;
  15946. });
  15947. thread t = thread([&] { svr.listen(HOST, PORT); });
  15948. auto se = detail::scope_exit([&] {
  15949. svr.stop();
  15950. t.join();
  15951. ASSERT_FALSE(svr.is_running());
  15952. ASSERT_TRUE(handled);
  15953. });
  15954. svr.wait_until_ready();
  15955. auto boundary = std::string("cpp-httplib-multipart-data");
  15956. std::string content = "--" + boundary +
  15957. "\r\n"
  15958. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15959. "\r\n"
  15960. "text1\r\n"
  15961. "--" +
  15962. boundary + "--\r\n";
  15963. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15964. "Host: localhost\r\n"
  15965. "Content-Type: multipart/form-data;boundary=" +
  15966. boundary +
  15967. "\r\n"
  15968. "Content-Length: " +
  15969. std::to_string(content.size()) +
  15970. "\r\n"
  15971. "Dummy-Header: ";
  15972. std::string header_suffix = "\r\n"
  15973. "\r\n";
  15974. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15975. size_t header_dummy_size =
  15976. read_buff_size -
  15977. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15978. auto header_dummy = std::string(header_dummy_size, '@');
  15979. auto req = header_prefix + header_dummy + header_suffix + content;
  15980. std::string response;
  15981. ASSERT_TRUE(send_request(1, req, &response));
  15982. ASSERT_EQ("200", response.substr(9, 3));
  15983. }
  15984. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15985. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15986. // (not chunked Transfer-Encoding) after the streaming refactor.
  15987. auto handled = false;
  15988. Server svr;
  15989. svr.Post("/upload", [&](const Request &req, Response &res) {
  15990. auto cl_it = req.headers.find("Content-Length");
  15991. EXPECT_TRUE(cl_it != req.headers.end());
  15992. auto te_it = req.headers.find("Transfer-Encoding");
  15993. EXPECT_TRUE(te_it == req.headers.end());
  15994. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15995. res.set_content("ok", "text/plain");
  15996. handled = true;
  15997. });
  15998. auto port = svr.bind_to_any_port(HOST);
  15999. auto t = thread([&] { svr.listen_after_bind(); });
  16000. auto se = detail::scope_exit([&] {
  16001. svr.stop();
  16002. t.join();
  16003. ASSERT_FALSE(svr.is_running());
  16004. ASSERT_TRUE(handled);
  16005. });
  16006. svr.wait_until_ready();
  16007. UploadFormDataItems items = {
  16008. {"field1", "hello", "", "text/plain"},
  16009. {"file1", "world", "test.txt", "application/octet-stream"},
  16010. };
  16011. Client cli(HOST, port);
  16012. auto res = cli.Post("/upload", {}, items);
  16013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16014. EXPECT_EQ(StatusCode::OK_200, res->status);
  16015. }
  16016. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16017. // Verify that make_multipart_content_provider coalesces many small segments
  16018. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16019. constexpr size_t kItemCount = 1000;
  16020. UploadFormDataItems items;
  16021. items.reserve(kItemCount);
  16022. for (size_t i = 0; i < kItemCount; i++) {
  16023. items.push_back(
  16024. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16025. }
  16026. const std::string boundary = "----test-boundary";
  16027. auto content_length = detail::get_multipart_content_length(items, boundary);
  16028. auto provider = detail::make_multipart_content_provider(items, boundary);
  16029. // Drive the provider the same way write_content_with_progress does
  16030. size_t write_count = 0;
  16031. size_t total_bytes = 0;
  16032. DataSink sink;
  16033. size_t offset = 0;
  16034. sink.write = [&](const char *d, size_t l) -> bool {
  16035. (void)d;
  16036. write_count++;
  16037. total_bytes += l;
  16038. offset += l;
  16039. return true;
  16040. };
  16041. sink.is_writable = []() -> bool { return true; };
  16042. while (offset < content_length) {
  16043. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16044. }
  16045. EXPECT_EQ(content_length, total_bytes);
  16046. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16047. // With buffering into 64KB blocks, write_count should be much smaller.
  16048. auto segment_count = 3 * kItemCount + 1;
  16049. EXPECT_LT(write_count, segment_count / 10);
  16050. }
  16051. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16052. // Integration test: send many UploadFormDataItems and verify the server
  16053. // receives all of them correctly (#2410).
  16054. constexpr size_t kItemCount = 500;
  16055. auto handled = false;
  16056. Server svr;
  16057. svr.Post("/upload", [&](const Request &req, Response &res) {
  16058. EXPECT_EQ(kItemCount, req.form.fields.size());
  16059. for (size_t i = 0; i < kItemCount; i++) {
  16060. auto key = "field" + std::to_string(i);
  16061. auto val = "value" + std::to_string(i);
  16062. auto it = req.form.fields.find(key);
  16063. if (it != req.form.fields.end()) {
  16064. EXPECT_EQ(val, it->second.content);
  16065. } else {
  16066. ADD_FAILURE() << "Missing field: " << key;
  16067. }
  16068. }
  16069. res.set_content("ok", "text/plain");
  16070. handled = true;
  16071. });
  16072. auto port = svr.bind_to_any_port(HOST);
  16073. auto t = thread([&] { svr.listen_after_bind(); });
  16074. auto se = detail::scope_exit([&] {
  16075. svr.stop();
  16076. t.join();
  16077. ASSERT_FALSE(svr.is_running());
  16078. ASSERT_TRUE(handled);
  16079. });
  16080. svr.wait_until_ready();
  16081. UploadFormDataItems items;
  16082. items.reserve(kItemCount);
  16083. for (size_t i = 0; i < kItemCount; i++) {
  16084. items.push_back(
  16085. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16086. }
  16087. Client cli(HOST, port);
  16088. auto res = cli.Post("/upload", items);
  16089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16090. EXPECT_EQ(StatusCode::OK_200, res->status);
  16091. }
  16092. TEST(MultipartFormDataTest, MakeFileProvider) {
  16093. // Verify make_file_provider sends a file's contents correctly.
  16094. const std::string file_content(4096, 'Z');
  16095. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16096. {
  16097. std::ofstream ofs(tmp_path, std::ios::binary);
  16098. ofs.write(file_content.data(),
  16099. static_cast<std::streamsize>(file_content.size()));
  16100. }
  16101. auto handled = false;
  16102. Server svr;
  16103. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16104. const ContentReader &content_reader) {
  16105. ASSERT_TRUE(req.is_multipart_form_data());
  16106. std::vector<FormData> items;
  16107. content_reader(
  16108. [&](const FormData &file) {
  16109. items.push_back(file);
  16110. return true;
  16111. },
  16112. [&](const char *data, size_t data_length) {
  16113. items.back().content.append(data, data_length);
  16114. return true;
  16115. });
  16116. ASSERT_EQ(1u, items.size());
  16117. EXPECT_EQ("myfile", items[0].name);
  16118. EXPECT_EQ("data.bin", items[0].filename);
  16119. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16120. EXPECT_EQ(file_content, items[0].content);
  16121. handled = true;
  16122. });
  16123. auto port = svr.bind_to_any_port(HOST);
  16124. auto t = thread([&] { svr.listen_after_bind(); });
  16125. auto se = detail::scope_exit([&] {
  16126. svr.stop();
  16127. t.join();
  16128. ASSERT_FALSE(svr.is_running());
  16129. ASSERT_TRUE(handled);
  16130. std::remove(tmp_path.c_str());
  16131. });
  16132. svr.wait_until_ready();
  16133. FormDataProviderItems providers;
  16134. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16135. "application/octet-stream"));
  16136. Client cli(HOST, port);
  16137. auto res = cli.Post("/upload", {}, {}, providers);
  16138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16139. EXPECT_EQ(StatusCode::OK_200, res->status);
  16140. }
  16141. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16142. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16143. // (100) headers is rejected with a 400 Bad Request response.
  16144. Server svr;
  16145. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16146. res.set_content("ok", "text/plain");
  16147. });
  16148. thread t = thread([&] { svr.listen(HOST, PORT); });
  16149. auto se = detail::scope_exit([&] {
  16150. svr.stop();
  16151. t.join();
  16152. ASSERT_FALSE(svr.is_running());
  16153. });
  16154. svr.wait_until_ready();
  16155. // Build a multipart part with 101 custom headers (exceeding
  16156. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16157. std::stringstream body;
  16158. body << "--simpleboundary\r\n"
  16159. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16160. for (int i = 0; i < 101; i++) {
  16161. body << "X-Custom-Header-" << i << ": value\r\n";
  16162. }
  16163. body << "\r\n"
  16164. << "value1\r\n"
  16165. << "--simpleboundary--\r\n";
  16166. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16167. Client cli(HOST, PORT);
  16168. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16170. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16171. }
  16172. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16173. // A body that never contains the declared boundary must not be accumulated
  16174. // while the parser waits for it. Buffering it would also make every read
  16175. // rescan everything seen so far, which is quadratic in the body size.
  16176. Server svr;
  16177. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16178. res.set_content("ok", "text/plain");
  16179. });
  16180. auto port = svr.bind_to_any_port(HOST);
  16181. thread t = thread([&] { svr.listen_after_bind(); });
  16182. auto se = detail::scope_exit([&] {
  16183. svr.stop();
  16184. t.join();
  16185. ASSERT_FALSE(svr.is_running());
  16186. });
  16187. svr.wait_until_ready();
  16188. Client cli(HOST, port);
  16189. cli.set_read_timeout(60, 0);
  16190. cli.set_write_timeout(60, 0);
  16191. // '-' is the worst case: it matches the first character of the boundary, so
  16192. // every position has to be checked against it.
  16193. auto post_dashes = [&](size_t size) {
  16194. const std::string body(size, '-');
  16195. auto start = std::chrono::steady_clock::now();
  16196. auto res =
  16197. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16198. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16199. std::chrono::steady_clock::now() - start)
  16200. .count();
  16201. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16202. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16203. return ms;
  16204. };
  16205. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16206. // Windows.
  16207. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16208. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16209. // Comparing the two sizes rather than checking an absolute duration keeps
  16210. // this meaningful across build types and CI load, both of which move the
  16211. // absolute numbers by more than an order of magnitude. Four times the bytes
  16212. // costs about four times the time when parsing is linear, and about sixteen
  16213. // times when the body is buffered and rescanned.
  16214. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16215. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16216. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16217. << "ms, which suggests the body is being buffered and rescanned";
  16218. }
  16219. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16220. // A boundary can only be followed by CRLF or by "--", so anything else is
  16221. // malformed no matter what comes next. The parser must say so right away
  16222. // instead of buffering the rest of the declared body.
  16223. Server svr;
  16224. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16225. res.set_content("ok", "text/plain");
  16226. });
  16227. auto port = svr.bind_to_any_port(HOST);
  16228. thread t = thread([&] { svr.listen_after_bind(); });
  16229. auto se = detail::scope_exit([&] {
  16230. svr.stop();
  16231. t.join();
  16232. ASSERT_FALSE(svr.is_running());
  16233. });
  16234. svr.wait_until_ready();
  16235. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16236. // buffers instead of failing would still be waiting for the remaining bytes.
  16237. const std::string body = "--zzzz\r\n"
  16238. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16239. "\r\n"
  16240. "text1"
  16241. "\r\n--zzzzXX";
  16242. const std::string req = "POST /post HTTP/1.1\r\n"
  16243. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16244. "Content-Length: 1048576\r\n"
  16245. "\r\n" +
  16246. body;
  16247. std::string response;
  16248. ASSERT_TRUE(send_request(3, req, &response, port));
  16249. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16250. EXPECT_EQ("400", response.substr(9, 3));
  16251. }
  16252. // Posts a multipart body split into two writes, so that the server sees the
  16253. // split at whatever offset the caller chose, and expects the single "text1"
  16254. // field to come through.
  16255. static void expect_split_multipart_ok(const std::string &body1,
  16256. const std::string &body2) {
  16257. auto handled = false;
  16258. Server svr;
  16259. svr.Post("/post", [&](const Request &req, Response &) {
  16260. EXPECT_EQ(1u, req.form.fields.size());
  16261. EXPECT_EQ("text1", req.form.get_field("text1"));
  16262. handled = true;
  16263. });
  16264. auto port = svr.bind_to_any_port(HOST);
  16265. thread t = thread([&] { svr.listen_after_bind(); });
  16266. auto se = detail::scope_exit([&] {
  16267. svr.stop();
  16268. t.join();
  16269. ASSERT_FALSE(svr.is_running());
  16270. ASSERT_TRUE(handled);
  16271. });
  16272. svr.wait_until_ready();
  16273. // "Connection: close" makes the server close once it has answered, so the
  16274. // response drain ends immediately instead of idling until the read timeout.
  16275. const std::string head =
  16276. "POST /post HTTP/1.1\r\n"
  16277. "Host: localhost\r\n"
  16278. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16279. "Connection: close\r\n"
  16280. "Content-Length: " +
  16281. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16282. std::string response;
  16283. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16284. ASSERT_GE(response.size(), 12u) << "no response";
  16285. EXPECT_EQ("200", response.substr(9, 3));
  16286. }
  16287. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16288. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16289. // ignored, including when it does not arrive in the same read as the
  16290. // close-delimiter itself.
  16291. expect_split_multipart_ok("--zzzz\r\n"
  16292. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16293. "\r\n"
  16294. "text1"
  16295. "\r\n--zzzz--",
  16296. "\r\nthis epilogue must be ignored\r\n");
  16297. }
  16298. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16299. // The initial boundary may be preceded by a preamble of any length and may
  16300. // straddle a read boundary. Discarding data while waiting for it must not
  16301. // throw away a partial boundary sitting at the end of the buffer.
  16302. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16303. "zz\r\n"
  16304. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16305. "\r\n"
  16306. "text1"
  16307. "\r\n--zzzz--\r\n");
  16308. }
  16309. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16310. // The received boundary was only checked for being non-empty, so it could be
  16311. // as long as a header is allowed to be. The parser scans the body for
  16312. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16313. // costs a nearly full comparison at nearly every position, making the
  16314. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16315. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16316. Server svr;
  16317. svr.Post("/post", [](const Request &req, Response &res) {
  16318. EXPECT_EQ(1u, req.form.fields.size());
  16319. EXPECT_EQ("text1", req.form.get_field("text1"));
  16320. res.set_content("ok", "text/plain");
  16321. });
  16322. auto port = svr.bind_to_any_port(HOST);
  16323. thread t = thread([&] { svr.listen_after_bind(); });
  16324. auto se = detail::scope_exit([&] {
  16325. svr.stop();
  16326. t.join();
  16327. ASSERT_FALSE(svr.is_running());
  16328. });
  16329. svr.wait_until_ready();
  16330. Client cli(HOST, port);
  16331. auto post_with_boundary_of_length = [&](size_t len) {
  16332. const std::string boundary(len, 'a');
  16333. const std::string body =
  16334. "--" + boundary +
  16335. "\r\n"
  16336. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16337. "\r\n"
  16338. "text1"
  16339. "\r\n--" +
  16340. boundary + "--\r\n";
  16341. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16342. };
  16343. auto res = post_with_boundary_of_length(70);
  16344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16345. EXPECT_EQ(StatusCode::OK_200, res->status);
  16346. res = post_with_boundary_of_length(71);
  16347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16348. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16349. }
  16350. TEST(MakeFileBodyTest, Basic) {
  16351. const std::string file_content(4096, 'Z');
  16352. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16353. {
  16354. std::ofstream ofs(tmp_path, std::ios::binary);
  16355. ofs.write(file_content.data(),
  16356. static_cast<std::streamsize>(file_content.size()));
  16357. }
  16358. auto handled = false;
  16359. Server svr;
  16360. svr.Post("/upload", [&](const Request &req, Response &res) {
  16361. EXPECT_EQ(file_content, req.body);
  16362. handled = true;
  16363. res.status = StatusCode::OK_200;
  16364. });
  16365. auto port = svr.bind_to_any_port(HOST);
  16366. auto t = thread([&] { svr.listen_after_bind(); });
  16367. auto se = detail::scope_exit([&] {
  16368. svr.stop();
  16369. t.join();
  16370. ASSERT_FALSE(svr.is_running());
  16371. ASSERT_TRUE(handled);
  16372. std::remove(tmp_path.c_str());
  16373. });
  16374. svr.wait_until_ready();
  16375. auto fb = make_file_body(tmp_path);
  16376. ASSERT_GT(fb.first, 0u);
  16377. Client cli(HOST, port);
  16378. auto res =
  16379. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16381. EXPECT_EQ(StatusCode::OK_200, res->status);
  16382. }
  16383. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16384. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16385. {
  16386. std::ofstream ofs(path, std::ios::binary);
  16387. const std::string content(100, 'A');
  16388. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16389. }
  16390. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16391. auto body = make_file_body(path);
  16392. ASSERT_EQ(100u, body.first);
  16393. ASSERT_TRUE(static_cast<bool>(body.second));
  16394. // Rewritten shorter after its length was measured - and, on a server, after
  16395. // that length has already gone out as Content-Length.
  16396. {
  16397. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16398. const std::string content(10, 'A');
  16399. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16400. }
  16401. std::string written;
  16402. DataSink sink;
  16403. sink.write = [&](const char *d, size_t l) {
  16404. written.append(d, l);
  16405. return true;
  16406. };
  16407. // The provider has to report failure. write_content_with_progress() advances
  16408. // its offset only by what was written, so a provider that returns true
  16409. // without completing the length it promised is called again straight away,
  16410. // and again.
  16411. EXPECT_FALSE(body.second(0, body.first, sink));
  16412. EXPECT_EQ(std::string(10, 'A'), written);
  16413. }
  16414. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16415. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16416. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16417. {
  16418. std::ofstream ofs(path, std::ios::binary);
  16419. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16420. }
  16421. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16422. auto body = make_file_body(path);
  16423. ASSERT_EQ(content.size(), body.first);
  16424. ASSERT_TRUE(static_cast<bool>(body.second));
  16425. std::string written;
  16426. DataSink sink;
  16427. sink.write = [&](const char *d, size_t l) {
  16428. written.append(d, l);
  16429. return true;
  16430. };
  16431. EXPECT_TRUE(body.second(0, body.first, sink));
  16432. EXPECT_EQ(content, written);
  16433. }
  16434. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16435. static constexpr unsigned int number_of_tasks{1000000};
  16436. std::atomic_uint count{0};
  16437. std::unique_ptr<TaskQueue> task_queue{
  16438. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16439. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16440. auto queued = task_queue->enqueue(
  16441. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16442. EXPECT_TRUE(queued);
  16443. }
  16444. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16445. task_queue->shutdown();
  16446. #else
  16447. EXPECT_NO_THROW(task_queue->shutdown());
  16448. #endif
  16449. EXPECT_EQ(number_of_tasks, count.load());
  16450. }
  16451. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16452. static constexpr unsigned int number_of_tasks{1000000};
  16453. static constexpr unsigned int qlimit{2};
  16454. unsigned int queued_count{0};
  16455. std::atomic_uint count{0};
  16456. std::unique_ptr<TaskQueue> task_queue{
  16457. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16458. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16459. if (task_queue->enqueue(
  16460. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16461. queued_count++;
  16462. }
  16463. }
  16464. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16465. task_queue->shutdown();
  16466. #else
  16467. EXPECT_NO_THROW(task_queue->shutdown());
  16468. #endif
  16469. EXPECT_EQ(queued_count, count.load());
  16470. EXPECT_TRUE(queued_count <= number_of_tasks);
  16471. EXPECT_TRUE(queued_count >= qlimit);
  16472. }
  16473. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16474. // Use a short idle timeout so a dynamic thread spawns, times out and
  16475. // exits during the test, and the pool keeps working afterwards.
  16476. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16477. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16478. /*idle_timeout_sec=*/1}};
  16479. std::atomic_uint count{0};
  16480. std::condition_variable cv;
  16481. std::mutex mtx;
  16482. bool release = false;
  16483. // Block the base thread so the second task spawns a dynamic thread.
  16484. EXPECT_TRUE(task_queue->enqueue([&] {
  16485. std::unique_lock<std::mutex> lock(mtx);
  16486. while (!release) {
  16487. cv.wait(lock);
  16488. }
  16489. count++;
  16490. }));
  16491. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16492. // Let the dynamic thread finish its task and exceed the idle timeout.
  16493. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16494. {
  16495. std::unique_lock<std::mutex> lock(mtx);
  16496. release = true;
  16497. }
  16498. cv.notify_all();
  16499. // The pool must still accept and run tasks after the dynamic thread exited.
  16500. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16501. task_queue->shutdown();
  16502. EXPECT_EQ(3u, count.load());
  16503. }
  16504. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16505. static constexpr size_t number_of_tasks{32};
  16506. std::unique_ptr<TaskQueue> task_queue{
  16507. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16508. // Let the base threads go idle so the burst below finds them waiting.
  16509. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16510. std::mutex mtx;
  16511. std::condition_variable cv;
  16512. size_t running = 0;
  16513. bool release = false;
  16514. for (size_t i = 0; i < number_of_tasks; i++) {
  16515. EXPECT_TRUE(task_queue->enqueue([&] {
  16516. std::unique_lock<std::mutex> lock(mtx);
  16517. running++;
  16518. cv.notify_all();
  16519. cv.wait(lock, [&] { return release; });
  16520. }));
  16521. }
  16522. {
  16523. std::unique_lock<std::mutex> lock(mtx);
  16524. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16525. [&] { return running == number_of_tasks; }));
  16526. release = true;
  16527. }
  16528. cv.notify_all();
  16529. task_queue->shutdown();
  16530. }
  16531. TEST(TaskQueueTest, MaxQueuedRequests) {
  16532. static constexpr unsigned int qlimit{3};
  16533. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16534. std::condition_variable sem_cv;
  16535. std::mutex sem_mtx;
  16536. int credits = 0;
  16537. bool queued;
  16538. /* Fill up the queue with tasks that will block until we give them credits to
  16539. * complete. */
  16540. for (unsigned int n = 0; n <= qlimit;) {
  16541. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16542. std::unique_lock<std::mutex> lock(sem_mtx);
  16543. while (credits <= 0) {
  16544. sem_cv.wait(lock);
  16545. }
  16546. /* Consume the credit and signal the test code if they are all gone. */
  16547. if (--credits == 0) { sem_cv.notify_one(); }
  16548. });
  16549. if (n < qlimit) {
  16550. /* The first qlimit enqueues must succeed. */
  16551. EXPECT_TRUE(queued);
  16552. } else {
  16553. /* The last one will succeed only when the worker thread
  16554. * starts and dequeues the first blocking task. Although
  16555. * not necessary for the correctness of this test, we sleep for
  16556. * a short while to avoid busy waiting. */
  16557. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16558. }
  16559. if (queued) { n++; }
  16560. }
  16561. /* Further enqueues must fail since the queue is full. */
  16562. for (auto i = 0; i < 4; i++) {
  16563. queued = task_queue->enqueue([] {});
  16564. EXPECT_FALSE(queued);
  16565. }
  16566. /* Give the credits to allow the previous tasks to complete. */
  16567. {
  16568. std::unique_lock<std::mutex> lock(sem_mtx);
  16569. credits += qlimit + 1;
  16570. }
  16571. sem_cv.notify_all();
  16572. /* Wait for all the credits to be consumed. */
  16573. {
  16574. std::unique_lock<std::mutex> lock(sem_mtx);
  16575. while (credits > 0) {
  16576. sem_cv.wait(lock);
  16577. }
  16578. }
  16579. /* Check that we are able again to enqueue at least qlimit tasks. */
  16580. for (unsigned int i = 0; i < qlimit; i++) {
  16581. queued = task_queue->enqueue([] {});
  16582. EXPECT_TRUE(queued);
  16583. }
  16584. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16585. task_queue->shutdown();
  16586. #else
  16587. EXPECT_NO_THROW(task_queue->shutdown());
  16588. #endif
  16589. }
  16590. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16591. Server svr;
  16592. std::string method;
  16593. std::string body;
  16594. auto has_content_length = false;
  16595. auto has_transfer_encoding = false;
  16596. std::atomic<int> bad_requests{0};
  16597. // Leftover body bytes get parsed as a malformed request and answered with
  16598. // 400
  16599. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16600. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16601. });
  16602. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16603. res.set_redirect("/down", StatusCode::SeeOther_303);
  16604. });
  16605. svr.Get("/down", [&](const Request &req, Response &res) {
  16606. method = req.method;
  16607. body = req.body;
  16608. has_content_length = req.has_header("Content-Length");
  16609. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16610. res.set_content("ok", "text/plain");
  16611. });
  16612. auto port = svr.bind_to_any_port(HOST);
  16613. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16614. auto se = detail::scope_exit([&] {
  16615. svr.stop();
  16616. thread.join();
  16617. ASSERT_FALSE(svr.is_running());
  16618. });
  16619. svr.wait_until_ready();
  16620. const std::string payload = "SECRET-BODY";
  16621. auto check = [&](Client &cli, const Result &res) {
  16622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16623. EXPECT_EQ(StatusCode::OK_200, res->status);
  16624. EXPECT_EQ("ok", res->body);
  16625. EXPECT_EQ("GET", method);
  16626. EXPECT_TRUE(body.empty());
  16627. EXPECT_FALSE(has_content_length);
  16628. EXPECT_FALSE(has_transfer_encoding);
  16629. // Nothing of the original body may be left on the connection
  16630. auto res2 = cli.Get("/down");
  16631. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16632. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16633. EXPECT_EQ("ok", res2->body);
  16634. EXPECT_EQ(0, bad_requests);
  16635. };
  16636. // With content length
  16637. {
  16638. Client cli(HOST, port);
  16639. cli.set_keep_alive(true);
  16640. cli.set_follow_location(true);
  16641. auto res = cli.Post(
  16642. "/up", payload.size(),
  16643. [&](size_t offset, size_t length, DataSink &sink) {
  16644. return sink.write(payload.data() + offset, length);
  16645. },
  16646. "text/plain");
  16647. check(cli, res);
  16648. }
  16649. // Without content length (chunked)
  16650. {
  16651. Client cli(HOST, port);
  16652. cli.set_keep_alive(true);
  16653. cli.set_follow_location(true);
  16654. auto res = cli.Post(
  16655. "/up",
  16656. [&](size_t /*offset*/, DataSink &sink) {
  16657. sink.write(payload.data(), payload.size());
  16658. sink.done();
  16659. return true;
  16660. },
  16661. "text/plain");
  16662. check(cli, res);
  16663. }
  16664. }
  16665. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16666. Server svr;
  16667. std::string target;
  16668. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16669. // Echo the still-encoded name back in the Location
  16670. const std::string prefix = "/start/";
  16671. res.status = StatusCode::Found_302;
  16672. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16673. });
  16674. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16675. target = req.target;
  16676. res.set_content("ok", "text/plain");
  16677. });
  16678. auto port = svr.bind_to_any_port(HOST);
  16679. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16680. auto se = detail::scope_exit([&] {
  16681. svr.stop();
  16682. thread.join();
  16683. ASSERT_FALSE(svr.is_running());
  16684. });
  16685. svr.wait_until_ready();
  16686. // Decoding the Location path would turn the first four into a path
  16687. // separator, a query delimiter, a fragment delimiter and a different
  16688. // percent-encoded octet. The rest must keep reaching the server as they are.
  16689. const std::vector<std::string> names = {
  16690. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16691. };
  16692. for (auto path_encode : {true, false}) {
  16693. Client cli(HOST, port);
  16694. cli.set_follow_location(true);
  16695. cli.set_path_encode(path_encode);
  16696. for (const auto &name : names) {
  16697. target.clear();
  16698. auto res = cli.Get("/start/" + name);
  16699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16700. EXPECT_EQ(StatusCode::OK_200, res->status);
  16701. EXPECT_EQ("/dest/" + name, target);
  16702. }
  16703. }
  16704. }
  16705. TEST(RedirectTest, NotModifiedIsReturned) {
  16706. Server svr;
  16707. svr.Get("/cached", [](const Request &, Response &res) {
  16708. res.status = StatusCode::NotModified_304;
  16709. });
  16710. auto port = svr.bind_to_any_port(HOST);
  16711. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16712. auto se = detail::scope_exit([&] {
  16713. svr.stop();
  16714. thread.join();
  16715. ASSERT_FALSE(svr.is_running());
  16716. });
  16717. svr.wait_until_ready();
  16718. Client cli(HOST, port);
  16719. cli.set_follow_location(true);
  16720. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  16721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16722. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  16723. }
  16724. TEST(RedirectTest, NoLocationIsReturned) {
  16725. Server svr;
  16726. svr.Get("/no-location", [](const Request &, Response &res) {
  16727. res.status = StatusCode::Found_302;
  16728. res.set_content("no location", "text/plain");
  16729. });
  16730. auto port = svr.bind_to_any_port(HOST);
  16731. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16732. auto se = detail::scope_exit([&] {
  16733. svr.stop();
  16734. thread.join();
  16735. ASSERT_FALSE(svr.is_running());
  16736. });
  16737. svr.wait_until_ready();
  16738. Client cli(HOST, port);
  16739. cli.set_follow_location(true);
  16740. auto res = cli.Get("/no-location");
  16741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16742. EXPECT_EQ(StatusCode::Found_302, res->status);
  16743. EXPECT_EQ("no location", res->body);
  16744. // The callbacks see the body of the response that is returned
  16745. auto handler_called = false;
  16746. auto progress_called = false;
  16747. std::string body;
  16748. auto res2 = cli.Get(
  16749. "/no-location",
  16750. [&](const Response &) {
  16751. handler_called = true;
  16752. return true;
  16753. },
  16754. [&](const char *data, size_t data_length) {
  16755. body.append(data, data_length);
  16756. return true;
  16757. },
  16758. [&](size_t, size_t) {
  16759. progress_called = true;
  16760. return true;
  16761. });
  16762. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16763. EXPECT_EQ(StatusCode::Found_302, res2->status);
  16764. EXPECT_TRUE(handler_called);
  16765. EXPECT_TRUE(progress_called);
  16766. EXPECT_EQ("no location", body);
  16767. }
  16768. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16769. Server svr;
  16770. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16771. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16772. });
  16773. svr.Get("/hello", [](const Request &req, Response &res) {
  16774. res.set_content(req.get_param_value("key"), "text/plain");
  16775. });
  16776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16777. auto se = detail::scope_exit([&] {
  16778. svr.stop();
  16779. thread.join();
  16780. ASSERT_FALSE(svr.is_running());
  16781. });
  16782. svr.wait_until_ready();
  16783. {
  16784. Client cli(HOST, PORT);
  16785. cli.set_follow_location(true);
  16786. auto res = cli.Get("/");
  16787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16788. EXPECT_EQ(StatusCode::OK_200, res->status);
  16789. EXPECT_EQ("val&key2=val2", res->body);
  16790. }
  16791. }
  16792. #endif
  16793. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16794. Server svr;
  16795. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16796. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16797. });
  16798. svr.Get("/hello", [](const Request &req, Response &res) {
  16799. res.set_content(req.get_param_value("key"), "text/plain");
  16800. });
  16801. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16802. auto se = detail::scope_exit([&] {
  16803. svr.stop();
  16804. thread.join();
  16805. ASSERT_FALSE(svr.is_running());
  16806. });
  16807. svr.wait_until_ready();
  16808. {
  16809. Client cli(HOST, PORT);
  16810. cli.set_follow_location(true);
  16811. auto res = cli.Get("/");
  16812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16813. EXPECT_EQ(StatusCode::OK_200, res->status);
  16814. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16815. }
  16816. }
  16817. TEST(RedirectTest, RedirectWithPlusInPath) {
  16818. Server svr;
  16819. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16820. res.set_redirect("/a+b");
  16821. });
  16822. // Route pattern uses regex; escape + as \\+
  16823. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16824. res.set_content(req.path, "text/plain");
  16825. });
  16826. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16827. auto se = detail::scope_exit([&] {
  16828. svr.stop();
  16829. thread.join();
  16830. ASSERT_FALSE(svr.is_running());
  16831. });
  16832. svr.wait_until_ready();
  16833. {
  16834. Client cli(HOST, PORT);
  16835. cli.set_follow_location(true);
  16836. auto res = cli.Get("/");
  16837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16838. EXPECT_EQ(StatusCode::OK_200, res->status);
  16839. EXPECT_EQ("/a+b", res->body);
  16840. }
  16841. }
  16842. TEST(RedirectTest, ResolveRelativeLocation) {
  16843. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16844. const std::vector<std::pair<std::string, std::string>> cases = {
  16845. {"g", "/b/c/g"},
  16846. {"./g", "/b/c/g"},
  16847. {"g/", "/b/c/g/"},
  16848. {"?y", "/b/c/d;p?y"},
  16849. {"g?y", "/b/c/g?y"},
  16850. {"#s", "/b/c/d;p?q#s"},
  16851. {"g#s", "/b/c/g#s"},
  16852. {"g?y#s", "/b/c/g?y#s"},
  16853. {";x", "/b/c/;x"},
  16854. {"g;x", "/b/c/g;x"},
  16855. {".", "/b/c/"},
  16856. {"./", "/b/c/"},
  16857. {"..", "/b/"},
  16858. {"../", "/b/"},
  16859. {"../g", "/b/g"},
  16860. {"../..", "/"},
  16861. {"../../", "/"},
  16862. {"../../g", "/g"},
  16863. {"../../../g", "/g"},
  16864. {"g.", "/b/c/g."},
  16865. {".g", "/b/c/.g"},
  16866. {"g..", "/b/c/g.."},
  16867. {"..g", "/b/c/..g"},
  16868. {"./../g", "/b/g"},
  16869. {"./g/.", "/b/c/g/"},
  16870. {"g/./h", "/b/c/g/h"},
  16871. {"g/../h", "/b/c/h"},
  16872. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16873. {"g;x=1/../y", "/b/c/y"},
  16874. {"g?y/./x", "/b/c/g?y/./x"},
  16875. {"g#s/../x", "/b/c/g#s/../x"},
  16876. // Not relative-path references, so left for parse_url.
  16877. {"/g", "/g"},
  16878. {"//g", "//g"},
  16879. {"http://g/x", "http://g/x"},
  16880. {"g:h", "g:h"},
  16881. };
  16882. for (const auto &c : cases) {
  16883. EXPECT_EQ(c.second,
  16884. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16885. << c.first;
  16886. }
  16887. }
  16888. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16889. Server svr;
  16890. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16891. res.set_redirect(req.get_param_value("to"));
  16892. });
  16893. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16894. res.set_content(req.target, "text/plain");
  16895. });
  16896. svr.Get("/other", [](const Request &req, Response &res) {
  16897. res.set_content(req.target, "text/plain");
  16898. });
  16899. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16900. auto se = detail::scope_exit([&] {
  16901. svr.stop();
  16902. thread.join();
  16903. ASSERT_FALSE(svr.is_running());
  16904. });
  16905. svr.wait_until_ready();
  16906. const std::vector<std::pair<std::string, std::string>> cases = {
  16907. {"next", "/dir/next"},
  16908. {"./next?x=1", "/dir/next?x=1"},
  16909. {"../other", "/other"},
  16910. };
  16911. for (const auto &c : cases) {
  16912. Client cli(HOST, PORT);
  16913. cli.set_follow_location(true);
  16914. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16915. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16916. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16917. EXPECT_EQ(c.second, res->body) << c.first;
  16918. }
  16919. }
  16920. #ifdef CPPHTTPLIB_SSL_ENABLED
  16921. TEST(RedirectTest, Issue2185_Online) {
  16922. SSLClient client("github.com");
  16923. client.set_follow_location(true);
  16924. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16925. "Coollab-Windows.zip");
  16926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16927. EXPECT_EQ(StatusCode::OK_200, res->status);
  16928. EXPECT_EQ(9920427U, res->body.size());
  16929. }
  16930. #endif
  16931. TEST(VulnerabilityTest, CRLFInjection) {
  16932. Server svr;
  16933. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16934. res.set_content("Hello 1", "text/plain");
  16935. });
  16936. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16937. res.set_content("Hello 2", "text/plain");
  16938. });
  16939. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16940. res.set_content("Hello 3", "text/plain");
  16941. });
  16942. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16943. res.set_content("Hello 4", "text/plain");
  16944. });
  16945. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16946. for (const auto &x : req.headers) {
  16947. auto key = x.first;
  16948. EXPECT_STRNE("evil", key.c_str());
  16949. }
  16950. });
  16951. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16952. auto se = detail::scope_exit([&] {
  16953. svr.stop();
  16954. thread.join();
  16955. ASSERT_FALSE(svr.is_running());
  16956. });
  16957. svr.wait_until_ready();
  16958. {
  16959. Client cli(HOST, PORT);
  16960. cli.Post("/test1", "A=B",
  16961. "application/x-www-form-urlencoded\r\nevil: hello1");
  16962. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16963. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16964. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16965. }
  16966. }
  16967. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16968. auto server_thread = std::thread([] {
  16969. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16970. default_socket_options(srv);
  16971. sockaddr_in addr{};
  16972. addr.sin_family = AF_INET;
  16973. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16974. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16975. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16976. ::listen(srv, 1);
  16977. sockaddr_in cli_addr{};
  16978. socklen_t cli_len = sizeof(cli_addr);
  16979. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16980. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16981. std::string buf_all;
  16982. char buf[2048];
  16983. ssize_t n;
  16984. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16985. buf_all.append(buf, static_cast<size_t>(n));
  16986. size_t pos;
  16987. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16988. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16989. auto e = request_block.find("\r\n");
  16990. if (e != std::string::npos) {
  16991. auto request_line = request_block.substr(0, e);
  16992. std::string msg =
  16993. "CRLF injection detected in request line: '" + request_line + "'";
  16994. EXPECT_FALSE(true) << msg;
  16995. }
  16996. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16997. ::send(cli,
  16998. #ifdef _WIN32
  16999. static_cast<const char *>(resp.c_str()),
  17000. static_cast<int>(resp.size()),
  17001. #else
  17002. resp.c_str(), resp.size(),
  17003. #endif
  17004. 0);
  17005. buf_all.erase(0, pos + 4);
  17006. }
  17007. }
  17008. detail::close_socket(cli);
  17009. detail::close_socket(srv);
  17010. });
  17011. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17012. auto cli = Client("127.0.0.1", PORT + 1);
  17013. auto headers = Headers{
  17014. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17015. {"Connection", "keep-alive"}};
  17016. auto res = cli.Get("/hi", headers);
  17017. EXPECT_FALSE(res);
  17018. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17019. server_thread.join();
  17020. }
  17021. // A request rejected before any byte reaches the socket must fail right away
  17022. // instead of waiting for a response the server will never send.
  17023. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17024. // The kernel completes the TCP handshake from the listen backlog, so the
  17025. // client connects, but nothing ever reads, responds or closes.
  17026. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17027. default_socket_options(srv);
  17028. sockaddr_in addr{};
  17029. addr.sin_family = AF_INET;
  17030. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17031. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17032. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17033. ASSERT_EQ(0, ::listen(srv, 8));
  17034. auto cli = Client("127.0.0.1", PORT + 1);
  17035. cli.set_read_timeout(10, 0);
  17036. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17037. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17038. std::chrono::steady_clock::now() - start)
  17039. .count();
  17040. };
  17041. {
  17042. Request req;
  17043. req.method = "GE T";
  17044. req.path = "/";
  17045. auto start = std::chrono::steady_clock::now();
  17046. auto res = cli.send(req);
  17047. EXPECT_FALSE(res);
  17048. EXPECT_EQ(Error::Write, res.error());
  17049. EXPECT_LT(elapsed_ms(start), 1000);
  17050. }
  17051. {
  17052. auto start = std::chrono::steady_clock::now();
  17053. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17054. EXPECT_FALSE(res);
  17055. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17056. EXPECT_LT(elapsed_ms(start), 1000);
  17057. }
  17058. EXPECT_FALSE(cli.is_socket_open());
  17059. detail::close_socket(srv);
  17060. }
  17061. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17062. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17063. default_socket_options(srv);
  17064. sockaddr_in addr{};
  17065. addr.sin_family = AF_INET;
  17066. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17067. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17068. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17069. ASSERT_EQ(0, ::listen(srv, 1));
  17070. std::string received;
  17071. auto server_thread = std::thread([&] {
  17072. auto sock = ::accept(srv, nullptr, nullptr);
  17073. if (sock == INVALID_SOCKET) { return; }
  17074. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17075. char buf[2048];
  17076. ssize_t n;
  17077. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17078. received.append(buf, static_cast<size_t>(n));
  17079. }
  17080. detail::close_socket(sock);
  17081. });
  17082. {
  17083. auto cli = Client("127.0.0.1", PORT + 1);
  17084. // "Z" sorts after the default headers, so writing straight to the socket
  17085. // would have sent the request line and those headers before the rejection.
  17086. auto handle =
  17087. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17088. EXPECT_FALSE(handle.is_valid());
  17089. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17090. }
  17091. server_thread.join();
  17092. detail::close_socket(srv);
  17093. EXPECT_TRUE(received.empty()) << received;
  17094. }
  17095. TEST(PathParamsTest, StaticMatch) {
  17096. const auto pattern = "/users/all";
  17097. detail::PathParamsMatcher matcher(pattern);
  17098. Request request;
  17099. request.path = "/users/all";
  17100. ASSERT_TRUE(matcher.match(request));
  17101. std::unordered_map<std::string, std::string> expected_params = {};
  17102. EXPECT_EQ(request.path_params, expected_params);
  17103. }
  17104. TEST(PathParamsTest, StaticMismatch) {
  17105. const auto pattern = "/users/all";
  17106. detail::PathParamsMatcher matcher(pattern);
  17107. Request request;
  17108. request.path = "/users/1";
  17109. ASSERT_FALSE(matcher.match(request));
  17110. }
  17111. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17112. const auto pattern = "/users/:id/subscriptions";
  17113. detail::PathParamsMatcher matcher(pattern);
  17114. Request request;
  17115. request.path = "/users/42/subscriptions";
  17116. ASSERT_TRUE(matcher.match(request));
  17117. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17118. EXPECT_EQ(request.path_params, expected_params);
  17119. }
  17120. TEST(PathParamsTest, SingleParamInTheEnd) {
  17121. const auto pattern = "/users/:id";
  17122. detail::PathParamsMatcher matcher(pattern);
  17123. Request request;
  17124. request.path = "/users/24";
  17125. ASSERT_TRUE(matcher.match(request));
  17126. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17127. EXPECT_EQ(request.path_params, expected_params);
  17128. }
  17129. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17130. const auto pattern = "/users/:id/";
  17131. detail::PathParamsMatcher matcher(pattern);
  17132. Request request;
  17133. request.path = "/users/42/";
  17134. ASSERT_TRUE(matcher.match(request));
  17135. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17136. EXPECT_EQ(request.path_params, expected_params);
  17137. }
  17138. TEST(PathParamsTest, EmptyParam) {
  17139. const auto pattern = "/users/:id/";
  17140. detail::PathParamsMatcher matcher(pattern);
  17141. Request request;
  17142. request.path = "/users//";
  17143. ASSERT_TRUE(matcher.match(request));
  17144. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17145. EXPECT_EQ(request.path_params, expected_params);
  17146. }
  17147. TEST(PathParamsTest, FragmentMismatch) {
  17148. const auto pattern = "/users/:id/";
  17149. detail::PathParamsMatcher matcher(pattern);
  17150. Request request;
  17151. request.path = "/admins/24/";
  17152. ASSERT_FALSE(matcher.match(request));
  17153. }
  17154. TEST(PathParamsTest, ExtraFragments) {
  17155. const auto pattern = "/users/:id";
  17156. detail::PathParamsMatcher matcher(pattern);
  17157. Request request;
  17158. request.path = "/users/42/subscriptions";
  17159. ASSERT_FALSE(matcher.match(request));
  17160. }
  17161. TEST(PathParamsTest, MissingTrailingParam) {
  17162. const auto pattern = "/users/:id";
  17163. detail::PathParamsMatcher matcher(pattern);
  17164. Request request;
  17165. request.path = "/users";
  17166. ASSERT_FALSE(matcher.match(request));
  17167. }
  17168. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17169. const auto pattern = "/users/:id/subscriptions";
  17170. detail::PathParamsMatcher matcher(pattern);
  17171. Request request;
  17172. request.path = "/users/subscriptions";
  17173. ASSERT_FALSE(matcher.match(request));
  17174. }
  17175. TEST(PathParamsTest, MultipleParams) {
  17176. const auto pattern = "/users/:userid/subscriptions/:subid";
  17177. detail::PathParamsMatcher matcher(pattern);
  17178. Request request;
  17179. request.path = "/users/42/subscriptions/2";
  17180. ASSERT_TRUE(matcher.match(request));
  17181. std::unordered_map<std::string, std::string> expected_params = {
  17182. {"userid", "42"}, {"subid", "2"}};
  17183. EXPECT_EQ(request.path_params, expected_params);
  17184. }
  17185. TEST(PathParamsTest, SequenceOfParams) {
  17186. const auto pattern = "/values/:x/:y/:z";
  17187. detail::PathParamsMatcher matcher(pattern);
  17188. Request request;
  17189. request.path = "/values/1/2/3";
  17190. ASSERT_TRUE(matcher.match(request));
  17191. std::unordered_map<std::string, std::string> expected_params = {
  17192. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17193. EXPECT_EQ(request.path_params, expected_params);
  17194. }
  17195. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17196. const auto pattern = "/prefix:suffix";
  17197. detail::PathParamsMatcher matcher(pattern);
  17198. Request request;
  17199. request.path = "/prefix:suffix";
  17200. ASSERT_TRUE(matcher.match(request));
  17201. const std::unordered_map<std::string, std::string> expected_params = {};
  17202. EXPECT_EQ(request.path_params, expected_params);
  17203. }
  17204. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17205. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17206. // calling thread's stack on a long enough path for a quantified pattern;
  17207. // RegexMatcher must refuse to run regex matching on paths beyond
  17208. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17209. detail::RegexMatcher matcher("/files/(.*)");
  17210. Request within_limit;
  17211. within_limit.path = "/files/" + std::string(10, 'A');
  17212. EXPECT_TRUE(matcher.match(within_limit));
  17213. Request over_limit;
  17214. over_limit.path =
  17215. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17216. EXPECT_FALSE(matcher.match(over_limit));
  17217. }
  17218. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17219. Server svr;
  17220. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17221. res.set_content("ok", "text/plain");
  17222. });
  17223. auto port = svr.bind_to_any_port(HOST);
  17224. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17225. auto se = detail::scope_exit([&] {
  17226. svr.stop();
  17227. thread.join();
  17228. ASSERT_FALSE(svr.is_running());
  17229. });
  17230. svr.wait_until_ready();
  17231. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17232. // request URI limit; this used to be able to crash the process.
  17233. std::string path =
  17234. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17235. std::string req = "GET " + path +
  17236. " HTTP/1.1\r\n"
  17237. "Host: " +
  17238. std::string(HOST) + ":" + std::to_string(port) +
  17239. "\r\n"
  17240. "Connection: close\r\n"
  17241. "\r\n";
  17242. std::string response;
  17243. ASSERT_TRUE(send_request(5, req, &response, port));
  17244. EXPECT_NE(std::string::npos, response.find("404"));
  17245. }
  17246. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17247. Server svr;
  17248. auto handler = [](const Request & /*req*/, Response &res) {
  17249. res.set_content("hit", "text/plain");
  17250. };
  17251. // No regex metacharacter, so this one is compared literally
  17252. svr.Get("/literal/route", handler);
  17253. // '.' is a regex metacharacter, so this one must keep regex semantics
  17254. svr.Get("/a.c", handler);
  17255. auto port = svr.bind_to_any_port(HOST);
  17256. std::thread t([&]() { svr.listen_after_bind(); });
  17257. auto se = detail::scope_exit([&] {
  17258. svr.stop();
  17259. t.join();
  17260. ASSERT_FALSE(svr.is_running());
  17261. });
  17262. svr.wait_until_ready();
  17263. Client cli(HOST, port);
  17264. struct {
  17265. const char *path;
  17266. int status;
  17267. } cases[] = {
  17268. {"/literal/route", StatusCode::OK_200},
  17269. {"/literal/routes", StatusCode::NotFound_404},
  17270. {"/literal/rout", StatusCode::NotFound_404},
  17271. {"/abc", StatusCode::OK_200},
  17272. {"/a.c", StatusCode::OK_200},
  17273. };
  17274. for (const auto &x : cases) {
  17275. auto res = cli.Get(x.path);
  17276. ASSERT_TRUE(res) << x.path;
  17277. EXPECT_EQ(x.status, res->status) << x.path;
  17278. }
  17279. }
  17280. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17281. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17282. // from exhausting the stack, so it must only constrain routes that actually
  17283. // run a regular expression. A literal route is matched by comparison and
  17284. // stays usable at any length.
  17285. Server svr;
  17286. const std::string pattern =
  17287. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17288. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17289. res.set_content("hit", "text/plain");
  17290. });
  17291. auto port = svr.bind_to_any_port(HOST);
  17292. std::thread t([&]() { svr.listen_after_bind(); });
  17293. auto se = detail::scope_exit([&] {
  17294. svr.stop();
  17295. t.join();
  17296. ASSERT_FALSE(svr.is_running());
  17297. });
  17298. svr.wait_until_ready();
  17299. Client cli(HOST, port);
  17300. auto res = cli.Get(pattern);
  17301. ASSERT_TRUE(res);
  17302. EXPECT_EQ(StatusCode::OK_200, res->status);
  17303. }
  17304. TEST(ParseUrlTest, VariousPatterns) {
  17305. {
  17306. detail::UrlComponents uc;
  17307. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17308. EXPECT_EQ("http", uc.scheme);
  17309. EXPECT_EQ("example.com", uc.host);
  17310. EXPECT_EQ("8080", uc.port);
  17311. EXPECT_EQ("/path", uc.path);
  17312. EXPECT_EQ("?q=1", uc.query);
  17313. }
  17314. {
  17315. detail::UrlComponents uc;
  17316. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17317. EXPECT_EQ("https", uc.scheme);
  17318. EXPECT_EQ("example.com", uc.host);
  17319. EXPECT_TRUE(uc.port.empty());
  17320. EXPECT_EQ("/path", uc.path);
  17321. }
  17322. {
  17323. detail::UrlComponents uc;
  17324. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17325. EXPECT_EQ("::1", uc.host);
  17326. EXPECT_EQ("8080", uc.port);
  17327. EXPECT_EQ("/path", uc.path);
  17328. }
  17329. {
  17330. detail::UrlComponents uc;
  17331. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17332. }
  17333. {
  17334. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17335. // the path while the connection still targets the bracketed host.
  17336. detail::UrlComponents uc;
  17337. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17338. }
  17339. {
  17340. detail::UrlComponents uc;
  17341. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17342. }
  17343. {
  17344. detail::UrlComponents uc;
  17345. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17346. EXPECT_EQ("::1", uc.host);
  17347. EXPECT_TRUE(uc.port.empty());
  17348. EXPECT_EQ("/path", uc.path);
  17349. }
  17350. {
  17351. detail::UrlComponents uc;
  17352. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17353. EXPECT_TRUE(uc.scheme.empty());
  17354. EXPECT_EQ("example.com", uc.host);
  17355. EXPECT_EQ("/path", uc.path);
  17356. EXPECT_EQ("?q=1", uc.query);
  17357. }
  17358. {
  17359. detail::UrlComponents uc;
  17360. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17361. EXPECT_TRUE(uc.host.empty());
  17362. EXPECT_EQ("/path", uc.path);
  17363. EXPECT_EQ("?q=1", uc.query);
  17364. }
  17365. {
  17366. detail::UrlComponents uc;
  17367. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17368. EXPECT_EQ("example.com", uc.host);
  17369. EXPECT_EQ("8080", uc.port);
  17370. }
  17371. {
  17372. // Unix socket path — must not be parsed as host
  17373. detail::UrlComponents uc;
  17374. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17375. EXPECT_TRUE(uc.host.empty());
  17376. }
  17377. {
  17378. detail::UrlComponents uc;
  17379. ASSERT_TRUE(detail::parse_url("", uc));
  17380. EXPECT_TRUE(uc.host.empty());
  17381. EXPECT_TRUE(uc.path.empty());
  17382. }
  17383. {
  17384. detail::UrlComponents uc;
  17385. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17386. }
  17387. {
  17388. detail::UrlComponents uc;
  17389. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17390. }
  17391. {
  17392. // Accepted by parse_url; callers restrict to http/https
  17393. detail::UrlComponents uc;
  17394. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17395. EXPECT_EQ("ftp", uc.scheme);
  17396. }
  17397. {
  17398. detail::UrlComponents uc;
  17399. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17400. }
  17401. {
  17402. detail::UrlComponents uc;
  17403. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17404. }
  17405. }
  17406. TEST(ParseUrlTest, FragmentHandling) {
  17407. {
  17408. detail::UrlComponents uc;
  17409. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17410. EXPECT_EQ("/path", uc.path);
  17411. EXPECT_TRUE(uc.query.empty());
  17412. }
  17413. {
  17414. detail::UrlComponents uc;
  17415. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17416. EXPECT_TRUE(uc.path.empty());
  17417. EXPECT_TRUE(uc.query.empty());
  17418. }
  17419. }
  17420. TEST(ParseUrlTest, UserinfoHandling) {
  17421. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17422. // parsers would see evil.com as the host.
  17423. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17424. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17425. for (auto url : urls) {
  17426. detail::UrlComponents uc;
  17427. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17428. }
  17429. }
  17430. TEST(ParseUrlTest, IPv6EdgeCases) {
  17431. {
  17432. detail::UrlComponents uc;
  17433. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17434. EXPECT_TRUE(uc.scheme.empty());
  17435. EXPECT_EQ("::1", uc.host);
  17436. EXPECT_EQ("8080", uc.port);
  17437. }
  17438. {
  17439. // Zone ID '%25' is not in [a-fA-F0-9:]
  17440. detail::UrlComponents uc;
  17441. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17442. }
  17443. }
  17444. TEST(ParseUrlTest, SchemeEdgeCases) {
  17445. {
  17446. detail::UrlComponents uc;
  17447. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17448. }
  17449. {
  17450. detail::UrlComponents uc;
  17451. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17452. }
  17453. {
  17454. detail::UrlComponents uc;
  17455. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17456. }
  17457. }
  17458. TEST(ParseUrlTest, PortEdgeCases) {
  17459. {
  17460. detail::UrlComponents uc;
  17461. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17462. EXPECT_TRUE(uc.port.empty());
  17463. EXPECT_EQ("/path", uc.path);
  17464. }
  17465. {
  17466. // parse_url accepts any port string; validation is done by parse_port
  17467. detail::UrlComponents uc;
  17468. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17469. EXPECT_EQ("abc", uc.port);
  17470. }
  17471. }
  17472. TEST(ParseUrlTest, WebSocketPatterns) {
  17473. {
  17474. detail::UrlComponents uc;
  17475. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17476. EXPECT_EQ("ws", uc.scheme);
  17477. EXPECT_EQ("echo.example.com", uc.host);
  17478. EXPECT_EQ("8080", uc.port);
  17479. EXPECT_EQ("/ws", uc.path);
  17480. }
  17481. {
  17482. detail::UrlComponents uc;
  17483. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17484. EXPECT_EQ("wss", uc.scheme);
  17485. EXPECT_EQ("echo.example.com", uc.host);
  17486. EXPECT_TRUE(uc.port.empty());
  17487. EXPECT_EQ("/ws", uc.path);
  17488. }
  17489. }
  17490. TEST(ParseUrlTest, QueryOnly) {
  17491. detail::UrlComponents uc;
  17492. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17493. EXPECT_TRUE(uc.host.empty());
  17494. EXPECT_TRUE(uc.path.empty());
  17495. EXPECT_EQ("?q=1&r=2", uc.query);
  17496. }
  17497. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17498. detail::UrlComponents uc;
  17499. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17500. EXPECT_TRUE(uc.scheme.empty());
  17501. EXPECT_EQ("example.com", uc.host);
  17502. EXPECT_EQ("443", uc.port);
  17503. EXPECT_EQ("/path", uc.path);
  17504. }
  17505. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17506. // If ipv6 regex working, regex match codepath is taken.
  17507. // else port will default to 80 in Client impl
  17508. int clientImplMagicPort = 80;
  17509. int port = 4321;
  17510. // above ports must be different to avoid false negative
  17511. EXPECT_NE(clientImplMagicPort, port);
  17512. std::string ipV6TestURL = "http://[ff06::c3]";
  17513. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17514. CLIENT_PRIVATE_KEY_FILE);
  17515. EXPECT_EQ(cli.port(), port);
  17516. }
  17517. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17518. auto file_path = "./www/dir/index.html";
  17519. auto dir_path = "./www/dir";
  17520. detail::FileStat stat_file(file_path);
  17521. EXPECT_TRUE(stat_file.is_file());
  17522. EXPECT_FALSE(stat_file.is_dir());
  17523. detail::FileStat stat_dir(dir_path);
  17524. EXPECT_FALSE(stat_dir.is_file());
  17525. EXPECT_TRUE(stat_dir.is_dir());
  17526. }
  17527. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17528. // IPv4 with default HTTP port (80)
  17529. EXPECT_EQ("example.com",
  17530. detail::make_host_and_port_string("example.com", 80, false));
  17531. // IPv4 with default HTTPS port (443)
  17532. EXPECT_EQ("example.com",
  17533. detail::make_host_and_port_string("example.com", 443, true));
  17534. // IPv4 with non-default HTTP port
  17535. EXPECT_EQ("example.com:8080",
  17536. detail::make_host_and_port_string("example.com", 8080, false));
  17537. // IPv4 with non-default HTTPS port
  17538. EXPECT_EQ("example.com:8443",
  17539. detail::make_host_and_port_string("example.com", 8443, true));
  17540. // IPv6 with default HTTP port (80)
  17541. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17542. // IPv6 with default HTTPS port (443)
  17543. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17544. // IPv6 with non-default HTTP port
  17545. EXPECT_EQ("[::1]:8080",
  17546. detail::make_host_and_port_string("::1", 8080, false));
  17547. // IPv6 with non-default HTTPS port
  17548. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17549. // IPv6 full address with default port
  17550. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17551. detail::make_host_and_port_string(
  17552. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17553. // IPv6 full address with non-default port
  17554. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17555. detail::make_host_and_port_string(
  17556. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17557. // IPv6 localhost with non-default port
  17558. EXPECT_EQ("[::1]:3000",
  17559. detail::make_host_and_port_string("::1", 3000, false));
  17560. // IPv6 with zone ID (link-local address) with default port
  17561. EXPECT_EQ("[fe80::1%eth0]",
  17562. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17563. // IPv6 with zone ID (link-local address) with non-default port
  17564. EXPECT_EQ("[fe80::1%eth0]:8080",
  17565. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17566. // Edge case: Port 443 with is_ssl=false (should add port)
  17567. EXPECT_EQ("example.com:443",
  17568. detail::make_host_and_port_string("example.com", 443, false));
  17569. // Edge case: Port 80 with is_ssl=true (should add port)
  17570. EXPECT_EQ("example.com:80",
  17571. detail::make_host_and_port_string("example.com", 80, true));
  17572. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17573. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17574. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17575. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17576. // Security fix: Already bracketed IPv6 should not get double brackets
  17577. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17578. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17579. EXPECT_EQ("[::1]:8080",
  17580. detail::make_host_and_port_string("[::1]", 8080, false));
  17581. EXPECT_EQ("[2001:db8::1]:8080",
  17582. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17583. EXPECT_EQ("[fe80::1%eth0]",
  17584. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17585. EXPECT_EQ("[fe80::1%eth0]:8080",
  17586. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17587. // Edge case: Empty host (should return as-is)
  17588. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17589. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17590. // This is a known limitation but shouldn't crash
  17591. EXPECT_EQ("[host:name]",
  17592. detail::make_host_and_port_string("host:name", 80, false));
  17593. // Port number edge cases (no validation, but should not crash)
  17594. EXPECT_EQ("example.com:0",
  17595. detail::make_host_and_port_string("example.com", 0, false));
  17596. EXPECT_EQ("example.com:-1",
  17597. detail::make_host_and_port_string("example.com", -1, false));
  17598. EXPECT_EQ("example.com:65535",
  17599. detail::make_host_and_port_string("example.com", 65535, false));
  17600. EXPECT_EQ("example.com:65536",
  17601. detail::make_host_and_port_string("example.com", 65536, false));
  17602. }
  17603. #ifdef CPPHTTPLIB_SSL_ENABLED
  17604. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17605. httplib::SSLClient cli("roblox.com", 443);
  17606. cli.set_follow_location(true);
  17607. auto res = cli.Get("/");
  17608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17609. EXPECT_EQ(StatusCode::OK_200, res->status);
  17610. }
  17611. #endif
  17612. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17613. Server svr;
  17614. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17615. EXPECT_EQ(res.status, 400);
  17616. });
  17617. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17618. auto se = detail::scope_exit([&] {
  17619. svr.stop();
  17620. thread.join();
  17621. ASSERT_FALSE(svr.is_running());
  17622. });
  17623. svr.wait_until_ready();
  17624. Client cli(HOST, PORT);
  17625. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17626. }
  17627. TEST(InvalidHeaderCharsTest, is_field_name) {
  17628. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17629. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17630. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17631. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17632. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17633. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17634. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17635. EXPECT_FALSE(detail::fields::is_field_name(""));
  17636. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17637. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17638. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17639. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17640. }
  17641. TEST(InvalidHeaderCharsTest, is_field_value) {
  17642. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17643. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17644. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17645. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17646. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17647. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17648. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17649. EXPECT_TRUE(detail::fields::is_field_value(""));
  17650. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17651. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17652. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17653. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17654. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17655. }
  17656. TEST(InvalidHeaderCharsTest, OnServer) {
  17657. Server svr;
  17658. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17659. std::string header = "Not Set";
  17660. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17661. res.set_header(header, "value");
  17662. res.set_content("Page Content Page Content", "text/plain");
  17663. });
  17664. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17665. std::string header = "Not Set";
  17666. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17667. res.set_header("X-Test", header);
  17668. res.set_content("Page Content Page Content", "text/plain");
  17669. });
  17670. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17671. auto se = detail::scope_exit([&] {
  17672. svr.stop();
  17673. thread.join();
  17674. ASSERT_FALSE(svr.is_running());
  17675. });
  17676. svr.wait_until_ready();
  17677. Client cli(HOST, PORT);
  17678. {
  17679. auto res = cli.Get(
  17680. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17682. EXPECT_EQ("Page Content Page Content", res->body);
  17683. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17684. }
  17685. {
  17686. auto res = cli.Get(
  17687. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17689. EXPECT_EQ("Page Content Page Content", res->body);
  17690. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17691. }
  17692. }
  17693. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17694. auto handled = false;
  17695. Server svr;
  17696. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17697. thread t = thread([&] { svr.listen(HOST, PORT); });
  17698. auto se = detail::scope_exit([&] {
  17699. svr.stop();
  17700. t.join();
  17701. ASSERT_FALSE(svr.is_running());
  17702. ASSERT_FALSE(handled);
  17703. });
  17704. svr.wait_until_ready();
  17705. auto req = "POST /test HTTP/1.1\r\n"
  17706. "Content-Length: x\r\n"
  17707. "\r\n";
  17708. std::string response;
  17709. ASSERT_TRUE(send_request(1, req, &response));
  17710. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17711. response.substr(0, response.find("\r\n")));
  17712. }
  17713. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17714. // case-insensitive, and a server that receives a 100-continue expectation in
  17715. // an HTTP/1.0 request MUST ignore it.
  17716. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17717. std::string response;
  17718. ASSERT_TRUE(send_request(1, req, &response, port));
  17719. *got_100 = response.find("100 Continue") != std::string::npos;
  17720. }
  17721. class ExpectTokenTest : public ::testing::Test {
  17722. protected:
  17723. void SetUp() override {
  17724. svr_.Post("/p", [](const Request &, Response &res) {
  17725. res.set_content("ok", "text/plain");
  17726. });
  17727. port_ = svr_.bind_to_any_port(HOST);
  17728. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17729. svr_.wait_until_ready();
  17730. }
  17731. void TearDown() override {
  17732. svr_.stop();
  17733. if (thread_.joinable()) { thread_.join(); }
  17734. }
  17735. std::string request(const char *version, const char *expect_value) const {
  17736. return std::string("POST /p ") + version +
  17737. "\r\n"
  17738. "Host: localhost\r\n"
  17739. "Content-Length: 2\r\n"
  17740. "Connection: close\r\n"
  17741. "Expect: " +
  17742. expect_value +
  17743. "\r\n"
  17744. "\r\n"
  17745. "hi";
  17746. }
  17747. Server svr_;
  17748. int port_ = 0;
  17749. thread thread_;
  17750. };
  17751. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17752. bool got_100 = false;
  17753. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17754. EXPECT_TRUE(got_100);
  17755. }
  17756. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17757. bool got_100 = true;
  17758. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17759. EXPECT_FALSE(got_100);
  17760. }
  17761. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17762. bool got_100 = false;
  17763. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17764. EXPECT_TRUE(got_100);
  17765. }
  17766. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17767. bool got_100 = false;
  17768. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17769. EXPECT_TRUE(got_100);
  17770. }
  17771. // `100 Continue` is sent only when the server starts reading the body, so a
  17772. // request rejected before that never invites the client to send it. The
  17773. // requests below carry the expectation but withhold the body, as a client
  17774. // waiting for `100 Continue` would.
  17775. // A POST that expects `100 Continue` and withholds its two-byte body.
  17776. static std::string expect_headers_only(const std::string &path) {
  17777. return "POST " + path +
  17778. " HTTP/1.1\r\n"
  17779. "Host: localhost\r\n"
  17780. "Content-Length: 2\r\n"
  17781. "Expect: 100-continue\r\n"
  17782. "\r\n";
  17783. }
  17784. class ExpectLazyContinueTest : public ::testing::Test {
  17785. protected:
  17786. void SetUp() override {
  17787. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17788. if (req.path == "/pre-routing") {
  17789. res.status = StatusCode::Unauthorized_401;
  17790. return Server::HandlerResponse::Handled;
  17791. }
  17792. return Server::HandlerResponse::Unhandled;
  17793. });
  17794. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17795. if (req.matched_route == "/pre-request") {
  17796. res.status = StatusCode::Forbidden_403;
  17797. return Server::HandlerResponse::Handled;
  17798. }
  17799. return Server::HandlerResponse::Unhandled;
  17800. });
  17801. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17802. res.set_content("ok", "text/plain");
  17803. });
  17804. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17805. res.set_content("ok", "text/plain");
  17806. });
  17807. svr_.Post("/reader-used", [](const Request &, Response &res,
  17808. const ContentReader &content_reader) {
  17809. std::string body;
  17810. content_reader([&](const char *data, size_t len) {
  17811. body.append(data, len);
  17812. return true;
  17813. });
  17814. res.set_content(body, "text/plain");
  17815. });
  17816. svr_.Post("/reader-unused",
  17817. [](const Request &, Response &res, const ContentReader &) {
  17818. res.set_content("ignored", "text/plain");
  17819. });
  17820. port_ = svr_.bind_to_any_port(HOST);
  17821. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17822. svr_.wait_until_ready();
  17823. }
  17824. void TearDown() override {
  17825. svr_.stop();
  17826. if (thread_.joinable()) { thread_.join(); }
  17827. }
  17828. // Sends `req` and reads until the server closes the connection. Returns
  17829. // false if the read had to wait for the client-side timeout instead.
  17830. bool send_until_closed(const std::string &req, std::string *resp) const {
  17831. auto start = std::chrono::steady_clock::now();
  17832. if (!send_request(3, req, resp, port_)) { return false; }
  17833. auto elapsed = std::chrono::steady_clock::now() - start;
  17834. return elapsed < std::chrono::seconds(2);
  17835. }
  17836. // The final response comes without `100 Continue`, and the server closes
  17837. // the connection since the body may or may not follow.
  17838. void expect_final_without_interim(const std::string &path,
  17839. const char *status_line) const {
  17840. std::string resp;
  17841. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17842. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17843. EXPECT_EQ(0u, resp.find(status_line));
  17844. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17845. }
  17846. Server svr_;
  17847. int port_ = 0;
  17848. thread thread_;
  17849. };
  17850. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17851. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17852. }
  17853. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17854. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17855. }
  17856. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17857. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17858. }
  17859. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17860. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17861. }
  17862. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17863. // The body follows once `100 Continue` has had time to arrive.
  17864. auto req = expect_headers_only("/reader-used");
  17865. req.insert(req.size() - 2, "Connection: close\r\n");
  17866. std::string resp;
  17867. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17868. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17869. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17870. EXPECT_NE(std::string::npos, resp.find("hi"));
  17871. }
  17872. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17873. // Large enough for the client to add `Expect: 100-continue` itself.
  17874. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17875. std::atomic<bool> body_sent{false};
  17876. Client cli(HOST, port_);
  17877. auto res = cli.Post(
  17878. "/pre-request", length,
  17879. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17880. body_sent = true;
  17881. std::string chunk(len, 'x');
  17882. sink.write(chunk.data(), chunk.size());
  17883. return true;
  17884. },
  17885. "application/octet-stream");
  17886. ASSERT_TRUE(res);
  17887. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17888. EXPECT_FALSE(body_sent);
  17889. }
  17890. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17891. Server svr;
  17892. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17893. return StatusCode::ExpectationFailed_417;
  17894. });
  17895. svr.Post("/p", [](const Request &, Response &res) {
  17896. res.set_content("ok", "text/plain");
  17897. });
  17898. auto port = svr.bind_to_any_port(HOST);
  17899. thread t = thread([&] { svr.listen_after_bind(); });
  17900. auto se = detail::scope_exit([&] {
  17901. svr.stop();
  17902. t.join();
  17903. });
  17904. svr.wait_until_ready();
  17905. std::string resp;
  17906. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17907. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17908. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17909. // Exactly one response: the route handler must not run after the 417.
  17910. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17911. }
  17912. #ifndef _WIN32
  17913. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17914. static constexpr char reject[] = "Unauthorized";
  17915. static constexpr char accept[] = "Upload accepted";
  17916. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17917. Server svr;
  17918. svr.set_expect_100_continue_handler(
  17919. [](const Request & /*req*/, Response &res) {
  17920. res.status = StatusCode::Unauthorized_401;
  17921. res.set_content(reject, "text/plain");
  17922. return res.status;
  17923. });
  17924. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17925. res.set_content(accept, "text/plain");
  17926. });
  17927. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17928. auto se = detail::scope_exit([&] {
  17929. svr.stop();
  17930. thread.join();
  17931. ASSERT_FALSE(svr.is_running());
  17932. });
  17933. svr.wait_until_ready();
  17934. {
  17935. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17936. curl_easy_init(), &curl_easy_cleanup};
  17937. ASSERT_NE(curl, nullptr);
  17938. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17939. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17940. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17941. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17942. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17943. &curl_slist_free_all};
  17944. ASSERT_NE(list, nullptr);
  17945. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17946. struct read_data {
  17947. uint64_t read_size;
  17948. uint64_t total_size;
  17949. } data = {0, total_size};
  17950. using read_callback_t =
  17951. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17952. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17953. void *userdata) -> size_t {
  17954. read_data *d = (read_data *)userdata;
  17955. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17956. std::fill_n(ptr, size * nmemb, 'A');
  17957. d->read_size += size * nmemb;
  17958. return size * nmemb;
  17959. };
  17960. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  17961. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17962. std::vector<char> buffer;
  17963. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17964. using write_callback_t =
  17965. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17966. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17967. void *userdata) -> size_t {
  17968. std::vector<char> *buf = (std::vector<char> *)userdata;
  17969. buf->reserve(buf->size() + size * nmemb + 1);
  17970. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17971. return size * nmemb;
  17972. };
  17973. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17974. {
  17975. const auto res = curl_easy_perform(curl.get());
  17976. ASSERT_EQ(res, CURLE_OK);
  17977. }
  17978. {
  17979. auto response_code = long{};
  17980. const auto res =
  17981. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17982. ASSERT_EQ(res, CURLE_OK);
  17983. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17984. }
  17985. {
  17986. auto dl = curl_off_t{};
  17987. const auto res =
  17988. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17989. ASSERT_EQ(res, CURLE_OK);
  17990. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17991. }
  17992. {
  17993. buffer.push_back('\0');
  17994. ASSERT_STRCASEEQ(buffer.data(), reject);
  17995. }
  17996. }
  17997. }
  17998. #endif
  17999. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18000. // Regression test for #2458.
  18001. //
  18002. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18003. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18004. // ticket can make the client socket spuriously readable during the
  18005. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18006. // the client withholds the body and then blocks reading a response that never
  18007. // comes, failing with `Failed to read connection`.
  18008. //
  18009. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18010. // within the timeout. This raw OpenSSL server deliberately never sends
  18011. // `100 Continue`; the client must still deliver the body and receive 200.
  18012. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18013. signal(SIGPIPE, SIG_IGN);
  18014. const auto port = PORT + 4;
  18015. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18016. ASSERT_NE(srv, INVALID_SOCKET);
  18017. int opt = 1;
  18018. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18019. sockaddr_in addr{};
  18020. addr.sin_family = AF_INET;
  18021. addr.sin_port = htons(static_cast<uint16_t>(port));
  18022. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18023. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18024. ASSERT_EQ(0, ::listen(srv, 1));
  18025. std::atomic<size_t> server_body_bytes{0};
  18026. auto server_thread = std::thread([&] {
  18027. sockaddr_in cli_addr{};
  18028. socklen_t cli_len = sizeof(cli_addr);
  18029. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18030. if (cli == INVALID_SOCKET) { return; }
  18031. // Bound the lifetime of the server side so a buggy client (which never
  18032. // sends the body) cannot make this thread block forever on join.
  18033. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18034. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18035. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18036. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18037. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18038. SSL *ssl = SSL_new(ctx);
  18039. SSL_set_fd(ssl, static_cast<int>(cli));
  18040. if (SSL_accept(ssl) > 0) {
  18041. // Read the request headers. Reading here also flushes the TLS 1.3
  18042. // session tickets to the client. Deliberately do NOT send
  18043. // `100 Continue`.
  18044. std::string buf;
  18045. char tmp[1024];
  18046. while (buf.find("\r\n\r\n") == std::string::npos) {
  18047. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18048. if (n <= 0) { break; }
  18049. buf.append(tmp, static_cast<size_t>(n));
  18050. }
  18051. // A correct client sends the body now; count what arrives.
  18052. auto pos = buf.find("\r\n\r\n");
  18053. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18054. while (body < 4096) {
  18055. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18056. if (n <= 0) { break; }
  18057. body += static_cast<size_t>(n);
  18058. }
  18059. server_body_bytes = body;
  18060. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18061. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18062. SSL_shutdown(ssl);
  18063. }
  18064. SSL_free(ssl);
  18065. detail::close_socket(cli);
  18066. SSL_CTX_free(ctx);
  18067. });
  18068. auto se = detail::scope_exit([&] {
  18069. server_thread.join();
  18070. detail::close_socket(srv);
  18071. });
  18072. SSLClient cli("127.0.0.1", port);
  18073. cli.enable_server_certificate_verification(false);
  18074. cli.set_connection_timeout(5, 0);
  18075. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18076. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18077. std::string body(4096, 'A');
  18078. auto res = cli.Put("/api/test", body, "application/json");
  18079. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18080. EXPECT_EQ(StatusCode::OK_200, res->status);
  18081. EXPECT_EQ(body.size(), server_body_bytes.load());
  18082. }
  18083. #endif
  18084. template <typename S, typename C>
  18085. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18086. svr.Get("/stream", [&](const Request &, Response &res) {
  18087. auto data = new std::string("01234567890123456789");
  18088. res.set_content_provider(
  18089. data->size(), "text/plain",
  18090. [&, data](size_t offset, size_t length, DataSink &sink) {
  18091. const size_t DATA_CHUNK_SIZE = 4;
  18092. const auto &d = *data;
  18093. std::this_thread::sleep_for(std::chrono::seconds(1));
  18094. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18095. return true;
  18096. },
  18097. [data](bool success) {
  18098. EXPECT_FALSE(success);
  18099. delete data;
  18100. });
  18101. });
  18102. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18103. auto i = new size_t(0);
  18104. res.set_content_provider(
  18105. "text/plain",
  18106. [i](size_t, DataSink &sink) {
  18107. if (*i < 5) {
  18108. std::this_thread::sleep_for(std::chrono::seconds(1));
  18109. sink.write("abcd", 4);
  18110. (*i)++;
  18111. } else {
  18112. sink.done();
  18113. }
  18114. return true;
  18115. },
  18116. [i](bool success) {
  18117. EXPECT_FALSE(success);
  18118. delete i;
  18119. });
  18120. });
  18121. svr.Get("/chunked", [&](const Request &, Response &res) {
  18122. auto i = new size_t(0);
  18123. res.set_chunked_content_provider(
  18124. "text/plain",
  18125. [i](size_t, DataSink &sink) {
  18126. if (*i < 5) {
  18127. std::this_thread::sleep_for(std::chrono::seconds(1));
  18128. sink.os << "abcd";
  18129. (*i)++;
  18130. } else {
  18131. sink.done();
  18132. }
  18133. return true;
  18134. },
  18135. [i](bool success) {
  18136. EXPECT_FALSE(success);
  18137. delete i;
  18138. });
  18139. });
  18140. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18141. auto se = detail::scope_exit([&] {
  18142. svr.stop();
  18143. listen_thread.join();
  18144. ASSERT_FALSE(svr.is_running());
  18145. });
  18146. svr.wait_until_ready();
  18147. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18148. {
  18149. auto start = std::chrono::steady_clock::now();
  18150. auto res = cli.Get("/stream");
  18151. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18152. std::chrono::steady_clock::now() - start)
  18153. .count();
  18154. ASSERT_FALSE(res);
  18155. EXPECT_EQ(Error::Read, res.error());
  18156. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18157. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18158. }
  18159. {
  18160. auto start = std::chrono::steady_clock::now();
  18161. auto res = cli.Get("/stream_without_length");
  18162. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18163. std::chrono::steady_clock::now() - start)
  18164. .count();
  18165. ASSERT_FALSE(res);
  18166. EXPECT_EQ(Error::Read, res.error());
  18167. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18168. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18169. }
  18170. {
  18171. auto start = std::chrono::steady_clock::now();
  18172. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18173. EXPECT_EQ("abcd", string(data, data_length));
  18174. return true;
  18175. });
  18176. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18177. std::chrono::steady_clock::now() - start)
  18178. .count();
  18179. ASSERT_FALSE(res);
  18180. EXPECT_EQ(Error::Read, res.error());
  18181. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18182. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18183. }
  18184. }
  18185. TEST(MaxTimeoutTest, ContentStream) {
  18186. time_t timeout = 2000;
  18187. time_t threshold = 200;
  18188. Server svr;
  18189. Client cli("localhost", PORT);
  18190. max_timeout_test(svr, cli, timeout, threshold);
  18191. }
  18192. #ifdef CPPHTTPLIB_SSL_ENABLED
  18193. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18194. time_t timeout = 2000;
  18195. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18196. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18197. SSLClient cli("localhost", PORT);
  18198. cli.enable_server_certificate_verification(false);
  18199. max_timeout_test(svr, cli, timeout, threshold);
  18200. }
  18201. #endif
  18202. class EventDispatcher {
  18203. public:
  18204. EventDispatcher() {}
  18205. bool wait_event(DataSink *sink) {
  18206. unique_lock<mutex> lk(m_);
  18207. int id = id_;
  18208. // Wait with timeout to prevent hanging if client disconnects
  18209. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18210. [&] { return cid_ == id; })) {
  18211. return false; // Timeout occurred
  18212. }
  18213. sink->write(message_.data(), message_.size());
  18214. return true;
  18215. }
  18216. void send_event(const string &message) {
  18217. lock_guard<mutex> lk(m_);
  18218. cid_ = id_++;
  18219. message_ = message;
  18220. cv_.notify_all();
  18221. }
  18222. private:
  18223. mutex m_;
  18224. condition_variable cv_;
  18225. atomic_int id_{0};
  18226. atomic_int cid_{-1};
  18227. string message_;
  18228. };
  18229. TEST(ClientInThreadTest, Issue2068) {
  18230. EventDispatcher ed;
  18231. Server svr;
  18232. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18233. res.set_chunked_content_provider("text/event-stream",
  18234. [&](size_t /*offset*/, DataSink &sink) {
  18235. return ed.wait_event(&sink);
  18236. });
  18237. });
  18238. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18239. svr.wait_until_ready();
  18240. thread event_thread([&] {
  18241. int id = 0;
  18242. while (svr.is_running()) {
  18243. this_thread::sleep_for(chrono::milliseconds(500));
  18244. std::stringstream ss;
  18245. ss << "data: " << id << "\n\n";
  18246. ed.send_event(ss.str());
  18247. id++;
  18248. }
  18249. });
  18250. auto se = detail::scope_exit([&] {
  18251. svr.stop();
  18252. listen_thread.join();
  18253. event_thread.join();
  18254. ASSERT_FALSE(svr.is_running());
  18255. });
  18256. {
  18257. auto client = detail::make_unique<Client>(HOST, PORT);
  18258. client->set_read_timeout(std::chrono::minutes(10));
  18259. std::atomic<bool> stop{false};
  18260. std::thread t([&] {
  18261. client->Get("/event1",
  18262. [&](const char *, size_t) -> bool { return !stop; });
  18263. });
  18264. std::this_thread::sleep_for(std::chrono::seconds(2));
  18265. stop = true;
  18266. client->stop();
  18267. t.join();
  18268. // Reset client after thread has finished
  18269. client.reset();
  18270. }
  18271. }
  18272. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18273. auto handled = false;
  18274. Server svr;
  18275. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18276. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18277. auto se = detail::scope_exit([&] {
  18278. svr.stop();
  18279. t.join();
  18280. ASSERT_FALSE(svr.is_running());
  18281. ASSERT_FALSE(handled);
  18282. });
  18283. svr.wait_until_ready();
  18284. // Two Content-Length headers with different values — must be rejected
  18285. auto req = "POST /test HTTP/1.1\r\n"
  18286. "Content-Length: 5\r\n"
  18287. "Content-Length: 10\r\n"
  18288. "\r\n"
  18289. "hello";
  18290. std::string response;
  18291. ASSERT_TRUE(send_request(1, req, &response));
  18292. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18293. response.substr(0, response.find("\r\n")));
  18294. }
  18295. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18296. auto handled = false;
  18297. Server svr;
  18298. svr.Post("/test", [&](const Request &, Response &res) {
  18299. handled = true;
  18300. res.set_content("ok", "text/plain");
  18301. });
  18302. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18303. auto se = detail::scope_exit([&] {
  18304. svr.stop();
  18305. t.join();
  18306. ASSERT_FALSE(svr.is_running());
  18307. ASSERT_TRUE(handled);
  18308. });
  18309. svr.wait_until_ready();
  18310. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18311. auto req = "POST /test HTTP/1.1\r\n"
  18312. "Host: localhost\r\n"
  18313. "Content-Length: 5\r\n"
  18314. "Content-Length: 5\r\n"
  18315. "\r\n"
  18316. "hello";
  18317. std::string response;
  18318. ASSERT_TRUE(send_request(1, req, &response));
  18319. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18320. }
  18321. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18322. Server svr;
  18323. svr.Get("/test", [](const Request &, Response &res) {
  18324. res.set_content("ok", "text/plain");
  18325. });
  18326. auto port = svr.bind_to_any_port(HOST);
  18327. thread t = thread([&] { svr.listen_after_bind(); });
  18328. auto se = detail::scope_exit([&] {
  18329. svr.stop();
  18330. t.join();
  18331. ASSERT_FALSE(svr.is_running());
  18332. });
  18333. svr.wait_until_ready();
  18334. auto status_line = [&](const std::string &host_lines) {
  18335. std::string res;
  18336. send_request(
  18337. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18338. &res, port);
  18339. return res.substr(0, res.find("\r\n"));
  18340. };
  18341. const char *accepted[] = {
  18342. "Host: localhost\r\n",
  18343. "Host: a.example:8080\r\n",
  18344. "Host: my_service\r\n",
  18345. "Host: [::1]:8080\r\n",
  18346. "Host: [fe80::1%25eth0]\r\n",
  18347. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18348. };
  18349. for (auto host_lines : accepted) {
  18350. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18351. }
  18352. const char *rejected[] = {
  18353. "Host: a.example\r\nHost: b.example\r\n",
  18354. "Host: a.example\r\nHost: a.example\r\n",
  18355. "Host: a@b.example\r\n",
  18356. "Host: a.example/b\r\n",
  18357. "Host: a.example\\b\r\n",
  18358. "Host: a.example?b\r\n",
  18359. "Host: a.example#b\r\n",
  18360. "Host: a.example b.example\r\n",
  18361. };
  18362. for (auto host_lines : rejected) {
  18363. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18364. << host_lines;
  18365. }
  18366. }
  18367. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18368. Server svr;
  18369. svr.Get("/", [](const Request &req, Response &res) {
  18370. EXPECT_EQ(2U, req.trailers.size());
  18371. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18372. // Denied
  18373. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18374. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18375. // Accepted
  18376. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18377. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18378. EXPECT_TRUE(req.has_trailer("X-World"));
  18379. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18380. res.set_content("ok", "text/plain");
  18381. });
  18382. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18383. auto se = detail::scope_exit([&] {
  18384. svr.stop();
  18385. t.join();
  18386. ASSERT_FALSE(svr.is_running());
  18387. });
  18388. svr.wait_until_ready();
  18389. const std::string req = "GET / HTTP/1.1\r\n"
  18390. "Transfer-Encoding: chunked\r\n"
  18391. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18392. "\r\n"
  18393. "0\r\n"
  18394. "Content-Length: 10\r\n"
  18395. "Host: internal.local\r\n"
  18396. "Content-Type: malicious/content\r\n"
  18397. "Cookie: any\r\n"
  18398. "Set-Cookie: any\r\n"
  18399. "X-Forwarded-For: attacker.com\r\n"
  18400. "X-Real-Ip: 1.1.1.1\r\n"
  18401. "X-Hello: hello\r\n"
  18402. "X-World: world\r\n"
  18403. "\r\n";
  18404. std::string res;
  18405. ASSERT_TRUE(send_request(1, req, &res));
  18406. }
  18407. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18408. // several field lines, and the combined value is what has to be parsed. A
  18409. // Trailer field split across lines therefore declares every name it lists;
  18410. // reading only the first line silently drops the trailers the later lines
  18411. // declare. The prohibited-trailer filter still applies to every line.
  18412. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18413. Server svr;
  18414. size_t observed_trailer_count = 0;
  18415. std::string observed_hello;
  18416. std::string observed_world;
  18417. bool observed_content_length = true;
  18418. svr.Get("/", [&](const Request &req, Response &res) {
  18419. observed_trailer_count = req.trailers.size();
  18420. observed_hello = req.get_trailer_value("X-Hello");
  18421. observed_world = req.get_trailer_value("X-World");
  18422. observed_content_length = req.has_trailer("Content-Length");
  18423. res.set_content("ok", "text/plain");
  18424. });
  18425. auto port = svr.bind_to_any_port(HOST);
  18426. thread t = thread([&]() { svr.listen_after_bind(); });
  18427. auto se = detail::scope_exit([&] {
  18428. svr.stop();
  18429. t.join();
  18430. ASSERT_FALSE(svr.is_running());
  18431. });
  18432. svr.wait_until_ready();
  18433. const std::string req = "GET / HTTP/1.1\r\n"
  18434. "Host: localhost\r\n"
  18435. "Transfer-Encoding: chunked\r\n"
  18436. "Trailer: X-Hello\r\n"
  18437. "Trailer: X-World, Content-Length\r\n"
  18438. "\r\n"
  18439. "0\r\n"
  18440. "X-Hello: hello\r\n"
  18441. "X-World: world\r\n"
  18442. "Content-Length: 10\r\n"
  18443. "\r\n";
  18444. std::string res;
  18445. ASSERT_TRUE(send_request(1, req, &res, port));
  18446. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18447. // Accepted: both field lines contribute to the declared set
  18448. EXPECT_EQ(2U, observed_trailer_count);
  18449. EXPECT_EQ(observed_hello, "hello");
  18450. EXPECT_EQ(observed_world, "world");
  18451. // Denied: a prohibited name stays prohibited on a later field line
  18452. EXPECT_FALSE(observed_content_length);
  18453. }
  18454. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18455. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18456. // unbounded run of fields that are never declared, because the counter would
  18457. // only advance for declared fields.
  18458. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18459. Server svr;
  18460. bool handler_called = false;
  18461. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18462. handler_called = true;
  18463. res.set_content("ok", "text/plain");
  18464. });
  18465. auto port = svr.bind_to_any_port(HOST);
  18466. thread t = thread([&]() { svr.listen_after_bind(); });
  18467. auto se = detail::scope_exit([&] {
  18468. svr.stop();
  18469. t.join();
  18470. ASSERT_FALSE(svr.is_running());
  18471. });
  18472. svr.wait_until_ready();
  18473. // Declare nothing, then send far more undeclared trailer fields than the
  18474. // header-count limit. Parsing must stop and reject the request rather than
  18475. // read every line.
  18476. std::string req = "GET / HTTP/1.1\r\n"
  18477. "Transfer-Encoding: chunked\r\n"
  18478. "\r\n"
  18479. "0\r\n";
  18480. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18481. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18482. }
  18483. req += "\r\n";
  18484. std::string res;
  18485. ASSERT_TRUE(send_request(1, req, &res, port));
  18486. // The request is rejected before the handler runs.
  18487. EXPECT_FALSE(handler_called);
  18488. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18489. }
  18490. // The set of declared trailer names is capped so a peer cannot grow it without
  18491. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18492. // declared past the cap is not honored, even if the field is actually sent.
  18493. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18494. Server svr;
  18495. // One name inside the cap and one past it, so the test tracks the cap rather
  18496. // than a fixed count.
  18497. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18498. const std::string within_cap_name = "X-T-0";
  18499. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18500. bool observed_within_cap = false;
  18501. bool observed_past_cap = false;
  18502. svr.Get("/", [&](const Request &req, Response &res) {
  18503. observed_within_cap = req.has_trailer(within_cap_name);
  18504. observed_past_cap = req.has_trailer(past_cap_name);
  18505. res.set_content("ok", "text/plain");
  18506. });
  18507. auto port = svr.bind_to_any_port(HOST);
  18508. thread t = thread([&]() { svr.listen_after_bind(); });
  18509. auto se = detail::scope_exit([&] {
  18510. svr.stop();
  18511. t.join();
  18512. ASSERT_FALSE(svr.is_running());
  18513. });
  18514. svr.wait_until_ready();
  18515. // Declare more trailer names than the cap in a single Trailer field, then
  18516. // actually send the first (within the cap) and the last (past it).
  18517. std::string trailer_decl = "Trailer: ";
  18518. for (int i = 0; i < declared_count; i++) {
  18519. if (i != 0) { trailer_decl += ", "; }
  18520. trailer_decl += "X-T-" + std::to_string(i);
  18521. }
  18522. trailer_decl += "\r\n";
  18523. const std::string req = "GET / HTTP/1.1\r\n"
  18524. "Host: localhost\r\n"
  18525. "Transfer-Encoding: chunked\r\n" +
  18526. trailer_decl +
  18527. "\r\n"
  18528. "0\r\n" +
  18529. within_cap_name + ": a\r\n" + past_cap_name +
  18530. ": b\r\n"
  18531. "\r\n";
  18532. std::string res;
  18533. ASSERT_TRUE(send_request(1, req, &res, port));
  18534. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18535. // A name within the cap is honored; one declared past the cap is dropped.
  18536. EXPECT_TRUE(observed_within_cap);
  18537. EXPECT_FALSE(observed_past_cap);
  18538. }
  18539. // A direct client that is not listed in trusted_proxies must not be able to
  18540. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18541. // the peer address on the actual TCP connection determines whether the
  18542. // header is honored.
  18543. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18544. Server svr;
  18545. // Deliberately does NOT include the loopback address the test client
  18546. // actually connects from, so the direct connection is not a trusted proxy.
  18547. svr.set_trusted_proxies({"203.0.113.66"});
  18548. std::string observed_remote_addr;
  18549. svr.Get("/ip", [&](const Request &req, Response &res) {
  18550. observed_remote_addr = req.remote_addr;
  18551. res.set_content("ok", "text/plain");
  18552. });
  18553. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18554. auto se = detail::scope_exit([&] {
  18555. svr.stop();
  18556. t.join();
  18557. ASSERT_FALSE(svr.is_running());
  18558. });
  18559. svr.wait_until_ready();
  18560. Client cli(HOST, PORT);
  18561. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18563. EXPECT_EQ(StatusCode::OK_200, res->status);
  18564. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18565. // ignored entirely and the real connection-level address retained.
  18566. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18567. observed_remote_addr == "127.0.0.1");
  18568. }
  18569. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18570. Server svr;
  18571. std::string observed_remote_addr;
  18572. std::string observed_xff;
  18573. svr.Get("/ip", [&](const Request &req, Response &res) {
  18574. observed_remote_addr = req.remote_addr;
  18575. observed_xff = req.get_header_value("X-Forwarded-For");
  18576. res.set_content("ok", "text/plain");
  18577. });
  18578. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18579. auto se = detail::scope_exit([&] {
  18580. svr.stop();
  18581. t.join();
  18582. ASSERT_FALSE(svr.is_running());
  18583. });
  18584. svr.wait_until_ready();
  18585. Client cli(HOST, PORT);
  18586. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18588. EXPECT_EQ(StatusCode::OK_200, res->status);
  18589. EXPECT_EQ(observed_xff, "203.0.113.66");
  18590. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18591. observed_remote_addr == "127.0.0.1");
  18592. }
  18593. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18594. Server svr;
  18595. svr.set_trusted_proxies({"203.0.113.66"});
  18596. std::string observed_remote_addr;
  18597. std::string observed_xff;
  18598. svr.Get("/ip", [&](const Request &req, Response &res) {
  18599. observed_remote_addr = req.remote_addr;
  18600. observed_xff = req.get_header_value("X-Forwarded-For");
  18601. res.set_content("ok", "text/plain");
  18602. });
  18603. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18604. auto se = detail::scope_exit([&] {
  18605. svr.stop();
  18606. t.join();
  18607. ASSERT_FALSE(svr.is_running());
  18608. });
  18609. svr.wait_until_ready();
  18610. Client cli(HOST, PORT);
  18611. auto res = cli.Get("/ip");
  18612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18613. EXPECT_EQ(StatusCode::OK_200, res->status);
  18614. EXPECT_EQ(observed_xff, "");
  18615. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18616. observed_remote_addr == "127.0.0.1");
  18617. }
  18618. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18619. Server svr;
  18620. // Include the loopback address the test client actually connects from, so
  18621. // the direct connection itself is recognized as the trusted proxy hop.
  18622. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18623. std::string observed_remote_addr;
  18624. std::string observed_xff;
  18625. svr.Get("/ip", [&](const Request &req, Response &res) {
  18626. observed_remote_addr = req.remote_addr;
  18627. observed_xff = req.get_header_value("X-Forwarded-For");
  18628. res.set_content("ok", "text/plain");
  18629. });
  18630. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18631. auto se = detail::scope_exit([&] {
  18632. svr.stop();
  18633. t.join();
  18634. ASSERT_FALSE(svr.is_running());
  18635. });
  18636. svr.wait_until_ready();
  18637. Client cli(HOST, PORT);
  18638. auto res = cli.Get(
  18639. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18641. EXPECT_EQ(StatusCode::OK_200, res->status);
  18642. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18643. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18644. }
  18645. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18646. Server svr;
  18647. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18648. std::string observed_remote_addr;
  18649. std::string observed_xff;
  18650. svr.Get("/ip", [&](const Request &req, Response &res) {
  18651. observed_remote_addr = req.remote_addr;
  18652. observed_xff = req.get_header_value("X-Forwarded-For");
  18653. res.set_content("ok", "text/plain");
  18654. });
  18655. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18656. auto se = detail::scope_exit([&] {
  18657. svr.stop();
  18658. t.join();
  18659. ASSERT_FALSE(svr.is_running());
  18660. });
  18661. svr.wait_until_ready();
  18662. Client cli(HOST, PORT);
  18663. auto res = cli.Get(
  18664. "/ip",
  18665. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18667. EXPECT_EQ(StatusCode::OK_200, res->status);
  18668. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18669. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18670. }
  18671. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18672. Server svr;
  18673. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18674. std::string observed_remote_addr;
  18675. std::string observed_xff;
  18676. svr.Get("/ip", [&](const Request &req, Response &res) {
  18677. observed_remote_addr = req.remote_addr;
  18678. observed_xff = req.get_header_value("X-Forwarded-For");
  18679. res.set_content("ok", "text/plain");
  18680. });
  18681. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18682. auto se = detail::scope_exit([&] {
  18683. svr.stop();
  18684. t.join();
  18685. ASSERT_FALSE(svr.is_running());
  18686. });
  18687. svr.wait_until_ready();
  18688. Client cli(HOST, PORT);
  18689. auto res = cli.Get(
  18690. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18692. EXPECT_EQ(StatusCode::OK_200, res->status);
  18693. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18694. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18695. // and must not be selected.
  18696. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18697. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18698. }
  18699. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18700. Server svr;
  18701. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18702. std::string observed_remote_addr;
  18703. svr.Get("/ip", [&](const Request &req, Response &res) {
  18704. observed_remote_addr = req.remote_addr;
  18705. res.set_content("ok", "text/plain");
  18706. });
  18707. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18708. auto se = detail::scope_exit([&] {
  18709. svr.stop();
  18710. t.join();
  18711. ASSERT_FALSE(svr.is_running());
  18712. });
  18713. svr.wait_until_ready();
  18714. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18715. // a forged address and the trusted proxy's own address; the forged value must
  18716. // not win over the address the trusted proxy actually recorded.
  18717. Client cli(HOST, PORT);
  18718. auto res = cli.Get(
  18719. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18721. EXPECT_EQ(StatusCode::OK_200, res->status);
  18722. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18723. }
  18724. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18725. Server svr;
  18726. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18727. std::string observed_remote_addr;
  18728. std::string observed_xff;
  18729. svr.Get("/ip", [&](const Request &req, Response &res) {
  18730. observed_remote_addr = req.remote_addr;
  18731. observed_xff = req.get_header_value("X-Forwarded-For");
  18732. res.set_content("ok", "text/plain");
  18733. });
  18734. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18735. auto se = detail::scope_exit([&] {
  18736. svr.stop();
  18737. t.join();
  18738. ASSERT_FALSE(svr.is_running());
  18739. });
  18740. svr.wait_until_ready();
  18741. Client cli(HOST, PORT);
  18742. auto res = cli.Get(
  18743. "/ip",
  18744. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18746. EXPECT_EQ(StatusCode::OK_200, res->status);
  18747. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18748. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18749. }
  18750. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18751. Server svr;
  18752. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18753. std::string observed_remote_addr;
  18754. std::string observed_xff;
  18755. svr.Get("/ip", [&](const Request &req, Response &res) {
  18756. observed_remote_addr = req.remote_addr;
  18757. observed_xff = req.get_header_value("X-Forwarded-For");
  18758. res.set_content("ok", "text/plain");
  18759. });
  18760. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18761. auto se = detail::scope_exit([&] {
  18762. svr.stop();
  18763. t.join();
  18764. ASSERT_FALSE(svr.is_running());
  18765. });
  18766. svr.wait_until_ready();
  18767. std::string raw_req =
  18768. "GET /ip HTTP/1.1\r\n"
  18769. "Host: localhost\r\n"
  18770. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18771. "Connection: close\r\n"
  18772. "\r\n";
  18773. std::string out;
  18774. ASSERT_TRUE(send_request(5, raw_req, &out));
  18775. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18776. // Header parser trims surrounding whitespace of the header value
  18777. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18778. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18779. }
  18780. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18781. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18782. // their own X-Forwarded-For as a separate field line rather than extending the
  18783. // one the client sent, so every occurrence has to be taken into account.
  18784. // Reading only the first one hands back the address the client chose.
  18785. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18786. Server svr;
  18787. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18788. std::string observed_remote_addr;
  18789. size_t observed_xff_count = 0;
  18790. svr.Get("/ip", [&](const Request &req, Response &res) {
  18791. observed_remote_addr = req.remote_addr;
  18792. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18793. res.set_content("ok", "text/plain");
  18794. });
  18795. auto port = svr.bind_to_any_port(HOST);
  18796. thread t = thread([&]() { svr.listen_after_bind(); });
  18797. auto se = detail::scope_exit([&] {
  18798. svr.stop();
  18799. t.join();
  18800. ASSERT_FALSE(svr.is_running());
  18801. });
  18802. svr.wait_until_ready();
  18803. // The client supplies the first field line; the trusted proxy appends the
  18804. // address it observed as a second one.
  18805. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18806. "Host: localhost\r\n"
  18807. "X-Forwarded-For: 1.2.3.4\r\n"
  18808. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18809. "Connection: close\r\n"
  18810. "\r\n";
  18811. std::string out;
  18812. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18813. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18814. EXPECT_EQ(observed_xff_count, 2U);
  18815. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18816. // The same chain spread over one field line per hop derives the same client
  18817. // address, i.e. the split and the comma-joined representations agree.
  18818. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18819. "Host: localhost\r\n"
  18820. "X-Forwarded-For: 1.2.3.4\r\n"
  18821. "X-Forwarded-For: 198.51.100.23\r\n"
  18822. "X-Forwarded-For: 192.0.2.45\r\n"
  18823. "Connection: close\r\n"
  18824. "\r\n";
  18825. out.clear();
  18826. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18827. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18828. EXPECT_EQ(observed_xff_count, 3U);
  18829. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18830. }
  18831. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18832. // crash the server (it used to call front() on an empty vector inside
  18833. // get_client_ip). The connection-level remote address must be retained instead.
  18834. static void run_malformed_xff_test(const std::string &xff_value) {
  18835. Server svr;
  18836. svr.set_trusted_proxies({"192.0.2.45"});
  18837. std::string observed_remote_addr;
  18838. svr.Get("/ip", [&](const Request &req, Response &res) {
  18839. observed_remote_addr = req.remote_addr;
  18840. res.set_content("ok", "text/plain");
  18841. });
  18842. int port = 0;
  18843. thread t = thread([&]() {
  18844. port = svr.bind_to_any_port(HOST);
  18845. svr.listen_after_bind();
  18846. });
  18847. auto se = detail::scope_exit([&] {
  18848. svr.stop();
  18849. t.join();
  18850. ASSERT_FALSE(svr.is_running());
  18851. });
  18852. svr.wait_until_ready();
  18853. Client cli(HOST, port);
  18854. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18856. EXPECT_EQ(StatusCode::OK_200, res->status);
  18857. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18858. observed_remote_addr == "127.0.0.1");
  18859. }
  18860. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18861. run_malformed_xff_test("");
  18862. }
  18863. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18864. run_malformed_xff_test(",");
  18865. }
  18866. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18867. run_malformed_xff_test(", , ,");
  18868. }
  18869. // The same rule applies to Accept: a request whose acceptable types are spread
  18870. // over several field lines must be negotiated against all of them.
  18871. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18872. // case-insensitive connection options. Comparing the whole field value against
  18873. // one option misses a client that sends several of them, and misses every
  18874. // casing but the one written in the comparison.
  18875. //
  18876. // Sends req, reads the response, then reuses the same socket for a second
  18877. // request to find out whether the server kept the connection.
  18878. static void probe_connection_reuse(int port, const std::string &req,
  18879. bool *announced_close, bool *reusable) {
  18880. auto error = Error::Success;
  18881. auto sock = detail::create_client_socket(
  18882. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18883. /*connection_timeout_sec=*/5, 0,
  18884. /*read_timeout_sec=*/1, 0,
  18885. /*write_timeout_sec=*/5, 0, std::string(), error);
  18886. ASSERT_NE(sock, INVALID_SOCKET);
  18887. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18888. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18889. "Host: localhost\r\n"
  18890. "Connection: close\r\n"
  18891. "\r\n";
  18892. std::string first_response;
  18893. std::string second_response;
  18894. detail::process_client_socket(
  18895. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18896. [&](Stream &strm) {
  18897. if (strm.write(req.data(), req.size()) !=
  18898. static_cast<ssize_t>(req.size())) {
  18899. return false;
  18900. }
  18901. char buf[512];
  18902. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18903. // Headers plus the two-byte body of the handler below
  18904. while (reader.getline()) {
  18905. first_response += reader.ptr();
  18906. if (first_response.find("ok") != std::string::npos) { break; }
  18907. }
  18908. if (strm.write(second.data(), second.size()) !=
  18909. static_cast<ssize_t>(second.size())) {
  18910. return true;
  18911. }
  18912. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18913. while (reader2.getline()) {
  18914. second_response += reader2.ptr();
  18915. if (second_response.find("ok") != std::string::npos) { break; }
  18916. }
  18917. return true;
  18918. });
  18919. *announced_close =
  18920. first_response.find("Connection: close") != std::string::npos;
  18921. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18922. }
  18923. class ConnectionTokenTest : public ::testing::Test {
  18924. protected:
  18925. void SetUp() override {
  18926. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18927. res.set_content("ok", "text/plain");
  18928. });
  18929. port_ = svr_.bind_to_any_port(HOST);
  18930. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18931. svr_.wait_until_ready();
  18932. }
  18933. void TearDown() override {
  18934. svr_.stop();
  18935. if (thread_.joinable()) { thread_.join(); }
  18936. }
  18937. Server svr_;
  18938. int port_ = 0;
  18939. thread thread_;
  18940. };
  18941. // "close" alongside another option still closes the connection, and the
  18942. // response says so rather than leaving the peer to discover it.
  18943. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18944. bool announced_close = false;
  18945. bool reusable = true;
  18946. probe_connection_reuse(port_,
  18947. "GET /keepalive HTTP/1.1\r\n"
  18948. "Host: localhost\r\n"
  18949. "Connection: keep-alive, close\r\n"
  18950. "\r\n",
  18951. &announced_close, &reusable);
  18952. EXPECT_TRUE(announced_close);
  18953. EXPECT_FALSE(reusable);
  18954. }
  18955. // "close" split over two field lines is the same list, so it is honored too.
  18956. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18957. bool announced_close = false;
  18958. bool reusable = true;
  18959. probe_connection_reuse(port_,
  18960. "GET /keepalive HTTP/1.1\r\n"
  18961. "Host: localhost\r\n"
  18962. "Connection: keep-alive\r\n"
  18963. "Connection: close\r\n"
  18964. "\r\n",
  18965. &announced_close, &reusable);
  18966. EXPECT_TRUE(announced_close);
  18967. EXPECT_FALSE(reusable);
  18968. }
  18969. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18970. // keep-alive in the spelling everyone actually sends keeps its connection.
  18971. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18972. bool announced_close = false;
  18973. bool reusable = false;
  18974. probe_connection_reuse(port_,
  18975. "GET /keepalive HTTP/1.0\r\n"
  18976. "Host: localhost\r\n"
  18977. "Connection: keep-alive\r\n"
  18978. "\r\n",
  18979. &announced_close, &reusable);
  18980. EXPECT_FALSE(announced_close);
  18981. EXPECT_TRUE(reusable);
  18982. }
  18983. // A token the value merely contains is not the token itself.
  18984. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18985. bool announced_close = false;
  18986. bool reusable = false;
  18987. probe_connection_reuse(port_,
  18988. "GET /keepalive HTTP/1.1\r\n"
  18989. "Host: localhost\r\n"
  18990. "Connection: notclose\r\n"
  18991. "\r\n",
  18992. &announced_close, &reusable);
  18993. EXPECT_FALSE(announced_close);
  18994. EXPECT_TRUE(reusable);
  18995. }
  18996. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18997. Server svr;
  18998. std::vector<std::string> observed_types;
  18999. svr.Get("/", [&](const Request &req, Response &res) {
  19000. observed_types = req.accept_content_types;
  19001. res.set_content("ok", "text/plain");
  19002. });
  19003. auto port = svr.bind_to_any_port(HOST);
  19004. thread t = thread([&]() { svr.listen_after_bind(); });
  19005. auto se = detail::scope_exit([&] {
  19006. svr.stop();
  19007. t.join();
  19008. ASSERT_FALSE(svr.is_running());
  19009. });
  19010. svr.wait_until_ready();
  19011. Client cli(HOST, port);
  19012. Headers headers;
  19013. headers.emplace("Accept", "text/plain;q=0.5");
  19014. headers.emplace("Accept", "application/json");
  19015. auto res = cli.Get("/", headers);
  19016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19017. EXPECT_EQ(StatusCode::OK_200, res->status);
  19018. // Sorted by q-value, so the second field line's type comes first
  19019. ASSERT_EQ(2U, observed_types.size());
  19020. EXPECT_EQ("application/json", observed_types[0]);
  19021. EXPECT_EQ("text/plain", observed_types[1]);
  19022. }
  19023. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19024. // empty field line must not contribute a bare comma to the combined value.
  19025. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19026. Server svr;
  19027. std::vector<std::string> observed_types;
  19028. svr.Get("/", [&](const Request &req, Response &res) {
  19029. observed_types = req.accept_content_types;
  19030. res.set_content("ok", "text/plain");
  19031. });
  19032. auto port = svr.bind_to_any_port(HOST);
  19033. thread t = thread([&]() { svr.listen_after_bind(); });
  19034. auto se = detail::scope_exit([&] {
  19035. svr.stop();
  19036. t.join();
  19037. ASSERT_FALSE(svr.is_running());
  19038. });
  19039. svr.wait_until_ready();
  19040. // Empty first field line, then a real one
  19041. std::string raw_req = "GET / HTTP/1.1\r\n"
  19042. "Host: localhost\r\n"
  19043. "Accept:\r\n"
  19044. "Accept: application/json\r\n"
  19045. "Connection: close\r\n"
  19046. "\r\n";
  19047. std::string out;
  19048. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19049. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19050. ASSERT_EQ(1U, observed_types.size());
  19051. EXPECT_EQ("application/json", observed_types[0]);
  19052. }
  19053. // The skip in get_combined_header_value() is what keeps an empty field line
  19054. // from contributing a bare comma. Only a trailing empty field line exercises
  19055. // it: a leading one is already covered by the "combined is still empty" check,
  19056. // and parse_accept_header() now ignores the empty element either way, so the
  19057. // request-level test above can no longer tell the two apart.
  19058. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19059. Headers headers;
  19060. headers.emplace("Accept", "text/html");
  19061. headers.emplace("Accept", "");
  19062. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19063. headers.clear();
  19064. headers.emplace("Accept", "");
  19065. headers.emplace("Accept", "application/json");
  19066. EXPECT_EQ("application/json",
  19067. detail::get_combined_header_value(headers, "Accept"));
  19068. }
  19069. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19070. // An encoding offered on a later Accept-Encoding field line is still offered.
  19071. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19072. Server svr;
  19073. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19074. res.set_content(std::string(1024, 'x'), "text/plain");
  19075. });
  19076. auto port = svr.bind_to_any_port(HOST);
  19077. thread t = thread([&]() { svr.listen_after_bind(); });
  19078. auto se = detail::scope_exit([&] {
  19079. svr.stop();
  19080. t.join();
  19081. ASSERT_FALSE(svr.is_running());
  19082. });
  19083. svr.wait_until_ready();
  19084. Client cli(HOST, port);
  19085. cli.set_decompress(false);
  19086. Headers headers;
  19087. headers.emplace("Accept-Encoding", "identity");
  19088. headers.emplace("Accept-Encoding", "gzip");
  19089. auto res = cli.Get("/", headers);
  19090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19091. EXPECT_EQ(StatusCode::OK_200, res->status);
  19092. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19093. }
  19094. #endif
  19095. #ifndef _WIN32
  19096. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19097. Server svr;
  19098. svr.Post("/post", [&](const Request &req, Response &res) {
  19099. res.set_content(req.body, "text/plain");
  19100. });
  19101. svr.Put("/put", [&](const Request &req, Response &res) {
  19102. res.set_content(req.body, "text/plain");
  19103. });
  19104. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19105. res.set_content(req.body, "text/plain");
  19106. });
  19107. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19108. res.set_content(req.body, "text/plain");
  19109. });
  19110. thread t = thread([&]() { svr.listen(HOST, PORT); });
  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. std::string resp;
  19118. // POST without Content-Length
  19119. ASSERT_TRUE(send_request(5,
  19120. "POST /post HTTP/1.1\r\n"
  19121. "Host: localhost\r\n"
  19122. "Connection: close\r\n"
  19123. "\r\n",
  19124. &resp));
  19125. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19126. // PUT without Content-Length
  19127. resp.clear();
  19128. ASSERT_TRUE(send_request(5,
  19129. "PUT /put HTTP/1.1\r\n"
  19130. "Host: localhost\r\n"
  19131. "Connection: close\r\n"
  19132. "\r\n",
  19133. &resp));
  19134. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19135. // PATCH without Content-Length
  19136. resp.clear();
  19137. ASSERT_TRUE(send_request(5,
  19138. "PATCH /patch HTTP/1.1\r\n"
  19139. "Host: localhost\r\n"
  19140. "Connection: close\r\n"
  19141. "\r\n",
  19142. &resp));
  19143. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19144. // DELETE without Content-Length
  19145. resp.clear();
  19146. ASSERT_TRUE(send_request(5,
  19147. "DELETE /delete HTTP/1.1\r\n"
  19148. "Host: localhost\r\n"
  19149. "Connection: close\r\n"
  19150. "\r\n",
  19151. &resp));
  19152. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19153. }
  19154. #endif
  19155. //==============================================================================
  19156. // open_stream() Tests
  19157. //==============================================================================
  19158. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19159. std::string result;
  19160. char buf[8192];
  19161. ssize_t n;
  19162. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19163. result.append(buf, static_cast<size_t>(n));
  19164. }
  19165. return result;
  19166. }
  19167. // Mock stream for unit tests
  19168. class MockStream : public Stream {
  19169. public:
  19170. std::string data;
  19171. size_t pos = 0;
  19172. ssize_t error_after = -1; // -1 = no error
  19173. explicit MockStream(const std::string &d, ssize_t err = -1)
  19174. : data(d), error_after(err) {}
  19175. bool is_readable() const override { return true; }
  19176. bool wait_readable() const override { return true; }
  19177. bool wait_writable() const override { return true; }
  19178. ssize_t read(char *ptr, size_t size) override {
  19179. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19180. if (pos >= data.size()) return 0;
  19181. size_t limit =
  19182. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19183. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19184. std::memcpy(ptr, data.data() + pos, to_read);
  19185. pos += to_read;
  19186. return static_cast<ssize_t>(to_read);
  19187. }
  19188. ssize_t write(const char *, size_t) override { return -1; }
  19189. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19190. ip = "127.0.0.1";
  19191. port = 0;
  19192. }
  19193. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19194. ip = "127.0.0.1";
  19195. port = 0;
  19196. }
  19197. socket_t socket() const override { return INVALID_SOCKET; }
  19198. time_t duration() const override { return 0; }
  19199. };
  19200. TEST(StreamHandleTest, Basic) {
  19201. ClientImpl::StreamHandle handle;
  19202. EXPECT_FALSE(handle.is_valid());
  19203. handle.response = detail::make_unique<Response>();
  19204. handle.error = Error::Connection;
  19205. EXPECT_FALSE(handle.is_valid());
  19206. handle.error = Error::Success;
  19207. EXPECT_TRUE(handle.is_valid());
  19208. }
  19209. TEST(BodyReaderTest, Basic) {
  19210. MockStream stream("Hello, World!");
  19211. detail::BodyReader reader;
  19212. reader.stream = &stream;
  19213. reader.content_length = 13;
  19214. char buf[32];
  19215. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19216. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19217. EXPECT_TRUE(reader.eof);
  19218. }
  19219. TEST(BodyReaderTest, NoStream) {
  19220. detail::BodyReader reader;
  19221. char buf[32];
  19222. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19223. EXPECT_EQ(Error::Connection, reader.last_error);
  19224. }
  19225. TEST(BodyReaderTest, Error) {
  19226. MockStream stream("Hello, World!", 5);
  19227. detail::BodyReader reader;
  19228. reader.stream = &stream;
  19229. reader.content_length = 13;
  19230. char buf[32];
  19231. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19232. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19233. EXPECT_EQ(Error::Read, reader.last_error);
  19234. }
  19235. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19236. // Mock-based StreamHandle tests relying on private internals are removed.
  19237. class OpenStreamTest : public ::testing::Test {
  19238. protected:
  19239. void SetUp() override {
  19240. svr_.Get("/hello", [](const Request &, Response &res) {
  19241. res.set_content("Hello World!", "text/plain");
  19242. });
  19243. svr_.Get("/large", [](const Request &, Response &res) {
  19244. res.set_content(std::string(10000, 'X'), "text/plain");
  19245. });
  19246. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19247. res.set_content("Hello World!", "image/jpeg");
  19248. res.set_header("Content-Encoding", "UTF-8");
  19249. });
  19250. svr_.Get("/chunked", [](const Request &, Response &res) {
  19251. res.set_chunked_content_provider("text/plain",
  19252. [](size_t offset, DataSink &sink) {
  19253. if (offset < 15) {
  19254. sink.write("chunk", 5);
  19255. return true;
  19256. }
  19257. sink.done();
  19258. return true;
  19259. });
  19260. });
  19261. svr_.Get("/compressible", [](const Request &, Response &res) {
  19262. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19263. DataSink &sink) {
  19264. if (offset < 100 * 1024) {
  19265. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19266. sink.write(chunk.data(), chunk.size());
  19267. return true;
  19268. }
  19269. sink.done();
  19270. return true;
  19271. });
  19272. });
  19273. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19274. [](const Request & /*req*/, Response &res) {
  19275. auto i = new int(0);
  19276. res.set_header("Trailer", "Content-Length, X-Allowed");
  19277. res.set_chunked_content_provider(
  19278. "text/plain",
  19279. [i](size_t /*offset*/, DataSink &sink) {
  19280. switch (*i) {
  19281. case 0: sink.os << "123"; break;
  19282. case 1: sink.os << "456"; break;
  19283. case 2: sink.os << "789"; break;
  19284. case 3: {
  19285. sink.done_with_trailer(
  19286. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19287. } break;
  19288. }
  19289. (*i)++;
  19290. return true;
  19291. },
  19292. [i](bool success) {
  19293. EXPECT_TRUE(success);
  19294. delete i;
  19295. });
  19296. });
  19297. // Echo headers endpoint for header-related tests
  19298. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19299. std::string body;
  19300. for (const auto &h : req.headers) {
  19301. body.append(h.first);
  19302. body.push_back(':');
  19303. body.append(h.second);
  19304. body.push_back('\n');
  19305. }
  19306. res.set_content(body, "text/plain");
  19307. });
  19308. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19309. std::string body;
  19310. for (const auto &h : req.headers) {
  19311. body.append(h.first);
  19312. body.push_back(':');
  19313. body.append(h.second);
  19314. body.push_back('\n');
  19315. }
  19316. res.set_content(body, "text/plain");
  19317. });
  19318. port_ = svr_.bind_to_any_port("127.0.0.1");
  19319. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19320. svr_.wait_until_ready();
  19321. }
  19322. void TearDown() override {
  19323. svr_.stop();
  19324. if (thread_.joinable()) thread_.join();
  19325. }
  19326. Server svr_;
  19327. std::thread thread_;
  19328. int port_ = 0;
  19329. };
  19330. TEST_F(OpenStreamTest, Basic) {
  19331. Client cli("127.0.0.1", port_);
  19332. auto handle = cli.open_stream("GET", "/hello");
  19333. EXPECT_TRUE(handle.is_valid());
  19334. EXPECT_EQ("Hello World!", read_all(handle));
  19335. }
  19336. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19337. Client cli("127.0.0.1", port_);
  19338. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19339. ASSERT_TRUE(handle.is_valid());
  19340. EXPECT_EQ("Hello World!", read_all(handle));
  19341. }
  19342. TEST_F(OpenStreamTest, SmallBuffer) {
  19343. Client cli("127.0.0.1", port_);
  19344. auto handle = cli.open_stream("GET", "/hello");
  19345. std::string result;
  19346. char buf[4];
  19347. ssize_t n;
  19348. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19349. result.append(buf, static_cast<size_t>(n));
  19350. EXPECT_EQ("Hello World!", result);
  19351. }
  19352. TEST_F(OpenStreamTest, DefaultHeaders) {
  19353. Client cli("127.0.0.1", port_);
  19354. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19355. {
  19356. auto handle = cli.open_stream("GET", "/echo-headers");
  19357. ASSERT_TRUE(handle.is_valid());
  19358. auto body = read_all(handle);
  19359. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19360. std::string::npos);
  19361. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19362. std::string::npos);
  19363. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19364. }
  19365. // open_stream POST with body and no explicit content_type should NOT add
  19366. // text/plain Content-Type (behavior differs from non-streaming path), but
  19367. // should include Content-Length
  19368. {
  19369. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19370. ASSERT_TRUE(handle.is_valid());
  19371. auto body = read_all(handle);
  19372. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19373. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19374. }
  19375. // open_stream POST with explicit Content-Type should preserve it
  19376. {
  19377. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19378. {{"Content-Type", "application/custom"}},
  19379. "{}", "application/custom");
  19380. ASSERT_TRUE(handle.is_valid());
  19381. auto body = read_all(handle);
  19382. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19383. }
  19384. // User-specified User-Agent must not be overwritten for stream API
  19385. {
  19386. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19387. {{"User-Agent", "MyAgent/1.2"}});
  19388. ASSERT_TRUE(handle.is_valid());
  19389. auto body = read_all(handle);
  19390. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19391. }
  19392. }
  19393. TEST_F(OpenStreamTest, Large) {
  19394. Client cli("127.0.0.1", port_);
  19395. auto handle = cli.open_stream("GET", "/large");
  19396. EXPECT_EQ(10000u, read_all(handle).size());
  19397. }
  19398. TEST_F(OpenStreamTest, ConnectionError) {
  19399. Client cli("127.0.0.1", 9999);
  19400. auto handle = cli.open_stream("GET", "/hello");
  19401. EXPECT_FALSE(handle.is_valid());
  19402. }
  19403. TEST_F(OpenStreamTest, Chunked) {
  19404. Client cli("127.0.0.1", port_);
  19405. auto handle = cli.open_stream("GET", "/chunked");
  19406. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19407. "Transfer-Encoding") == "chunked");
  19408. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19409. }
  19410. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19411. Client cli("127.0.0.1", port_);
  19412. auto handle =
  19413. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19414. ASSERT_TRUE(handle.is_valid());
  19415. // Consume body to allow trailers to be received/parsed
  19416. auto body = read_all(handle);
  19417. // Explicitly parse trailers (ensure trailers are available for assertion)
  19418. handle.parse_trailers_if_needed();
  19419. EXPECT_EQ(std::string("123456789"), body);
  19420. // The response should include a Trailer header declaring both names
  19421. ASSERT_TRUE(handle.response);
  19422. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19423. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19424. handle.response->get_header_value("Trailer"));
  19425. // Prohibited trailer must not be present
  19426. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19427. // Allowed trailer should be present
  19428. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19429. EXPECT_EQ(std::string("yes"),
  19430. handle.response->get_trailer_value("X-Allowed"));
  19431. // Verify trailers are NOT present as regular headers
  19432. EXPECT_EQ(std::string(""),
  19433. handle.response->get_header_value("Content-Length"));
  19434. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19435. }
  19436. // Accepts one connection on an OS-assigned port, which it hands over through
  19437. // port_promise, reads the request head and sends back response. after_send,
  19438. // if given, runs on the connection before it is closed.
  19439. static std::thread
  19440. serve_single_response(std::promise<int> &port_promise,
  19441. const std::string &response,
  19442. std::function<void(socket_t)> after_send = nullptr) {
  19443. return std::thread([&port_promise, response, after_send] {
  19444. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19445. default_socket_options(srv);
  19446. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19447. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19448. sockaddr_in addr{};
  19449. addr.sin_family = AF_INET;
  19450. addr.sin_port = htons(0); // Let OS assign a free port
  19451. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19452. int opt = 1;
  19453. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19454. #ifdef _WIN32
  19455. reinterpret_cast<const char *>(&opt),
  19456. #else
  19457. &opt,
  19458. #endif
  19459. sizeof(opt));
  19460. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19461. ::listen(srv, 1) != 0) {
  19462. port_promise.set_value(-1);
  19463. detail::close_socket(srv);
  19464. return;
  19465. }
  19466. socklen_t addr_len = sizeof(addr);
  19467. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19468. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19469. sockaddr_in cli_addr{};
  19470. socklen_t cli_len = sizeof(cli_addr);
  19471. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19472. if (cli != INVALID_SOCKET) {
  19473. // Read the complete HTTP request (until the blank line that terminates
  19474. // headers) before sending the response. If the server closes the socket
  19475. // while the client's request data is still unread in the kernel receive
  19476. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19477. // connection on both sides: it discards the client's receive buffer
  19478. // (which already holds our response) and causes any in-progress write on
  19479. // the client to fail with ECONNRESET. Reading all request data first
  19480. // ensures close() emits a graceful FIN.
  19481. {
  19482. char rbuf[256];
  19483. std::string req;
  19484. while (req.find("\r\n\r\n") == std::string::npos) {
  19485. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19486. if (n <= 0) { break; }
  19487. req.append(rbuf, static_cast<size_t>(n));
  19488. }
  19489. }
  19490. ::send(cli,
  19491. #ifdef _WIN32
  19492. static_cast<const char *>(response.c_str()),
  19493. static_cast<int>(response.size()),
  19494. #else
  19495. response.c_str(), response.size(),
  19496. #endif
  19497. 0);
  19498. if (after_send) { after_send(cli); }
  19499. detail::close_socket(cli);
  19500. }
  19501. detail::close_socket(srv);
  19502. });
  19503. }
  19504. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19505. #ifndef _WIN32
  19506. signal(SIGPIPE, SIG_IGN);
  19507. #endif
  19508. std::promise<int> port_promise;
  19509. auto port_future = port_promise.get_future();
  19510. auto server_thread =
  19511. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19512. "Content-Type: text/plain\r\n"
  19513. "Content-Length: not-a-number\r\n"
  19514. "Connection: close\r\n"
  19515. "\r\n"
  19516. "hello");
  19517. auto port = port_future.get();
  19518. ASSERT_GT(port, 0);
  19519. Client cli("127.0.0.1", port);
  19520. auto handle = cli.open_stream("GET", "/");
  19521. EXPECT_FALSE(handle.is_valid());
  19522. server_thread.join();
  19523. }
  19524. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19525. #ifndef _WIN32
  19526. signal(SIGPIPE, SIG_IGN);
  19527. #endif
  19528. std::promise<int> port_promise;
  19529. auto port_future = port_promise.get_future();
  19530. auto server_thread = serve_single_response(
  19531. port_promise, "HTTP/1.1 200 OK\r\n"
  19532. "Content-Type: text/plain\r\n"
  19533. "Content-Length: 99999999999999999999999999\r\n"
  19534. "Connection: close\r\n"
  19535. "\r\n"
  19536. "hello");
  19537. auto port = port_future.get();
  19538. ASSERT_GT(port, 0);
  19539. // Historically std::stoull would throw std::out_of_range here and crash
  19540. // the process, then parsing silently clamped to a bogus framing length and
  19541. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19542. // so the stream fails to open, matching the not-a-number case above. The
  19543. // process still must NOT terminate.
  19544. Client cli("127.0.0.1", port);
  19545. auto handle = cli.open_stream("GET", "/");
  19546. EXPECT_FALSE(handle.is_valid());
  19547. server_thread.join();
  19548. }
  19549. // Serves `response` to the single request `fn` makes with a fresh client.
  19550. template <typename Fn>
  19551. static void with_single_response(const std::string &response, Fn fn) {
  19552. #ifndef _WIN32
  19553. signal(SIGPIPE, SIG_IGN);
  19554. #endif
  19555. std::promise<int> port_promise;
  19556. auto port_future = port_promise.get_future();
  19557. auto server_thread = serve_single_response(port_promise, response);
  19558. auto se = detail::scope_exit([&] { server_thread.join(); });
  19559. auto port = port_future.get();
  19560. ASSERT_GT(port, 0);
  19561. Client cli("127.0.0.1", port);
  19562. fn(cli);
  19563. }
  19564. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19565. // Neither Content-Length nor chunked: the body ends at the close
  19566. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19567. "Connection: close\r\n"
  19568. "\r\n"
  19569. "hello";
  19570. with_single_response(close_delimited, [](Client &cli) {
  19571. auto handle = cli.open_stream("GET", "/");
  19572. ASSERT_TRUE(handle.is_valid());
  19573. EXPECT_EQ("hello", read_all(handle));
  19574. EXPECT_FALSE(handle.has_read_error());
  19575. });
  19576. // A close before the end of the Content-Length is still an error
  19577. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19578. "Content-Length: 10\r\n"
  19579. "\r\n"
  19580. "hello";
  19581. with_single_response(short_content_length, [](Client &cli) {
  19582. auto handle = cli.open_stream("GET", "/");
  19583. ASSERT_TRUE(handle.is_valid());
  19584. read_all(handle);
  19585. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19586. });
  19587. // So is a close before the last chunk
  19588. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19589. "Transfer-Encoding: chunked\r\n"
  19590. "\r\n"
  19591. "5\r\nhello\r\n";
  19592. with_single_response(short_chunked, [](Client &cli) {
  19593. auto handle = cli.open_stream("GET", "/");
  19594. ASSERT_TRUE(handle.is_valid());
  19595. read_all(handle);
  19596. EXPECT_TRUE(handle.has_read_error());
  19597. });
  19598. }
  19599. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19600. const char *responses[] = {
  19601. "HTTP/1.1 103 Early Hints\r\n"
  19602. "Link: </style.css>; rel=preload\r\n"
  19603. "\r\n"
  19604. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19605. "HTTP/1.1 100 Continue\r\n"
  19606. "X-Note: interim\r\n"
  19607. "\r\n"
  19608. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19609. };
  19610. for (auto response : responses) {
  19611. with_single_response(response, [](Client &cli) {
  19612. auto res = cli.Get("/");
  19613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19614. EXPECT_EQ(StatusCode::OK_200, res->status);
  19615. EXPECT_EQ("ok", res->body);
  19616. });
  19617. }
  19618. }
  19619. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19620. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19621. const std::string final_response =
  19622. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19623. std::string interims;
  19624. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19625. interims += interim;
  19626. }
  19627. with_single_response(interims + final_response, [](Client &cli) {
  19628. auto res = cli.Get("/");
  19629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19630. EXPECT_EQ("ok", res->body);
  19631. });
  19632. with_single_response(interims + interim + final_response, [](Client &cli) {
  19633. auto res = cli.Get("/");
  19634. ASSERT_FALSE(res);
  19635. EXPECT_EQ(Error::Read, res.error());
  19636. });
  19637. }
  19638. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19639. #ifndef _WIN32
  19640. signal(SIGPIPE, SIG_IGN);
  19641. #endif
  19642. // The server answers the head without asking for the body. Bytes it then
  19643. // reads on the connection would be taken for the body the request declared.
  19644. auto closed_by_client = false;
  19645. std::promise<int> port_promise;
  19646. auto server_thread = serve_single_response(
  19647. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19648. [&](socket_t sock) {
  19649. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19650. char buf[256];
  19651. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19652. });
  19653. Client cli("127.0.0.1", port_promise.get_future().get());
  19654. cli.set_keep_alive(true);
  19655. cli.set_read_timeout(1, 0);
  19656. // Long enough for the client to send Expect: 100-continue.
  19657. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19659. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19660. cli.Get("/second");
  19661. server_thread.join();
  19662. EXPECT_TRUE(closed_by_client);
  19663. }
  19664. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19665. // Long enough for the client to send Expect: 100-continue
  19666. with_single_response(
  19667. "HTTP/1.1 103 Early Hints\r\n"
  19668. "Link: </style.css>; rel=preload\r\n"
  19669. "\r\n"
  19670. "HTTP/1.1 401 Unauthorized\r\n"
  19671. "Content-Length: 0\r\n\r\n",
  19672. [](Client &cli) {
  19673. cli.set_read_timeout(2, 0);
  19674. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19676. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19677. });
  19678. }
  19679. #ifdef CPPHTTPLIB_SSL_ENABLED
  19680. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19681. #ifndef _WIN32
  19682. signal(SIGPIPE, SIG_IGN);
  19683. #endif
  19684. auto reused = false;
  19685. std::promise<int> port_promise;
  19686. auto server_thread = serve_single_response(
  19687. port_promise,
  19688. "HTTP/1.1 401 Unauthorized\r\n"
  19689. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19690. "Content-Length: 0\r\n\r\n",
  19691. [&](socket_t sock) {
  19692. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19693. char buf[256];
  19694. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19695. });
  19696. Client cli("127.0.0.1", port_promise.get_future().get());
  19697. cli.set_keep_alive(true);
  19698. cli.set_digest_auth("user", "pass");
  19699. cli.set_read_timeout(1, 0);
  19700. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19701. server_thread.join();
  19702. EXPECT_FALSE(reused);
  19703. }
  19704. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19705. // Any other answer to CONNECT would read as the origin's response.
  19706. struct {
  19707. const char *response;
  19708. bool passed_on;
  19709. } cases[] = {
  19710. {"HTTP/1.1 201 Created\r\n"
  19711. "Set-Cookie: session=from-proxy\r\n"
  19712. "Content-Length: 0\r\n\r\n",
  19713. false},
  19714. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19715. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19716. "Content-Length: 0\r\n\r\n",
  19717. true},
  19718. };
  19719. for (const auto &c : cases) {
  19720. std::promise<int> port_promise;
  19721. auto server_thread = serve_single_response(port_promise, c.response);
  19722. SSLClient cli("example.com", 443);
  19723. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19724. auto res = cli.Get("/");
  19725. server_thread.join();
  19726. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19727. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19728. if (res) {
  19729. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19730. }
  19731. }
  19732. }
  19733. #endif
  19734. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19735. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19736. // the chunked coding and drop Content-Length, so a front-end that trusts
  19737. // Content-Length would disagree about where the body ends (response
  19738. // smuggling). The client must reject such a response.
  19739. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19740. for (const char *te : {"chunked", "gzip, chunked"}) {
  19741. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19742. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19743. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19744. "5\r\nhello\r\n0\r\n\r\n";
  19745. with_single_response(response, [&](Client &cli) {
  19746. auto res = cli.Get("/");
  19747. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19748. EXPECT_EQ(Error::Read, res.error()) << te;
  19749. });
  19750. with_single_response(response, [&](Client &cli) {
  19751. auto handle = cli.open_stream("GET", "/");
  19752. EXPECT_FALSE(handle.is_valid()) << te;
  19753. EXPECT_EQ(Error::Read, handle.error) << te;
  19754. });
  19755. }
  19756. }
  19757. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19758. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19759. // closing the connection (unlike a request, which must be rejected).
  19760. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19761. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19762. "Transfer-Encoding: chunked\r\n"
  19763. "Connection: close\r\n"
  19764. "\r\n"
  19765. "5\r\nhello\r\n0\r\n\r\n",
  19766. "HTTP/1.1 200 OK\r\n"
  19767. "Transfer-Encoding: gzip\r\n"
  19768. "Connection: close\r\n"
  19769. "\r\n"
  19770. "hello"}) {
  19771. with_single_response(response, [&](Client &cli) {
  19772. auto res = cli.Get("/");
  19773. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19774. EXPECT_EQ("hello", res->body);
  19775. });
  19776. with_single_response(response, [&](Client &cli) {
  19777. auto handle = cli.open_stream("GET", "/");
  19778. ASSERT_TRUE(handle.is_valid()) << response;
  19779. EXPECT_EQ("hello", read_all(handle));
  19780. });
  19781. }
  19782. }
  19783. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19784. // framing headers describe nothing to read and must not be rejected.
  19785. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19786. const std::string framing = "Content-Length: 5\r\n"
  19787. "Transfer-Encoding: chunked\r\n"
  19788. "Connection: close\r\n"
  19789. "\r\n";
  19790. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19791. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19792. });
  19793. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19794. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19795. });
  19796. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19797. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19798. with_single_response(response, [&](Client &cli) {
  19799. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19800. });
  19801. with_single_response(response, [&](Client &cli) {
  19802. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19803. });
  19804. }
  19805. }
  19806. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19807. // response, is faulty framing, so the connection is not reused after it.
  19808. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19809. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19810. "Content-Length: 0\r\n"
  19811. "Transfer-Encoding: chunked\r\n"
  19812. "\r\n"
  19813. "5\r\nhello\r\n0\r\n\r\n",
  19814. "HTTP/1.0 200 Connection established\r\n"
  19815. "Connection: keep-alive\r\n"
  19816. "Transfer-Encoding: chunked\r\n"
  19817. "\r\n"
  19818. "5\r\nhello\r\n0\r\n\r\n"}) {
  19819. with_single_response(response, [&](Client &cli) {
  19820. cli.set_keep_alive(true);
  19821. auto res = cli.Get("/");
  19822. ASSERT_TRUE(res) << response;
  19823. EXPECT_EQ("hello", res->body);
  19824. EXPECT_FALSE(cli.is_socket_open()) << response;
  19825. });
  19826. }
  19827. }
  19828. // A payload max length of 0 means no limit, however the body is framed.
  19829. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19830. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19831. "Transfer-Encoding: chunked\r\n"
  19832. "\r\n"
  19833. "5\r\nhello\r\n0\r\n\r\n",
  19834. "HTTP/1.1 200 OK\r\n"
  19835. "Connection: close\r\n"
  19836. "\r\n"
  19837. "hello"}) {
  19838. with_single_response(response, [&](Client &cli) {
  19839. cli.set_payload_max_length(0);
  19840. auto res = cli.Get("/");
  19841. ASSERT_TRUE(res) << response;
  19842. EXPECT_EQ("hello", res->body) << response;
  19843. });
  19844. }
  19845. }
  19846. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19847. Server svr;
  19848. svr.set_payload_max_length(0);
  19849. svr.Post("/echo", [](const Request &req, Response &res) {
  19850. res.set_content(req.body, "text/plain");
  19851. });
  19852. auto port = svr.bind_to_any_port(HOST);
  19853. thread t = thread([&] { svr.listen_after_bind(); });
  19854. auto se = detail::scope_exit([&] {
  19855. svr.stop();
  19856. t.join();
  19857. ASSERT_FALSE(svr.is_running());
  19858. });
  19859. svr.wait_until_ready();
  19860. Client cli(HOST, port);
  19861. auto res = cli.Post(
  19862. "/echo",
  19863. [](size_t /*offset*/, DataSink &sink) {
  19864. sink.write("hello", 5);
  19865. sink.done();
  19866. return true;
  19867. },
  19868. "text/plain");
  19869. ASSERT_TRUE(res);
  19870. EXPECT_EQ(StatusCode::OK_200, res->status);
  19871. EXPECT_EQ("hello", res->body);
  19872. }
  19873. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19874. TEST_F(OpenStreamTest, Gzip) {
  19875. Client cli("127.0.0.1", port_);
  19876. auto handle = cli.open_stream("GET", "/compressible", {},
  19877. {{"Accept-Encoding", "gzip"}});
  19878. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19879. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19880. }
  19881. #endif
  19882. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19883. TEST_F(OpenStreamTest, Brotli) {
  19884. Client cli("127.0.0.1", port_);
  19885. auto handle =
  19886. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19887. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19888. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19889. }
  19890. #endif
  19891. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19892. TEST_F(OpenStreamTest, Zstd) {
  19893. Client cli("127.0.0.1", port_);
  19894. auto handle = cli.open_stream("GET", "/compressible", {},
  19895. {{"Accept-Encoding", "zstd"}});
  19896. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19897. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19898. }
  19899. #endif
  19900. #ifdef CPPHTTPLIB_SSL_ENABLED
  19901. class SSLOpenStreamTest : public ::testing::Test {
  19902. protected:
  19903. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19904. void SetUp() override {
  19905. svr_.Get("/hello", [](const Request &, Response &res) {
  19906. res.set_content("Hello SSL World!", "text/plain");
  19907. });
  19908. svr_.Get("/chunked", [](const Request &, Response &res) {
  19909. res.set_chunked_content_provider("text/plain",
  19910. [](size_t offset, DataSink &sink) {
  19911. if (offset < 15) {
  19912. sink.write("chunk", 5);
  19913. return true;
  19914. }
  19915. sink.done();
  19916. return true;
  19917. });
  19918. });
  19919. svr_.Post("/echo", [](const Request &req, Response &res) {
  19920. res.set_content(req.body, req.get_header_value("Content-Type"));
  19921. });
  19922. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19923. std::string body = req.body;
  19924. res.set_chunked_content_provider(
  19925. "text/plain", [body](size_t offset, DataSink &sink) {
  19926. if (offset < body.size()) {
  19927. sink.write(body.data() + offset, body.size() - offset);
  19928. }
  19929. sink.done();
  19930. return true;
  19931. });
  19932. });
  19933. port_ = svr_.bind_to_any_port("127.0.0.1");
  19934. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19935. svr_.wait_until_ready();
  19936. }
  19937. void TearDown() override {
  19938. svr_.stop();
  19939. if (thread_.joinable()) thread_.join();
  19940. }
  19941. SSLServer svr_;
  19942. std::thread thread_;
  19943. int port_ = 0;
  19944. };
  19945. TEST_F(SSLOpenStreamTest, Basic) {
  19946. SSLClient cli("127.0.0.1", port_);
  19947. cli.enable_server_certificate_verification(false);
  19948. auto handle = cli.open_stream("GET", "/hello");
  19949. ASSERT_TRUE(handle.is_valid());
  19950. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19951. }
  19952. TEST_F(SSLOpenStreamTest, Chunked) {
  19953. SSLClient cli("127.0.0.1", port_);
  19954. cli.enable_server_certificate_verification(false);
  19955. auto handle = cli.open_stream("GET", "/chunked");
  19956. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19957. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19958. "Transfer-Encoding") == "chunked");
  19959. auto body = read_all(handle);
  19960. EXPECT_EQ("chunkchunkchunk", body);
  19961. }
  19962. TEST_F(SSLOpenStreamTest, Post) {
  19963. SSLClient cli("127.0.0.1", port_);
  19964. cli.enable_server_certificate_verification(false);
  19965. auto handle =
  19966. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19967. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19968. EXPECT_EQ(200, handle.response->status);
  19969. auto body = read_all(handle);
  19970. EXPECT_EQ("Hello SSL POST", body);
  19971. }
  19972. TEST_F(SSLOpenStreamTest, PostChunked) {
  19973. SSLClient cli("127.0.0.1", port_);
  19974. cli.enable_server_certificate_verification(false);
  19975. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19976. "Chunked SSL Data", "text/plain");
  19977. ASSERT_TRUE(handle.is_valid());
  19978. EXPECT_EQ(200, handle.response->status);
  19979. auto body = read_all(handle);
  19980. EXPECT_EQ("Chunked SSL Data", body);
  19981. }
  19982. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19983. // Content-Length is terminated by the server closing the connection. When the
  19984. // SSL peer sends a close_notify after the body, the client must treat it as a
  19985. // clean EOF and return a successful response rather than an error.
  19986. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19987. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19988. ASSERT_TRUE(svr.is_valid());
  19989. svr.set_keep_alive_max_count(1);
  19990. const std::string expected_body = "Hello from connection-close response!";
  19991. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19992. res.set_content_provider("text/plain",
  19993. [&](size_t offset, DataSink &sink) -> bool {
  19994. if (offset < expected_body.size()) {
  19995. sink.write(expected_body.data() + offset,
  19996. expected_body.size() - offset);
  19997. }
  19998. sink.done();
  19999. return true;
  20000. });
  20001. });
  20002. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20003. auto se = detail::scope_exit([&] {
  20004. svr.stop();
  20005. listen_thread.join();
  20006. ASSERT_FALSE(svr.is_running());
  20007. });
  20008. svr.wait_until_ready();
  20009. SSLClient cli(HOST, PORT);
  20010. cli.enable_server_certificate_verification(false);
  20011. auto res = cli.Get("/no-content-length");
  20012. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20013. EXPECT_EQ(StatusCode::OK_200, res->status);
  20014. EXPECT_EQ(expected_body, res->body);
  20015. }
  20016. #endif // CPPHTTPLIB_SSL_ENABLED
  20017. //==============================================================================
  20018. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20019. // results for various scenarios.
  20020. //==============================================================================
  20021. TEST(ParityTest, GetVsOpenStream) {
  20022. Server svr;
  20023. const std::string path = "/parity";
  20024. const std::string content = "Parity test content: hello world";
  20025. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20026. res.set_content(content, "text/plain");
  20027. });
  20028. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20029. auto se = detail::scope_exit([&] {
  20030. svr.stop();
  20031. t.join();
  20032. ASSERT_FALSE(svr.is_running());
  20033. });
  20034. svr.wait_until_ready();
  20035. Client cli(HOST, PORT);
  20036. // Non-stream path
  20037. auto r1 = cli.Get(path);
  20038. ASSERT_TRUE(r1);
  20039. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20040. // Stream path
  20041. auto h = cli.open_stream("GET", path);
  20042. ASSERT_TRUE(h.is_valid());
  20043. EXPECT_EQ(r1->body, read_all(h));
  20044. }
  20045. // Helper to compress data with provided compressor type T
  20046. template <typename Compressor>
  20047. static std::string compress_payload_for_parity(const std::string &in) {
  20048. std::string out;
  20049. Compressor compressor;
  20050. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20051. [&](const char *data, size_t n) {
  20052. out.append(data, n);
  20053. return true;
  20054. });
  20055. EXPECT_TRUE(ok);
  20056. return out;
  20057. }
  20058. // Helper function for compression parity tests
  20059. template <typename Compressor>
  20060. static void test_compression_parity(const std::string &original,
  20061. const std::string &path,
  20062. const std::string &encoding) {
  20063. const std::string compressed =
  20064. compress_payload_for_parity<Compressor>(original);
  20065. Server svr;
  20066. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20067. res.set_content(compressed, "application/octet-stream");
  20068. res.set_header("Content-Encoding", encoding);
  20069. });
  20070. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20071. auto se = detail::scope_exit([&] {
  20072. svr.stop();
  20073. t.join();
  20074. ASSERT_FALSE(svr.is_running());
  20075. });
  20076. svr.wait_until_ready();
  20077. Client cli(HOST, PORT);
  20078. // Non-streaming
  20079. {
  20080. auto res = cli.Get(path);
  20081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20082. EXPECT_EQ(StatusCode::OK_200, res->status);
  20083. EXPECT_EQ(original, res->body);
  20084. }
  20085. // Streaming
  20086. {
  20087. auto h = cli.open_stream("GET", path);
  20088. ASSERT_TRUE(h.is_valid());
  20089. EXPECT_EQ(original, read_all(h));
  20090. }
  20091. }
  20092. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20093. TEST(ParityTest, Gzip) {
  20094. test_compression_parity<detail::gzip_compressor>(
  20095. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20096. }
  20097. #endif
  20098. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20099. TEST(ParityTest, Brotli) {
  20100. test_compression_parity<detail::brotli_compressor>(
  20101. "Hello, brotli parity test payload", "/parity-br", "br");
  20102. }
  20103. #endif
  20104. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20105. TEST(ParityTest, Zstd) {
  20106. test_compression_parity<detail::zstd_compressor>(
  20107. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20108. }
  20109. #endif
  20110. //==============================================================================
  20111. // New Stream API Tests
  20112. //==============================================================================
  20113. inline std::string read_body(httplib::stream::Result &result) {
  20114. std::string body;
  20115. while (result.next()) {
  20116. body.append(result.data(), result.size());
  20117. }
  20118. return body;
  20119. }
  20120. TEST(ClientConnectionTest, Basic) {
  20121. httplib::ClientConnection conn;
  20122. EXPECT_FALSE(conn.is_open());
  20123. conn.sock = 1;
  20124. EXPECT_TRUE(conn.is_open());
  20125. httplib::ClientConnection conn2(std::move(conn));
  20126. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20127. conn2.sock = INVALID_SOCKET;
  20128. }
  20129. // Unified test server for all stream::* tests
  20130. class StreamApiTest : public ::testing::Test {
  20131. protected:
  20132. void SetUp() override {
  20133. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20134. res.set_content("Hello World!", "text/plain");
  20135. });
  20136. svr_.Get("/echo-params",
  20137. [](const httplib::Request &req, httplib::Response &res) {
  20138. std::string r;
  20139. for (const auto &p : req.params) {
  20140. if (!r.empty()) r += "&";
  20141. r += p.first + "=" + p.second;
  20142. }
  20143. res.set_content(r, "text/plain");
  20144. });
  20145. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20146. res.set_content(req.body, req.get_header_value("Content-Type"));
  20147. });
  20148. svr_.Post("/echo-headers",
  20149. [](const httplib::Request &req, httplib::Response &res) {
  20150. std::string r;
  20151. for (const auto &h : req.headers)
  20152. r += h.first + ": " + h.second + "\n";
  20153. res.set_content(r, "text/plain");
  20154. });
  20155. svr_.Post("/echo-params",
  20156. [](const httplib::Request &req, httplib::Response &res) {
  20157. std::string r = "params:";
  20158. for (const auto &p : req.params)
  20159. r += p.first + "=" + p.second + ";";
  20160. res.set_content(r + " body:" + req.body, "text/plain");
  20161. });
  20162. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20163. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20164. });
  20165. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20166. res.set_content("PUT:" + req.body, "text/plain");
  20167. });
  20168. svr_.Patch("/echo",
  20169. [](const httplib::Request &req, httplib::Response &res) {
  20170. res.set_content("PATCH:" + req.body, "text/plain");
  20171. });
  20172. svr_.Delete(
  20173. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20174. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20175. "text/plain");
  20176. });
  20177. svr_.Get("/head-test",
  20178. [](const httplib::Request &, httplib::Response &res) {
  20179. res.set_content("body for HEAD", "text/plain");
  20180. });
  20181. svr_.Options("/options",
  20182. [](const httplib::Request &, httplib::Response &res) {
  20183. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20184. });
  20185. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20186. svr_.wait_until_ready();
  20187. }
  20188. void TearDown() override {
  20189. svr_.stop();
  20190. if (thread_.joinable()) thread_.join();
  20191. }
  20192. httplib::Server svr_;
  20193. std::thread thread_;
  20194. };
  20195. // stream::Get tests
  20196. TEST_F(StreamApiTest, GetBasic) {
  20197. httplib::Client cli(HOST, PORT);
  20198. auto result = httplib::stream::Get(cli, "/hello");
  20199. ASSERT_TRUE(result.is_valid());
  20200. EXPECT_EQ(200, result.status());
  20201. EXPECT_EQ("Hello World!", read_body(result));
  20202. }
  20203. TEST_F(StreamApiTest, GetWithParams) {
  20204. httplib::Client cli(HOST, PORT);
  20205. httplib::Params params{{"foo", "bar"}};
  20206. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20207. ASSERT_TRUE(result.is_valid());
  20208. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20209. }
  20210. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20211. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20212. httplib::Client cli(HOST, PORT);
  20213. cli.set_payload_max_length(0);
  20214. auto result = httplib::stream::Get(cli, "/hello");
  20215. ASSERT_TRUE(result.is_valid());
  20216. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20217. EXPECT_EQ("Hello World!", read_body(result));
  20218. }
  20219. #endif
  20220. TEST_F(StreamApiTest, GetConnectionError) {
  20221. httplib::Client cli(HOST, 9999);
  20222. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20223. }
  20224. TEST_F(StreamApiTest, Get404) {
  20225. httplib::Client cli(HOST, PORT);
  20226. auto result = httplib::stream::Get(cli, "/nonexistent");
  20227. EXPECT_TRUE(result.is_valid());
  20228. EXPECT_EQ(404, result.status());
  20229. }
  20230. // stream::Post tests
  20231. TEST_F(StreamApiTest, PostBasic) {
  20232. httplib::Client cli(HOST, PORT);
  20233. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20234. "application/json");
  20235. ASSERT_TRUE(result.is_valid());
  20236. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20237. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20238. }
  20239. TEST_F(StreamApiTest, PostWithHeaders) {
  20240. httplib::Client cli(HOST, PORT);
  20241. httplib::Headers headers{{"X-Custom", "value"}};
  20242. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20243. "text/plain");
  20244. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20245. }
  20246. TEST_F(StreamApiTest, PostWithParams) {
  20247. httplib::Client cli(HOST, PORT);
  20248. httplib::Params params{{"k", "v"}};
  20249. auto result =
  20250. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20251. auto body = read_body(result);
  20252. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20253. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20254. }
  20255. TEST_F(StreamApiTest, PostLarge) {
  20256. httplib::Client cli(HOST, PORT);
  20257. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20258. size_t total = 0;
  20259. while (result.next()) {
  20260. total += result.size();
  20261. }
  20262. EXPECT_EQ(100u * 1024u, total);
  20263. }
  20264. // stream::Put/Patch tests
  20265. TEST_F(StreamApiTest, PutAndPatch) {
  20266. httplib::Client cli(HOST, PORT);
  20267. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20268. EXPECT_EQ("PUT:test", read_body(put));
  20269. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20270. EXPECT_EQ("PATCH:test", read_body(patch));
  20271. }
  20272. // stream::Delete tests
  20273. TEST_F(StreamApiTest, Delete) {
  20274. httplib::Client cli(HOST, PORT);
  20275. auto del1 = httplib::stream::Delete(cli, "/resource");
  20276. EXPECT_EQ("Deleted", read_body(del1));
  20277. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20278. EXPECT_EQ("Deleted:data", read_body(del2));
  20279. }
  20280. // stream::Head/Options tests
  20281. TEST_F(StreamApiTest, HeadAndOptions) {
  20282. httplib::Client cli(HOST, PORT);
  20283. auto head = httplib::stream::Head(cli, "/head-test");
  20284. EXPECT_TRUE(head.is_valid());
  20285. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20286. auto opts = httplib::stream::Options(cli, "/options");
  20287. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20288. }
  20289. // SSL stream::* tests
  20290. #ifdef CPPHTTPLIB_SSL_ENABLED
  20291. class SSLStreamApiTest : public ::testing::Test {
  20292. protected:
  20293. void SetUp() override {
  20294. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20295. res.set_content("Hello SSL!", "text/plain");
  20296. });
  20297. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20298. res.set_content(req.body, "text/plain");
  20299. });
  20300. port_ = svr_.bind_to_any_port("127.0.0.1");
  20301. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20302. svr_.wait_until_ready();
  20303. }
  20304. void TearDown() override {
  20305. svr_.stop();
  20306. if (thread_.joinable()) thread_.join();
  20307. }
  20308. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20309. std::thread thread_;
  20310. int port_ = 0;
  20311. };
  20312. TEST_F(SSLStreamApiTest, GetAndPost) {
  20313. httplib::SSLClient cli("127.0.0.1", port_);
  20314. cli.enable_server_certificate_verification(false);
  20315. auto get = httplib::stream::Get(cli, "/hello");
  20316. EXPECT_EQ("Hello SSL!", read_body(get));
  20317. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20318. EXPECT_EQ("test", read_body(post));
  20319. }
  20320. #endif
  20321. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20322. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20323. // BodyReader
  20324. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20325. // Test that read timeout during streaming is detected
  20326. // Use a large content-length response where server delays mid-stream
  20327. Server svr;
  20328. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20329. // Send a large response with delay in the middle
  20330. res.set_content_provider(
  20331. 1000, // content_length
  20332. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20333. if (offset < 100) {
  20334. // Send first 100 bytes immediately
  20335. std::string data(100, 'A');
  20336. sink.write(data.c_str(), data.size());
  20337. return true;
  20338. }
  20339. // Then delay longer than client timeout
  20340. std::this_thread::sleep_for(std::chrono::seconds(3));
  20341. std::string data(900, 'B');
  20342. sink.write(data.c_str(), data.size());
  20343. return true;
  20344. });
  20345. });
  20346. auto port = 8091;
  20347. std::thread t([&]() { svr.listen("localhost", port); });
  20348. svr.wait_until_ready();
  20349. Client cli("localhost", port);
  20350. cli.set_read_timeout(1, 0); // 1 second timeout
  20351. auto handle = cli.open_stream("GET", "/slow-stream");
  20352. ASSERT_TRUE(handle.is_valid());
  20353. char buf[256];
  20354. ssize_t total = 0;
  20355. ssize_t n;
  20356. bool got_error = false;
  20357. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20358. total += n;
  20359. }
  20360. if (n < 0) {
  20361. got_error = true;
  20362. // Should be timeout or read error
  20363. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20364. handle.get_read_error() == Error::Read)
  20365. << "Actual error: " << to_string(handle.get_read_error());
  20366. }
  20367. // Either we got an error, or we got less data than expected
  20368. EXPECT_TRUE(got_error || total < 1000)
  20369. << "Expected timeout but got all " << total << " bytes";
  20370. svr.stop();
  20371. t.join();
  20372. }
  20373. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20374. // Test connection closed detection via BodyReader
  20375. Server svr;
  20376. std::atomic<bool> close_now{false};
  20377. svr.Get("/will-close", [&](const Request &, Response &res) {
  20378. res.set_content_provider(
  20379. 10000, // Large content_length that we won't fully send
  20380. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20381. if (offset < 100) {
  20382. std::string data(100, 'X');
  20383. sink.write(data.c_str(), data.size());
  20384. return true;
  20385. }
  20386. // Wait for signal then abort
  20387. while (!close_now) {
  20388. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20389. }
  20390. return false; // Abort - server will close connection
  20391. });
  20392. });
  20393. auto port = 8092;
  20394. std::thread t([&]() { svr.listen("localhost", port); });
  20395. svr.wait_until_ready();
  20396. Client cli("localhost", port);
  20397. auto handle = cli.open_stream("GET", "/will-close");
  20398. ASSERT_TRUE(handle.is_valid());
  20399. char buf[256];
  20400. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20401. EXPECT_GT(n, 0) << "First read should succeed";
  20402. // Signal server to close
  20403. close_now = true;
  20404. // Keep reading until error or EOF
  20405. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20406. // Keep reading
  20407. }
  20408. // Should get an error since content_length wasn't satisfied
  20409. if (n < 0) {
  20410. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20411. handle.get_read_error() == Error::Read)
  20412. << "Actual error: " << to_string(handle.get_read_error());
  20413. }
  20414. svr.stop();
  20415. t.join();
  20416. }
  20417. #ifdef CPPHTTPLIB_SSL_ENABLED
  20418. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20419. // Test that read timeout during SSL streaming is detected
  20420. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20421. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20422. res.set_content_provider(
  20423. 1000, "text/plain",
  20424. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20425. if (offset < 100) {
  20426. std::string data(100, 'A');
  20427. sink.write(data.c_str(), data.size());
  20428. return true;
  20429. }
  20430. std::this_thread::sleep_for(std::chrono::seconds(3));
  20431. std::string data(900, 'B');
  20432. sink.write(data.c_str(), data.size());
  20433. return true;
  20434. });
  20435. });
  20436. auto port = 8093;
  20437. std::thread t([&]() { svr.listen("localhost", port); });
  20438. svr.wait_until_ready();
  20439. SSLClient cli("localhost", port);
  20440. cli.enable_server_certificate_verification(false);
  20441. cli.set_read_timeout(1, 0); // 1 second timeout
  20442. auto handle = cli.open_stream("GET", "/slow-stream");
  20443. ASSERT_TRUE(handle.is_valid());
  20444. char buf[256];
  20445. ssize_t total = 0;
  20446. ssize_t n;
  20447. bool got_error = false;
  20448. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20449. total += n;
  20450. }
  20451. if (n < 0) {
  20452. got_error = true;
  20453. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20454. handle.get_read_error() == Error::Read)
  20455. << "Actual error: " << to_string(handle.get_read_error());
  20456. }
  20457. EXPECT_TRUE(got_error || total < 1000)
  20458. << "Expected timeout but got all " << total << " bytes";
  20459. svr.stop();
  20460. t.join();
  20461. }
  20462. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20463. // Test SSL connection closed detection
  20464. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20465. std::atomic<bool> close_now{false};
  20466. svr.Get("/will-close", [&](const Request &, Response &res) {
  20467. res.set_content_provider(
  20468. 10000, "text/plain",
  20469. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20470. if (offset < 100) {
  20471. std::string data(100, 'X');
  20472. sink.write(data.c_str(), data.size());
  20473. return true;
  20474. }
  20475. while (!close_now) {
  20476. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20477. }
  20478. return false;
  20479. });
  20480. });
  20481. auto port = 8094;
  20482. std::thread t([&]() { svr.listen("localhost", port); });
  20483. svr.wait_until_ready();
  20484. SSLClient cli("localhost", port);
  20485. cli.enable_server_certificate_verification(false);
  20486. auto handle = cli.open_stream("GET", "/will-close");
  20487. ASSERT_TRUE(handle.is_valid());
  20488. char buf[256];
  20489. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20490. EXPECT_GT(n, 0);
  20491. // Signal server to close
  20492. close_now = true;
  20493. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20494. // Keep reading
  20495. }
  20496. if (n < 0) {
  20497. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20498. handle.get_read_error() == Error::Read)
  20499. << "Actual error: " << to_string(handle.get_read_error());
  20500. }
  20501. svr.stop();
  20502. t.join();
  20503. }
  20504. #endif
  20505. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20506. using namespace httplib;
  20507. // Create a test file
  20508. const char *fname = "etag_testfile.txt";
  20509. const char *content = "etag-content";
  20510. {
  20511. std::ofstream ofs(fname);
  20512. ofs << content;
  20513. ASSERT_TRUE(ofs.good());
  20514. }
  20515. Server svr;
  20516. svr.set_mount_point("/static", ".");
  20517. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20518. svr.wait_until_ready();
  20519. Client cli(HOST, PORT);
  20520. // First request: should get 200 with ETag header
  20521. auto res1 = cli.Get("/static/etag_testfile.txt");
  20522. ASSERT_TRUE(res1);
  20523. ASSERT_EQ(200, res1->status);
  20524. ASSERT_TRUE(res1->has_header("ETag"));
  20525. std::string etag = res1->get_header_value("ETag");
  20526. EXPECT_FALSE(etag.empty());
  20527. // Verify ETag format: W/"hex-hex"
  20528. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20529. EXPECT_EQ('W', etag[0]);
  20530. EXPECT_EQ('/', etag[1]);
  20531. EXPECT_EQ('"', etag[2]);
  20532. EXPECT_EQ('"', etag.back());
  20533. // Exact match: expect 304 Not Modified
  20534. Headers h2 = {{"If-None-Match", etag}};
  20535. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20536. ASSERT_TRUE(res2);
  20537. EXPECT_EQ(304, res2->status);
  20538. // Wildcard match: expect 304 Not Modified
  20539. Headers h3 = {{"If-None-Match", "*"}};
  20540. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20541. ASSERT_TRUE(res3);
  20542. EXPECT_EQ(304, res3->status);
  20543. // Non-matching ETag: expect 200
  20544. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20545. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20546. ASSERT_TRUE(res4);
  20547. EXPECT_EQ(200, res4->status);
  20548. // Multiple ETags with one matching: expect 304
  20549. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20550. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20551. ASSERT_TRUE(res5);
  20552. EXPECT_EQ(304, res5->status);
  20553. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20554. // that equivalent to the single comma-separated list above, so the match on
  20555. // the second line must still be found.
  20556. Headers h6;
  20557. h6.emplace("If-None-Match", "W/\"other\"");
  20558. h6.emplace("If-None-Match", etag);
  20559. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20560. ASSERT_TRUE(res6);
  20561. EXPECT_EQ(304, res6->status);
  20562. svr.stop();
  20563. t.join();
  20564. std::remove(fname);
  20565. }
  20566. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20567. using namespace httplib;
  20568. Server svr;
  20569. svr.set_mount_point("/static", ".");
  20570. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20571. svr.wait_until_ready();
  20572. Client cli(HOST, PORT);
  20573. // Send If-None-Match: * to a non-existent file
  20574. Headers h = {{"If-None-Match", "*"}};
  20575. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20577. EXPECT_EQ(404, res->status);
  20578. svr.stop();
  20579. t.join();
  20580. }
  20581. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20582. using namespace httplib;
  20583. // Create a test file
  20584. const char *fname = "etag_boundary_testfile.txt";
  20585. const char *content = "boundary-test";
  20586. {
  20587. std::ofstream ofs(fname);
  20588. ofs << content;
  20589. ASSERT_TRUE(ofs.good());
  20590. }
  20591. Server svr;
  20592. svr.set_mount_point("/static", ".");
  20593. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20594. svr.wait_until_ready();
  20595. Client cli(HOST, PORT);
  20596. // Get the actual ETag
  20597. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20598. ASSERT_TRUE(res1);
  20599. ASSERT_EQ(200, res1->status);
  20600. ASSERT_TRUE(res1->has_header("ETag"));
  20601. std::string etag = res1->get_header_value("ETag");
  20602. // Test 1: Very long ETag value (longer than actual ETag)
  20603. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20604. Headers h1 = {{"If-None-Match", "W/"
  20605. "\"very-long-etag-value-that-is-much-longer-"
  20606. "than-the-actual-etag-value\""}};
  20607. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20608. ASSERT_TRUE(res2);
  20609. EXPECT_EQ(200, res2->status); // Should not match
  20610. // Test 2: Long string followed by wildcard
  20611. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20612. // string)
  20613. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20614. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20615. ASSERT_TRUE(res3);
  20616. EXPECT_EQ(304, res3->status); // Should match on "*"
  20617. // Test 3: Wildcard followed by long string
  20618. // Should match on "*" immediately and return 304
  20619. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20620. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20621. ASSERT_TRUE(res4);
  20622. EXPECT_EQ(304, res4->status); // Should match on "*"
  20623. // Test 4: Multiple long non-matching values
  20624. // Should NOT match and return 200 (test that all comparisons are safe)
  20625. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20626. "W/\"second-long-non-matching-value\", "
  20627. "W/\"third-long-non-matching-value\""}};
  20628. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20629. ASSERT_TRUE(res5);
  20630. EXPECT_EQ(200, res5->status); // Should not match
  20631. // Test 5: Single character that is not "*" (edge case)
  20632. Headers h5 = {{"If-None-Match", "X"}};
  20633. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20634. ASSERT_TRUE(res6);
  20635. EXPECT_EQ(200, res6->status); // Should not match
  20636. svr.stop();
  20637. t.join();
  20638. std::remove(fname);
  20639. }
  20640. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20641. using namespace httplib;
  20642. // Create a test file
  20643. const char *fname = "ims_testfile.txt";
  20644. const char *content = "if-modified-since-test";
  20645. {
  20646. std::ofstream ofs(fname);
  20647. ofs << content;
  20648. ASSERT_TRUE(ofs.good());
  20649. }
  20650. Server svr;
  20651. svr.set_mount_point("/static", ".");
  20652. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20653. svr.wait_until_ready();
  20654. Client cli(HOST, PORT);
  20655. // First request: should get 200 with Last-Modified header
  20656. auto res1 = cli.Get("/static/ims_testfile.txt");
  20657. ASSERT_TRUE(res1);
  20658. ASSERT_EQ(200, res1->status);
  20659. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20660. std::string last_modified = res1->get_header_value("Last-Modified");
  20661. EXPECT_FALSE(last_modified.empty());
  20662. // If-Modified-Since with same time: expect 304
  20663. Headers h2 = {{"If-Modified-Since", last_modified}};
  20664. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20665. ASSERT_TRUE(res2);
  20666. EXPECT_EQ(304, res2->status);
  20667. // If-Modified-Since with future time: expect 304
  20668. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20669. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20670. ASSERT_TRUE(res3);
  20671. EXPECT_EQ(304, res3->status);
  20672. // If-Modified-Since with past time: expect 200
  20673. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20674. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20675. ASSERT_TRUE(res4);
  20676. EXPECT_EQ(200, res4->status);
  20677. // If-None-Match takes precedence over If-Modified-Since
  20678. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20679. ASSERT_TRUE(res1->has_header("ETag"));
  20680. std::string etag = res1->get_header_value("ETag");
  20681. Headers h5 = {{"If-None-Match", etag},
  20682. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20683. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20684. ASSERT_TRUE(res5);
  20685. EXPECT_EQ(304, res5->status);
  20686. svr.stop();
  20687. t.join();
  20688. std::remove(fname);
  20689. }
  20690. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20691. using namespace httplib;
  20692. Server svr;
  20693. // Endpoint that returns compressible content
  20694. svr.Get("/compressible", [](const Request &, Response &res) {
  20695. // Return a large enough body to trigger compression
  20696. std::string body(1000, 'a');
  20697. res.set_content(body, "text/plain");
  20698. });
  20699. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20700. svr.wait_until_ready();
  20701. Client cli(HOST, PORT);
  20702. // Request with gzip support: should get Vary header when compressed
  20703. cli.set_compress(true);
  20704. auto res1 = cli.Get("/compressible");
  20705. ASSERT_TRUE(res1);
  20706. EXPECT_EQ(200, res1->status);
  20707. // If Content-Encoding is set, Vary should also be set
  20708. if (res1->has_header("Content-Encoding")) {
  20709. EXPECT_TRUE(res1->has_header("Vary"));
  20710. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20711. }
  20712. // Request without Accept-Encoding header: should not have compression
  20713. Headers h_no_compress;
  20714. auto res2 = cli.Get("/compressible", h_no_compress);
  20715. ASSERT_TRUE(res2);
  20716. EXPECT_EQ(200, res2->status);
  20717. // Verify Vary header is present when compression is applied
  20718. // (the exact behavior depends on server configuration)
  20719. svr.stop();
  20720. t.join();
  20721. }
  20722. TEST(ETagTest, IfRangeWithETag) {
  20723. using namespace httplib;
  20724. // Create a test file with known content
  20725. const char *fname = "if_range_testfile.txt";
  20726. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20727. {
  20728. std::ofstream ofs(fname);
  20729. ofs << content;
  20730. ASSERT_TRUE(ofs.good());
  20731. }
  20732. Server svr;
  20733. svr.set_mount_point("/static", ".");
  20734. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20735. svr.wait_until_ready();
  20736. Client cli(HOST, PORT);
  20737. // First request: get ETag
  20738. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20739. ASSERT_TRUE(res1);
  20740. ASSERT_EQ(200, res1->status);
  20741. ASSERT_TRUE(res1->has_header("ETag"));
  20742. std::string etag = res1->get_header_value("ETag");
  20743. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20744. // Since our server generates weak ETags (W/"..."), If-Range with our
  20745. // ETag should NOT result in partial content - it should return full content.
  20746. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20747. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20748. ASSERT_TRUE(res2);
  20749. // Weak ETag in If-Range -> full content (200), not partial (206)
  20750. EXPECT_EQ(200, res2->status);
  20751. EXPECT_EQ(content, res2->body);
  20752. EXPECT_FALSE(res2->has_header("Content-Range"));
  20753. // Range request with non-matching If-Range (ETag): should get 200 (full
  20754. // content)
  20755. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20756. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20757. ASSERT_TRUE(res3);
  20758. EXPECT_EQ(200, res3->status);
  20759. EXPECT_EQ(content, res3->body);
  20760. EXPECT_FALSE(res3->has_header("Content-Range"));
  20761. // Range request with strong ETag (hypothetical - our server doesn't generate
  20762. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20763. // should return full content)
  20764. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20765. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20766. ASSERT_TRUE(res4);
  20767. EXPECT_EQ(200, res4->status);
  20768. EXPECT_EQ(content, res4->body);
  20769. EXPECT_FALSE(res4->has_header("Content-Range"));
  20770. svr.stop();
  20771. t.join();
  20772. std::remove(fname);
  20773. }
  20774. TEST(ETagTest, IfRangeWithDate) {
  20775. using namespace httplib;
  20776. // Create a test file
  20777. const char *fname = "if_range_date_testfile.txt";
  20778. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20779. {
  20780. std::ofstream ofs(fname);
  20781. ofs << content;
  20782. ASSERT_TRUE(ofs.good());
  20783. }
  20784. Server svr;
  20785. svr.set_mount_point("/static", ".");
  20786. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20787. svr.wait_until_ready();
  20788. Client cli(HOST, PORT);
  20789. // First request: get Last-Modified
  20790. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20791. ASSERT_TRUE(res1);
  20792. ASSERT_EQ(200, res1->status);
  20793. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20794. std::string last_modified = res1->get_header_value("Last-Modified");
  20795. // Range request with matching If-Range (date): should get 206
  20796. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20797. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20798. ASSERT_TRUE(res2);
  20799. EXPECT_EQ(206, res2->status);
  20800. EXPECT_EQ("FGHIJ", res2->body);
  20801. // Range request with old If-Range date: should get 200 (full content)
  20802. Headers h3 = {{"Range", "bytes=5-9"},
  20803. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20804. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20805. ASSERT_TRUE(res3);
  20806. EXPECT_EQ(200, res3->status);
  20807. EXPECT_EQ(content, res3->body);
  20808. // Range request with future If-Range date: should get 206
  20809. Headers h4 = {{"Range", "bytes=0-4"},
  20810. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20811. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20812. ASSERT_TRUE(res4);
  20813. EXPECT_EQ(206, res4->status);
  20814. EXPECT_EQ("ABCDE", res4->body);
  20815. svr.stop();
  20816. t.join();
  20817. std::remove(fname);
  20818. }
  20819. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20820. using namespace httplib;
  20821. const char *fname = "etag_malformed.txt";
  20822. const char *content = "malformed-etag";
  20823. {
  20824. std::ofstream ofs(fname);
  20825. ofs << content;
  20826. ASSERT_TRUE(ofs.good());
  20827. }
  20828. Server svr;
  20829. svr.set_mount_point("/static", ".");
  20830. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20831. svr.wait_until_ready();
  20832. Client cli(HOST, PORT);
  20833. // baseline: should get 200 and an ETag
  20834. auto res1 = cli.Get("/static/etag_malformed.txt");
  20835. ASSERT_TRUE(res1);
  20836. ASSERT_EQ(200, res1->status);
  20837. ASSERT_TRUE(res1->has_header("ETag"));
  20838. // Malformed ETag value (missing quotes) should be treated as non-matching
  20839. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20840. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20841. ASSERT_TRUE(res_bad);
  20842. EXPECT_EQ(200, res_bad->status);
  20843. // Whitespace-only header value should be considered invalid / non-matching
  20844. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20845. "Host: localhost\r\n"
  20846. "If-None-Match: \r\n"
  20847. "Connection: close\r\n"
  20848. "\r\n";
  20849. std::string out;
  20850. ASSERT_TRUE(send_request(5, raw_req, &out));
  20851. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20852. svr.stop();
  20853. t.join();
  20854. std::remove(fname);
  20855. }
  20856. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20857. using namespace httplib;
  20858. const char *fname = "ims_invalid_format.txt";
  20859. const char *content = "ims-bad-format";
  20860. {
  20861. std::ofstream ofs(fname);
  20862. ofs << content;
  20863. ASSERT_TRUE(ofs.good());
  20864. }
  20865. Server svr;
  20866. svr.set_mount_point("/static", ".");
  20867. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20868. svr.wait_until_ready();
  20869. Client cli(HOST, PORT);
  20870. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20871. ASSERT_TRUE(res1);
  20872. ASSERT_EQ(200, res1->status);
  20873. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20874. // If-Modified-Since with invalid format should not result in 304
  20875. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20876. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20877. ASSERT_TRUE(res_bad);
  20878. EXPECT_EQ(200, res_bad->status);
  20879. // If-Range with invalid date format should be treated as mismatch -> full
  20880. // content (200)
  20881. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20882. {"If-Range", "invalid-date"}};
  20883. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20884. ASSERT_TRUE(res_ifrange);
  20885. EXPECT_EQ(200, res_ifrange->status);
  20886. svr.stop();
  20887. t.join();
  20888. std::remove(fname);
  20889. }
  20890. TEST(ETagTest, IfRangeWithMalformedETag) {
  20891. using namespace httplib;
  20892. const char *fname = "ifrange_malformed.txt";
  20893. const std::string content = "0123456789";
  20894. {
  20895. std::ofstream ofs(fname);
  20896. ofs << content;
  20897. ASSERT_TRUE(ofs.good());
  20898. }
  20899. Server svr;
  20900. svr.set_mount_point("/static", ".");
  20901. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20902. svr.wait_until_ready();
  20903. Client cli(HOST, PORT);
  20904. // First request: get ETag
  20905. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20906. ASSERT_TRUE(res1);
  20907. ASSERT_EQ(200, res1->status);
  20908. ASSERT_TRUE(res1->has_header("ETag"));
  20909. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20910. // full content (200)
  20911. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20912. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20913. ASSERT_TRUE(res2);
  20914. EXPECT_EQ(200, res2->status);
  20915. EXPECT_EQ(content, res2->body);
  20916. svr.stop();
  20917. t.join();
  20918. std::remove(fname);
  20919. }
  20920. TEST(ETagTest, ExtremeLargeDateValues) {
  20921. using namespace httplib;
  20922. const char *fname = "ims_extreme_date.txt";
  20923. const char *content = "ims-extreme-date";
  20924. {
  20925. std::ofstream ofs(fname);
  20926. ofs << content;
  20927. ASSERT_TRUE(ofs.good());
  20928. }
  20929. Server svr;
  20930. svr.set_mount_point("/static", ".");
  20931. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20932. svr.wait_until_ready();
  20933. Client cli(HOST, PORT);
  20934. auto res1 = cli.Get(std::string("/static/") + fname);
  20935. ASSERT_TRUE(res1);
  20936. ASSERT_EQ(200, res1->status);
  20937. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20938. // Extremely large year that may overflow date parsing routines.
  20939. Headers h_large_date = {
  20940. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20941. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20942. ASSERT_TRUE(res_bad);
  20943. // Expect server to treat this as invalid/mismatch and return full content
  20944. EXPECT_EQ(200, res_bad->status);
  20945. // If-Range with extremely large date should be treated as mismatch -> full
  20946. // content (200)
  20947. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20948. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20949. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20950. ASSERT_TRUE(res_ifrange);
  20951. EXPECT_EQ(200, res_ifrange->status);
  20952. svr.stop();
  20953. t.join();
  20954. std::remove(fname);
  20955. }
  20956. TEST(ETagTest, NegativeFileModificationTime) {
  20957. using namespace httplib;
  20958. const char *fname = "ims_negative_mtime.txt";
  20959. const std::string content = "negative-mtime";
  20960. {
  20961. std::ofstream ofs(fname);
  20962. ofs << content;
  20963. ASSERT_TRUE(ofs.good());
  20964. }
  20965. // Try to set file mtime to a negative value. This may fail on some
  20966. // platforms/filesystems; if it fails, the test will still verify server
  20967. // behaves safely by performing a regular conditional request.
  20968. #if defined(__APPLE__) || defined(__linux__)
  20969. bool set_negative = false;
  20970. do {
  20971. struct timeval times[2];
  20972. // access time: now
  20973. times[0].tv_sec = time(nullptr);
  20974. times[0].tv_usec = 0;
  20975. // modification time: negative (e.g., -1)
  20976. times[1].tv_sec = -1;
  20977. times[1].tv_usec = 0;
  20978. if (utimes(fname, times) == 0) { set_negative = true; }
  20979. } while (0);
  20980. #else
  20981. bool set_negative = false;
  20982. #endif
  20983. Server svr;
  20984. svr.set_mount_point("/static", ".");
  20985. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20986. svr.wait_until_ready();
  20987. Client cli(HOST, PORT);
  20988. auto res1 = cli.Get(std::string("/static/") + fname);
  20989. ASSERT_TRUE(res1);
  20990. ASSERT_EQ(200, res1->status);
  20991. bool has_last_modified = res1->has_header("Last-Modified");
  20992. std::string last_modified;
  20993. if (has_last_modified) {
  20994. last_modified = res1->get_header_value("Last-Modified");
  20995. }
  20996. if (set_negative) {
  20997. // If we successfully set a negative mtime, ensure server returns a
  20998. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20999. // with an old date and ensure server handles it without crash.
  21000. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21001. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21002. ASSERT_TRUE(res2);
  21003. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21004. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21005. } else {
  21006. // Could not set negative mtime on this platform; fall back to verifying
  21007. // that normal invalid/malformed dates are treated safely (non-304).
  21008. Headers h_bad_date = {
  21009. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21010. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21011. ASSERT_TRUE(res_bad);
  21012. EXPECT_EQ(200, res_bad->status);
  21013. }
  21014. svr.stop();
  21015. t.join();
  21016. std::remove(fname);
  21017. }
  21018. //==============================================================================
  21019. // Integration Tests with Server
  21020. //==============================================================================
  21021. class SSEIntegrationTest : public ::testing::Test {
  21022. protected:
  21023. void SetUp() override {
  21024. stop_server_.store(false);
  21025. events_.clear();
  21026. server_ = httplib::detail::make_unique<Server>();
  21027. setup_server();
  21028. start_server();
  21029. }
  21030. void TearDown() override {
  21031. stop_server_.store(true);
  21032. event_cv_.notify_all();
  21033. server_->stop();
  21034. if (server_thread_.joinable()) { server_thread_.join(); }
  21035. }
  21036. void setup_server() {
  21037. // Simple SSE endpoint
  21038. server_->Get("/events", [this](const Request &req, Response &res) {
  21039. auto last_id = req.get_header_value("Last-Event-ID");
  21040. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21041. res.set_chunked_content_provider(
  21042. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21043. std::unique_lock<std::mutex> lock(event_mutex_);
  21044. if (event_cv_.wait_for(
  21045. lock, std::chrono::milliseconds(200), [this] {
  21046. return !events_.empty() || stop_server_.load();
  21047. })) {
  21048. if (stop_server_.load()) { return false; }
  21049. if (!events_.empty()) {
  21050. std::string event = events_.front();
  21051. events_.erase(events_.begin());
  21052. sink.write(event.data(), event.size());
  21053. return true;
  21054. }
  21055. }
  21056. return !stop_server_.load();
  21057. });
  21058. });
  21059. // Endpoint that returns error
  21060. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21061. res.status = 500;
  21062. res.set_content("Internal Server Error", "text/plain");
  21063. });
  21064. // Endpoint for custom event types
  21065. server_->Get("/custom-events", [](const Request &, Response &res) {
  21066. res.set_chunked_content_provider(
  21067. "text/event-stream", [](size_t offset, DataSink &sink) {
  21068. if (offset == 0) {
  21069. std::string event = "event: update\ndata: updated\n\n"
  21070. "event: delete\ndata: deleted\n\n";
  21071. sink.write(event.data(), event.size());
  21072. }
  21073. return false; // End stream after sending
  21074. });
  21075. });
  21076. }
  21077. void start_server() {
  21078. port_ = server_->bind_to_any_port(HOST);
  21079. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21080. // Wait for server to start
  21081. while (!server_->is_running()) {
  21082. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21083. }
  21084. }
  21085. int get_port() const { return port_; }
  21086. void send_event(const std::string &event) {
  21087. std::lock_guard<std::mutex> lock(event_mutex_);
  21088. events_.push_back(event);
  21089. event_cv_.notify_all();
  21090. }
  21091. std::unique_ptr<Server> server_;
  21092. std::thread server_thread_;
  21093. std::mutex event_mutex_;
  21094. std::condition_variable event_cv_;
  21095. std::vector<std::string> events_;
  21096. std::atomic<bool> stop_server_{false};
  21097. std::string last_received_event_id_;
  21098. int port_ = 0;
  21099. };
  21100. //==============================================================================
  21101. // SSE Parsing Tests
  21102. //==============================================================================
  21103. class SSEParsingTest : public SSEIntegrationTest {
  21104. protected:
  21105. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21106. // A trailing sentinel event tells when the whole stream has been parsed.
  21107. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21108. auto body = stream + "event: end\ndata: end\n\n";
  21109. server_->Get("/parse", [body](const Request &, Response &res) {
  21110. res.set_content(body, "text/event-stream");
  21111. });
  21112. return collect("/parse");
  21113. }
  21114. // Runs SSEClient against path until an "end" event arrives and returns the
  21115. // messages dispatched before it
  21116. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21117. Client client(HOST, get_port());
  21118. sse::SSEClient sse(client, path);
  21119. std::mutex mutex;
  21120. std::condition_variable cv;
  21121. std::vector<sse::SSEMessage> messages;
  21122. auto done = false;
  21123. sse.on_message([&](const sse::SSEMessage &msg) {
  21124. std::lock_guard<std::mutex> lock(mutex);
  21125. // Ignore a replay from a reconnect that races with stop()
  21126. if (!done) { messages.push_back(msg); }
  21127. });
  21128. sse.on_event("end", [&](const sse::SSEMessage &) {
  21129. std::lock_guard<std::mutex> lock(mutex);
  21130. done = true;
  21131. cv.notify_all();
  21132. });
  21133. sse.set_reconnect_interval(100);
  21134. sse.start_async();
  21135. {
  21136. std::unique_lock<std::mutex> lock(mutex);
  21137. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21138. }
  21139. sse.stop();
  21140. EXPECT_TRUE(done);
  21141. return messages;
  21142. }
  21143. };
  21144. TEST_F(SSEParsingTest, SingleLineData) {
  21145. auto msgs = parse("data: hello\n\n");
  21146. ASSERT_EQ(msgs.size(), 1u);
  21147. EXPECT_EQ(msgs[0].data, "hello");
  21148. EXPECT_EQ(msgs[0].event, "message");
  21149. }
  21150. TEST_F(SSEParsingTest, MultiLineData) {
  21151. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21152. ASSERT_EQ(msgs.size(), 1u);
  21153. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21154. }
  21155. TEST_F(SSEParsingTest, CustomEventType) {
  21156. auto msgs = parse("event: update\ndata: payload\n\n");
  21157. ASSERT_EQ(msgs.size(), 1u);
  21158. EXPECT_EQ(msgs[0].event, "update");
  21159. EXPECT_EQ(msgs[0].data, "payload");
  21160. }
  21161. TEST_F(SSEParsingTest, EventIdHandling) {
  21162. auto msgs = parse("id: 12345\ndata: test\n\n");
  21163. ASSERT_EQ(msgs.size(), 1u);
  21164. EXPECT_EQ(msgs[0].id, "12345");
  21165. }
  21166. TEST_F(SSEParsingTest, EmptyEventId) {
  21167. auto msgs = parse("id:\ndata: test\n\n");
  21168. ASSERT_EQ(msgs.size(), 1u);
  21169. EXPECT_EQ(msgs[0].id, "");
  21170. }
  21171. TEST_F(SSEParsingTest, CommentsIgnored) {
  21172. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21173. ASSERT_EQ(msgs.size(), 1u);
  21174. EXPECT_EQ(msgs[0].data, "hello");
  21175. EXPECT_EQ(msgs[0].event, "message");
  21176. }
  21177. TEST_F(SSEParsingTest, ColonInValue) {
  21178. auto msgs = parse("data: hello:world:test\n\n");
  21179. ASSERT_EQ(msgs.size(), 1u);
  21180. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21181. }
  21182. TEST_F(SSEParsingTest, FieldNameOnly) {
  21183. // A line without a colon is a field name with an empty value
  21184. auto msgs = parse("data\n\n");
  21185. ASSERT_EQ(msgs.size(), 1u);
  21186. EXPECT_EQ(msgs[0].data, "");
  21187. }
  21188. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21189. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21190. ASSERT_EQ(msgs.size(), 1u);
  21191. EXPECT_EQ(msgs[0].event, "update");
  21192. EXPECT_EQ(msgs[0].data, "hello");
  21193. }
  21194. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21195. auto msgs = parse("data\r\n\r\n");
  21196. ASSERT_EQ(msgs.size(), 1u);
  21197. EXPECT_EQ(msgs[0].data, "");
  21198. }
  21199. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21200. auto msgs = parse("event: update\rdata: hello\r\r");
  21201. ASSERT_EQ(msgs.size(), 1u);
  21202. EXPECT_EQ(msgs[0].event, "update");
  21203. EXPECT_EQ(msgs[0].data, "hello");
  21204. }
  21205. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21206. // Chunk boundaries fall inside every \r\n and right before the first one
  21207. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21208. "\n\r", "\nevent: end\ndata: end\n\n"};
  21209. server_->Get("/split", [chunks](const Request &, Response &res) {
  21210. auto i = std::make_shared<size_t>(0);
  21211. res.set_chunked_content_provider(
  21212. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21213. if (*i == chunks.size()) {
  21214. sink.done();
  21215. } else {
  21216. sink.write(chunks[*i].data(), chunks[*i].size());
  21217. (*i)++;
  21218. }
  21219. return true;
  21220. });
  21221. });
  21222. auto msgs = collect("/split");
  21223. ASSERT_EQ(msgs.size(), 1u);
  21224. EXPECT_EQ(msgs[0].event, "update");
  21225. EXPECT_EQ(msgs[0].data, "hello");
  21226. }
  21227. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21228. // Only a BOM at the start of the stream is ignored
  21229. auto msgs = parse("\xEF\xBB\xBF"
  21230. "data: first\n\n"
  21231. "\xEF\xBB\xBF"
  21232. "data: second\n\n");
  21233. ASSERT_EQ(msgs.size(), 1u);
  21234. EXPECT_EQ(msgs[0].data, "first");
  21235. }
  21236. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21237. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21238. ASSERT_EQ(msgs.size(), 1u);
  21239. EXPECT_EQ(msgs[0].data, "hello");
  21240. EXPECT_EQ(msgs[0].event, "message");
  21241. }
  21242. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21243. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21244. ASSERT_EQ(msgs.size(), 2u);
  21245. EXPECT_EQ(msgs[0].data, "hello");
  21246. EXPECT_EQ(msgs[1].data, "hello");
  21247. }
  21248. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21249. // An event without data is not dispatched, and its type must not leak
  21250. // into the next event
  21251. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21252. ASSERT_EQ(msgs.size(), 1u);
  21253. EXPECT_EQ(msgs[0].event, "message");
  21254. EXPECT_EQ(msgs[0].data, "hello");
  21255. }
  21256. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21257. // The first connection sends only an id; the second echoes back the
  21258. // Last-Event-ID it was reconnected with
  21259. std::atomic<int> connection_count{0};
  21260. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21261. if (connection_count++ == 0) {
  21262. res.set_content("id: 42\n\n", "text/event-stream");
  21263. } else {
  21264. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21265. "\n\nevent: end\ndata: end\n\n",
  21266. "text/event-stream");
  21267. }
  21268. });
  21269. auto msgs = collect("/id-only");
  21270. ASSERT_EQ(msgs.size(), 1u);
  21271. EXPECT_EQ(msgs[0].data, "42");
  21272. }
  21273. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21274. // The first connection sets an id and then clears it with an empty one; the
  21275. // second reports whether it was reconnected with a Last-Event-ID
  21276. std::atomic<int> connection_count{0};
  21277. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21278. if (connection_count++ == 0) {
  21279. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21280. "text/event-stream");
  21281. } else {
  21282. res.set_content(
  21283. std::string("data: ") +
  21284. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21285. "\n\nevent: end\ndata: end\n\n",
  21286. "text/event-stream");
  21287. }
  21288. });
  21289. auto msgs = collect("/id-clear");
  21290. ASSERT_EQ(msgs.size(), 3u);
  21291. EXPECT_EQ(msgs[0].id, "1");
  21292. EXPECT_EQ(msgs[1].id, "");
  21293. EXPECT_EQ(msgs[2].data, "not sent");
  21294. }
  21295. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21296. // The first connection sets an id and then sends ids that cannot be carried
  21297. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21298. // with
  21299. std::atomic<int> connection_count{0};
  21300. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21301. if (connection_count++ == 0) {
  21302. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21303. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21304. "text/event-stream");
  21305. } else {
  21306. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21307. "\n\nevent: end\ndata: end\n\n",
  21308. "text/event-stream");
  21309. }
  21310. });
  21311. auto msgs = collect("/id-unsendable");
  21312. ASSERT_EQ(msgs.size(), 1u);
  21313. EXPECT_EQ(msgs[0].data, "42");
  21314. }
  21315. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21316. auto msgs = parse("event: notification\nid: evt-42\n"
  21317. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21318. ASSERT_EQ(msgs.size(), 1u);
  21319. EXPECT_EQ(msgs[0].event, "notification");
  21320. EXPECT_EQ(msgs[0].id, "evt-42");
  21321. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21322. }
  21323. TEST(SSEMessageTest, Clear) {
  21324. sse::SSEMessage msg;
  21325. msg.event = "custom";
  21326. msg.data = "some data";
  21327. msg.id = "123";
  21328. msg.clear();
  21329. EXPECT_EQ(msg.event, "message");
  21330. EXPECT_EQ(msg.data, "");
  21331. EXPECT_EQ(msg.id, "");
  21332. }
  21333. //==============================================================================
  21334. // SSE Integration Tests
  21335. //==============================================================================
  21336. // Test: Successful connection and on_open callback
  21337. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21338. // Add a simple endpoint that sends one event and closes
  21339. server_->Get("/simple-event", [](const Request &, Response &res) {
  21340. res.set_chunked_content_provider(
  21341. "text/event-stream", [](size_t offset, DataSink &sink) {
  21342. if (offset == 0) {
  21343. std::string event = "data: hello\n\n";
  21344. sink.write(event.data(), event.size());
  21345. }
  21346. return false; // Close stream after sending
  21347. });
  21348. });
  21349. Client client("localhost", get_port());
  21350. sse::SSEClient sse(client, "/simple-event");
  21351. std::atomic<bool> open_called{false};
  21352. std::atomic<bool> message_received{false};
  21353. sse.on_open([&open_called]() { open_called.store(true); });
  21354. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21355. if (msg.data == "hello") { message_received.store(true); }
  21356. });
  21357. sse.set_reconnect_interval(100);
  21358. sse.set_max_reconnect_attempts(1);
  21359. // Start async
  21360. sse.start_async();
  21361. // Wait for message to be processed
  21362. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21363. sse.stop();
  21364. EXPECT_TRUE(open_called.load());
  21365. EXPECT_TRUE(message_received.load());
  21366. }
  21367. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21368. // A data line that never ends.
  21369. server_->Get("/endless-line", [](const Request &, Response &res) {
  21370. res.set_chunked_content_provider(
  21371. "text/event-stream", [](size_t offset, DataSink &sink) {
  21372. if (offset == 0) { sink.write("data: ", 6); }
  21373. std::string chunk(64 * 1024, 'A');
  21374. return sink.write(chunk.data(), chunk.size());
  21375. });
  21376. });
  21377. Client client("localhost", get_port());
  21378. sse::SSEClient sse(client, "/endless-line");
  21379. std::atomic<bool> too_long{false};
  21380. sse.on_error([&](Error err) {
  21381. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21382. });
  21383. sse.set_max_reconnect_attempts(1);
  21384. sse.start_async();
  21385. for (int i = 0; i < 500 && !too_long; i++) {
  21386. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21387. }
  21388. sse.stop();
  21389. EXPECT_TRUE(too_long);
  21390. }
  21391. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21392. // Far more in all than the client's payload limit below.
  21393. server_->Get("/many-events", [](const Request &, Response &res) {
  21394. res.set_chunked_content_provider(
  21395. "text/event-stream", [](size_t offset, DataSink &sink) {
  21396. if (offset == 0) {
  21397. std::string events;
  21398. for (int i = 0; i < 1000; i++) {
  21399. events += "data: message\n\n";
  21400. }
  21401. sink.write(events.data(), events.size());
  21402. }
  21403. return false;
  21404. });
  21405. });
  21406. Client client("localhost", get_port());
  21407. client.set_payload_max_length(1024);
  21408. sse::SSEClient sse(client, "/many-events");
  21409. std::atomic<int> messages{0};
  21410. std::atomic<bool> too_large{false};
  21411. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21412. sse.on_error([&](Error err) {
  21413. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21414. });
  21415. sse.set_max_reconnect_attempts(1);
  21416. sse.start_async();
  21417. for (int i = 0; i < 500 && messages < 1000; i++) {
  21418. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21419. }
  21420. sse.stop();
  21421. EXPECT_GE(messages.load(), 1000);
  21422. EXPECT_FALSE(too_large);
  21423. }
  21424. // Test: on_message callback
  21425. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21426. // Endpoint that sends multiple events then closes
  21427. server_->Get("/multi-event", [](const Request &, Response &res) {
  21428. res.set_chunked_content_provider(
  21429. "text/event-stream", [](size_t offset, DataSink &sink) {
  21430. if (offset == 0) {
  21431. std::string events = "data: message1\n\ndata: message2\n\n";
  21432. sink.write(events.data(), events.size());
  21433. }
  21434. return false;
  21435. });
  21436. });
  21437. Client client("localhost", get_port());
  21438. sse::SSEClient sse(client, "/multi-event");
  21439. std::vector<std::string> received_messages;
  21440. std::mutex messages_mutex;
  21441. sse.on_message([&](const sse::SSEMessage &msg) {
  21442. std::lock_guard<std::mutex> lock(messages_mutex);
  21443. received_messages.push_back(msg.data);
  21444. });
  21445. sse.set_reconnect_interval(100);
  21446. sse.set_max_reconnect_attempts(1);
  21447. sse.start_async();
  21448. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21449. sse.stop();
  21450. std::lock_guard<std::mutex> lock(messages_mutex);
  21451. EXPECT_GE(received_messages.size(), 2u);
  21452. if (received_messages.size() >= 2) {
  21453. EXPECT_EQ(received_messages[0], "message1");
  21454. EXPECT_EQ(received_messages[1], "message2");
  21455. }
  21456. }
  21457. // Test: on_event for specific types
  21458. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21459. Client client("localhost", get_port());
  21460. sse::SSEClient sse(client, "/custom-events");
  21461. std::atomic<bool> update_received{false};
  21462. std::atomic<bool> delete_received{false};
  21463. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21464. if (msg.data == "updated") { update_received.store(true); }
  21465. });
  21466. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21467. if (msg.data == "deleted") { delete_received.store(true); }
  21468. });
  21469. sse.set_max_reconnect_attempts(1);
  21470. sse.start_async();
  21471. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21472. sse.stop();
  21473. EXPECT_TRUE(update_received.load());
  21474. EXPECT_TRUE(delete_received.load());
  21475. }
  21476. // Test: on_error callback on connection failure
  21477. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21478. // Connect to a non-existent port
  21479. Client client("localhost", 59999);
  21480. sse::SSEClient sse(client, "/events");
  21481. std::atomic<bool> error_called{false};
  21482. Error received_error = Error::Success;
  21483. sse.on_error([&](Error err) {
  21484. error_called.store(true);
  21485. received_error = err;
  21486. });
  21487. sse.set_reconnect_interval(50);
  21488. sse.set_max_reconnect_attempts(1);
  21489. sse.start_async();
  21490. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21491. sse.stop();
  21492. EXPECT_TRUE(error_called.load());
  21493. EXPECT_NE(received_error, Error::Success);
  21494. }
  21495. // Test: Last-Event-ID header sent on reconnect
  21496. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21497. // Endpoint that sends event with ID
  21498. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21499. res.set_chunked_content_provider(
  21500. "text/event-stream", [](size_t offset, DataSink &sink) {
  21501. if (offset == 0) {
  21502. std::string event = "id: evt-123\ndata: test\n\n";
  21503. sink.write(event.data(), event.size());
  21504. }
  21505. return false;
  21506. });
  21507. });
  21508. Client client("localhost", get_port());
  21509. sse::SSEClient sse(client, "/event-with-id");
  21510. std::atomic<bool> id_received{false};
  21511. sse.on_message([&](const sse::SSEMessage &msg) {
  21512. if (!msg.id.empty()) { id_received.store(true); }
  21513. });
  21514. sse.set_reconnect_interval(100);
  21515. sse.set_max_reconnect_attempts(1);
  21516. sse.start_async();
  21517. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21518. sse.stop();
  21519. EXPECT_TRUE(id_received.load());
  21520. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21521. }
  21522. // Test: Manual stop
  21523. TEST_F(SSEIntegrationTest, ManualStop) {
  21524. // Endpoint that sends one event and stays open briefly
  21525. std::atomic<bool> handler_running{true};
  21526. server_->Get("/stay-open", [&handler_running](const Request &,
  21527. Response &res) {
  21528. res.set_chunked_content_provider(
  21529. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  21530. if (offset == 0) {
  21531. std::string event = "data: connected\n\n";
  21532. sink.write(event.data(), event.size());
  21533. }
  21534. // Keep connection open while handler_running is true
  21535. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  21536. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21537. }
  21538. return false;
  21539. });
  21540. });
  21541. Client client("localhost", get_port());
  21542. sse::SSEClient sse(client, "/stay-open");
  21543. std::atomic<bool> connected{false};
  21544. sse.on_open([&connected]() { connected.store(true); });
  21545. sse.set_reconnect_interval(100);
  21546. sse.set_max_reconnect_attempts(1);
  21547. sse.start_async();
  21548. // Wait for connection to establish
  21549. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21550. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21551. }
  21552. EXPECT_TRUE(connected.load());
  21553. EXPECT_TRUE(sse.is_connected());
  21554. // Signal handler to stop
  21555. handler_running.store(false);
  21556. // Stop SSE client
  21557. sse.stop();
  21558. EXPECT_FALSE(sse.is_connected());
  21559. }
  21560. // Sends one event, then nothing until stop is set
  21561. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  21562. return [&stop](const Request &, Response &res) {
  21563. res.set_chunked_content_provider(
  21564. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  21565. if (offset == 0) {
  21566. std::string event = "data: hello\n\n";
  21567. sink.write(event.data(), event.size());
  21568. }
  21569. while (!stop.load()) {
  21570. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21571. }
  21572. return false;
  21573. });
  21574. };
  21575. }
  21576. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  21577. static void check_stop_interrupts_blocked_read(Client &client) {
  21578. client.set_read_timeout(30, 0);
  21579. for (auto by_destructor : {false, true}) {
  21580. std::atomic<bool> received{false};
  21581. std::chrono::steady_clock::time_point start;
  21582. {
  21583. sse::SSEClient sse(client, "/idle-stream");
  21584. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  21585. sse.start_async();
  21586. for (int i = 0; i < 500 && !received.load(); ++i) {
  21587. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21588. }
  21589. ASSERT_TRUE(received.load());
  21590. // Let the client block in the next read
  21591. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  21592. start = std::chrono::steady_clock::now();
  21593. if (!by_destructor) { sse.stop(); }
  21594. }
  21595. EXPECT_LT(std::chrono::steady_clock::now() - start,
  21596. std::chrono::seconds(2));
  21597. }
  21598. }
  21599. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  21600. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  21601. Client client("localhost", get_port());
  21602. check_stop_interrupts_blocked_read(client);
  21603. }
  21604. #ifdef CPPHTTPLIB_SSL_ENABLED
  21605. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  21606. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21607. std::atomic<bool> done{false};
  21608. svr.Get("/idle-stream", idle_event_stream(done));
  21609. auto port = svr.bind_to_any_port(HOST);
  21610. std::thread t([&] { svr.listen_after_bind(); });
  21611. auto se = detail::scope_exit([&] {
  21612. done.store(true);
  21613. svr.stop();
  21614. t.join();
  21615. });
  21616. svr.wait_until_ready();
  21617. Client client("https://localhost:" + std::to_string(port));
  21618. client.enable_server_certificate_verification(false);
  21619. check_stop_interrupts_blocked_read(client);
  21620. }
  21621. #endif
  21622. // Test: SSEClient with custom headers
  21623. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21624. // Setup a server endpoint that checks for custom header
  21625. std::atomic<bool> header_received{false};
  21626. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21627. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21628. header_received.store(true);
  21629. }
  21630. res.set_chunked_content_provider("text/event-stream",
  21631. [](size_t, DataSink &) { return false; });
  21632. });
  21633. Client client("localhost", get_port());
  21634. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21635. sse::SSEClient sse(client, "/header-check", headers);
  21636. sse.set_max_reconnect_attempts(1);
  21637. sse.start_async();
  21638. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21639. sse.stop();
  21640. EXPECT_TRUE(header_received.load());
  21641. }
  21642. // Test: Reconnect interval configuration
  21643. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21644. Client client("localhost", get_port());
  21645. sse::SSEClient sse(client, "/events");
  21646. auto &result = sse.set_reconnect_interval(500);
  21647. // Builder pattern should return reference to self
  21648. EXPECT_EQ(&result, &sse);
  21649. }
  21650. // Test: Max reconnect attempts
  21651. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21652. // Connect to non-existent port to force reconnects
  21653. Client client("localhost", 59998);
  21654. sse::SSEClient sse(client, "/events");
  21655. std::atomic<int> error_count{0};
  21656. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21657. sse.set_reconnect_interval(50);
  21658. sse.set_max_reconnect_attempts(2);
  21659. auto start = std::chrono::steady_clock::now();
  21660. sse.start(); // Blocking call
  21661. auto end = std::chrono::steady_clock::now();
  21662. // Should have stopped after 2 failed attempts
  21663. EXPECT_GE(error_count.load(), 2);
  21664. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21665. auto duration =
  21666. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21667. #ifdef _WIN32
  21668. // Windows is much slower for socket connection failures
  21669. EXPECT_LT(duration.count(), 7000);
  21670. #else
  21671. EXPECT_LT(duration.count(), 1000);
  21672. #endif
  21673. }
  21674. // Test: Multi-line data in integration
  21675. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21676. // Endpoint with multi-line data
  21677. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21678. res.set_chunked_content_provider(
  21679. "text/event-stream", [](size_t offset, DataSink &sink) {
  21680. if (offset == 0) {
  21681. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21682. sink.write(event.data(), event.size());
  21683. }
  21684. return false;
  21685. });
  21686. });
  21687. Client client("localhost", get_port());
  21688. sse::SSEClient sse(client, "/multiline-data");
  21689. std::string received_data;
  21690. std::mutex data_mutex;
  21691. sse.on_message([&](const sse::SSEMessage &msg) {
  21692. std::lock_guard<std::mutex> lock(data_mutex);
  21693. received_data = msg.data;
  21694. });
  21695. sse.set_reconnect_interval(100);
  21696. sse.set_max_reconnect_attempts(1);
  21697. sse.start_async();
  21698. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21699. sse.stop();
  21700. std::lock_guard<std::mutex> lock(data_mutex);
  21701. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21702. }
  21703. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21704. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21705. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21706. DataSink &sink) {
  21707. if (offset == 0) {
  21708. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21709. sink.write(events.data(), events.size());
  21710. }
  21711. return false;
  21712. });
  21713. });
  21714. Client client("localhost", get_port());
  21715. sse::SSEClient sse(client, "/empty-data-lines");
  21716. std::mutex mutex;
  21717. std::condition_variable cv;
  21718. std::vector<std::string> received;
  21719. sse.on_message([&](const sse::SSEMessage &msg) {
  21720. std::lock_guard<std::mutex> lock(mutex);
  21721. received.push_back(msg.data);
  21722. cv.notify_all();
  21723. });
  21724. sse.set_max_reconnect_attempts(1);
  21725. sse.start_async();
  21726. {
  21727. std::unique_lock<std::mutex> lock(mutex);
  21728. cv.wait_for(lock, std::chrono::seconds(2),
  21729. [&] { return received.size() >= 3; });
  21730. }
  21731. sse.stop();
  21732. ASSERT_GE(received.size(), 3u);
  21733. EXPECT_EQ(received[0], "");
  21734. EXPECT_EQ(received[1], "\nhello");
  21735. EXPECT_EQ(received[2], "");
  21736. }
  21737. // Test: Auto-reconnect after server disconnection
  21738. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21739. std::atomic<int> connection_count{0};
  21740. std::atomic<int> message_count{0};
  21741. // Endpoint that sends one event and closes, forcing reconnect
  21742. server_->Get("/reconnect-test",
  21743. [&connection_count](const Request &, Response &res) {
  21744. connection_count.fetch_add(1);
  21745. res.set_chunked_content_provider(
  21746. "text/event-stream", [](size_t offset, DataSink &sink) {
  21747. if (offset == 0) {
  21748. std::string event = "data: hello\n\n";
  21749. sink.write(event.data(), event.size());
  21750. }
  21751. return false; // Close connection after sending
  21752. });
  21753. });
  21754. Client client("localhost", get_port());
  21755. sse::SSEClient sse(client, "/reconnect-test");
  21756. sse.on_message([&message_count](const sse::SSEMessage &) {
  21757. message_count.fetch_add(1);
  21758. });
  21759. sse.set_reconnect_interval(100);
  21760. sse.set_max_reconnect_attempts(3);
  21761. sse.start_async();
  21762. // Wait long enough for multiple reconnects
  21763. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21764. sse.stop();
  21765. // Should have connected multiple times (initial + reconnects)
  21766. EXPECT_GE(connection_count.load(), 2);
  21767. // Should have received messages from multiple connections
  21768. EXPECT_GE(message_count.load(), 2);
  21769. }
  21770. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  21771. std::atomic<int> connection_count{0};
  21772. // Neither Content-Length nor chunked: the close ends the stream
  21773. server_->Get("/close-delimited",
  21774. [&connection_count](const Request &, Response &res) {
  21775. connection_count.fetch_add(1);
  21776. res.set_content_provider(
  21777. "text/event-stream", [](size_t offset, DataSink &sink) {
  21778. if (offset == 0) {
  21779. std::string event = "data: hello\n\n";
  21780. sink.write(event.data(), event.size());
  21781. } else {
  21782. sink.done();
  21783. }
  21784. return true;
  21785. });
  21786. });
  21787. Client client("localhost", get_port());
  21788. sse::SSEClient sse(client, "/close-delimited");
  21789. std::atomic<int> error_count{0};
  21790. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  21791. sse.set_reconnect_interval(100);
  21792. sse.start_async();
  21793. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  21794. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21795. }
  21796. sse.stop();
  21797. // Reconnects as after any end of the stream, but reports no error
  21798. EXPECT_GE(connection_count.load(), 2);
  21799. EXPECT_EQ(0, error_count.load());
  21800. }
  21801. // Test: A retry field that is not all ASCII digits is ignored
  21802. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21803. std::atomic<int> connection_count{0};
  21804. server_->Get("/bad-retry",
  21805. [&connection_count](const Request &, Response &res) {
  21806. connection_count.fetch_add(1);
  21807. res.set_chunked_content_provider(
  21808. "text/event-stream", [](size_t offset, DataSink &sink) {
  21809. if (offset == 0) {
  21810. std::string event = "retry: -1\ndata: hello\n\n";
  21811. sink.write(event.data(), event.size());
  21812. }
  21813. return false;
  21814. });
  21815. });
  21816. Client client("localhost", get_port());
  21817. sse::SSEClient sse(client, "/bad-retry");
  21818. sse.set_reconnect_interval(10000);
  21819. sse.start_async();
  21820. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21821. sse.stop();
  21822. EXPECT_EQ(connection_count.load(), 1);
  21823. }
  21824. // Test: A retry field of all ASCII digits sets the reconnection time
  21825. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21826. std::mutex mutex;
  21827. std::condition_variable cv;
  21828. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21829. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21830. {
  21831. std::lock_guard<std::mutex> lock(mutex);
  21832. connected_at.push_back(std::chrono::steady_clock::now());
  21833. cv.notify_all();
  21834. }
  21835. res.set_chunked_content_provider(
  21836. "text/event-stream", [](size_t offset, DataSink &sink) {
  21837. if (offset == 0) {
  21838. std::string event = "retry: 0\ndata: hello\n\n";
  21839. sink.write(event.data(), event.size());
  21840. }
  21841. return false;
  21842. });
  21843. });
  21844. Client client("localhost", get_port());
  21845. sse::SSEClient sse(client, "/zero-retry");
  21846. sse.set_reconnect_interval(10000);
  21847. sse.start_async();
  21848. {
  21849. std::unique_lock<std::mutex> lock(mutex);
  21850. cv.wait_for(lock, std::chrono::seconds(5),
  21851. [&] { return connected_at.size() >= 2; });
  21852. }
  21853. sse.stop();
  21854. // The server-supplied interval is applied, but never below 100ms, so
  21855. // "retry: 0" does not cause a busy reconnect loop
  21856. std::lock_guard<std::mutex> lock(mutex);
  21857. ASSERT_GE(connected_at.size(), 2u);
  21858. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21859. connected_at[1] - connected_at[0])
  21860. .count();
  21861. EXPECT_GE(interval_ms, 100);
  21862. }
  21863. // Test: Last-Event-ID sent on reconnect
  21864. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21865. std::atomic<int> connection_count{0};
  21866. std::vector<std::string> received_last_event_ids;
  21867. std::mutex id_mutex;
  21868. // Endpoint that checks Last-Event-ID header and sends event with ID
  21869. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21870. int conn = connection_count.fetch_add(1);
  21871. // Capture the Last-Event-ID header from each connection
  21872. {
  21873. std::lock_guard<std::mutex> lock(id_mutex);
  21874. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21875. }
  21876. res.set_chunked_content_provider(
  21877. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21878. if (offset == 0) {
  21879. std::string event =
  21880. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21881. sink.write(event.data(), event.size());
  21882. }
  21883. return false;
  21884. });
  21885. });
  21886. Client client("localhost", get_port());
  21887. sse::SSEClient sse(client, "/reconnect-with-id");
  21888. sse.set_reconnect_interval(100);
  21889. sse.set_max_reconnect_attempts(3);
  21890. sse.start_async();
  21891. // Wait for at least 2 connections
  21892. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21893. sse.stop();
  21894. // Verify behavior
  21895. std::lock_guard<std::mutex> lock(id_mutex);
  21896. EXPECT_GE(received_last_event_ids.size(), 2u);
  21897. // First connection should have no Last-Event-ID
  21898. if (!received_last_event_ids.empty()) {
  21899. EXPECT_EQ(received_last_event_ids[0], "");
  21900. }
  21901. // Second connection should have Last-Event-ID from first connection
  21902. if (received_last_event_ids.size() >= 2) {
  21903. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21904. }
  21905. }
  21906. // Test: set_headers updates headers used on reconnect
  21907. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21908. std::vector<std::string> received_tokens;
  21909. std::mutex token_mutex;
  21910. // Endpoint that captures Authorization header
  21911. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21912. {
  21913. std::lock_guard<std::mutex> lock(token_mutex);
  21914. received_tokens.push_back(req.get_header_value("Authorization"));
  21915. }
  21916. res.set_chunked_content_provider(
  21917. "text/event-stream", [](size_t offset, DataSink &sink) {
  21918. if (offset == 0) {
  21919. std::string event = "data: hello\n\n";
  21920. sink.write(event.data(), event.size());
  21921. }
  21922. return false; // Close connection to trigger reconnect
  21923. });
  21924. });
  21925. Client client("localhost", get_port());
  21926. Headers headers = {{"Authorization", "Bearer old-token"}};
  21927. sse::SSEClient sse(client, "/auth-check", headers);
  21928. // Update headers on each successful connection
  21929. sse.on_open(
  21930. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21931. sse.set_reconnect_interval(100);
  21932. sse.set_max_reconnect_attempts(3);
  21933. sse.start_async();
  21934. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21935. sse.stop();
  21936. std::lock_guard<std::mutex> lock(token_mutex);
  21937. ASSERT_GE(received_tokens.size(), 2u);
  21938. // First connection uses original header
  21939. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21940. // Second connection uses updated header from set_headers
  21941. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21942. }
  21943. // Test: 401 allows reconnection (so on_error can refresh headers)
  21944. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21945. std::atomic<int> connection_count{0};
  21946. // Endpoint: returns 401 on first attempt, 200 on second
  21947. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21948. int conn = connection_count.fetch_add(1);
  21949. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21950. res.status = StatusCode::Unauthorized_401;
  21951. res.set_content("Unauthorized", "text/plain");
  21952. return;
  21953. }
  21954. res.set_chunked_content_provider(
  21955. "text/event-stream", [](size_t offset, DataSink &sink) {
  21956. if (offset == 0) {
  21957. std::string event = "data: authenticated\n\n";
  21958. sink.write(event.data(), event.size());
  21959. }
  21960. return false;
  21961. });
  21962. });
  21963. Client client("localhost", get_port());
  21964. Headers headers = {{"Authorization", "Bearer expired"}};
  21965. sse::SSEClient sse(client, "/auth-retry", headers);
  21966. std::atomic<bool> message_received{false};
  21967. // Refresh token on error
  21968. sse.on_error(
  21969. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21970. sse.on_message([&](const sse::SSEMessage &msg) {
  21971. if (msg.data == "authenticated") { message_received.store(true); }
  21972. });
  21973. sse.set_reconnect_interval(100);
  21974. sse.set_max_reconnect_attempts(3);
  21975. sse.start_async();
  21976. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21977. sse.stop();
  21978. // Should have reconnected after 401 and succeeded with new token
  21979. EXPECT_GE(connection_count.load(), 2);
  21980. EXPECT_TRUE(message_received.load());
  21981. }
  21982. TEST(Issue2318Test, EmptyHostString) {
  21983. {
  21984. httplib::Client cli_empty("", PORT);
  21985. auto res = cli_empty.Get("/");
  21986. ASSERT_FALSE(res);
  21987. EXPECT_EQ(httplib::Error::Connection, res.error());
  21988. }
  21989. {
  21990. httplib::Client cli(" ", PORT);
  21991. auto res = cli.Get("/");
  21992. ASSERT_FALSE(res);
  21993. EXPECT_EQ(httplib::Error::Connection, res.error());
  21994. }
  21995. }
  21996. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21997. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21998. Server svr;
  21999. // Set a small payload limit (1KB)
  22000. svr.set_payload_max_length(1024);
  22001. svr.Post("/test", [&](const Request &req, Response &res) {
  22002. res.set_content("Body size: " + std::to_string(req.body.size()),
  22003. "text/plain");
  22004. });
  22005. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22006. auto se = detail::scope_exit([&] {
  22007. svr.stop();
  22008. listen_thread.join();
  22009. });
  22010. svr.wait_until_ready();
  22011. // Create data that compresses well but exceeds limit when decompressed
  22012. // 8KB of repeated null bytes compresses to a very small size
  22013. std::string original_data(8 * 1024, '\0');
  22014. // Compress the data using gzip
  22015. std::string compressed_data;
  22016. detail::gzip_compressor compressor;
  22017. compressor.compress(original_data.data(), original_data.size(), true,
  22018. [&](const char *data, size_t size) {
  22019. compressed_data.append(data, size);
  22020. return true;
  22021. });
  22022. // Verify compression worked (compressed should be much smaller)
  22023. ASSERT_LT(compressed_data.size(), original_data.size());
  22024. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22025. // Send compressed data with Content-Encoding: gzip
  22026. Client cli(HOST, PORT);
  22027. Headers headers = {{"Content-Encoding", "gzip"}};
  22028. auto res =
  22029. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22030. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22032. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22033. }
  22034. #endif
  22035. // ============================================================================
  22036. // OpenSSL-Specific Tests
  22037. // ============================================================================
  22038. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22039. X509 *readCertificate(const std::string &strFileName) {
  22040. std::ifstream inStream(strFileName);
  22041. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22042. std::istreambuf_iterator<char>());
  22043. if (strCertPEM.empty()) return (nullptr);
  22044. BIO *pbCert = BIO_new(BIO_s_mem());
  22045. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22046. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22047. BIO_free(pbCert);
  22048. return (pCert);
  22049. }
  22050. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22051. std::ifstream inStream(strFileName);
  22052. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22053. std::istreambuf_iterator<char>());
  22054. if (strPrivateKeyPEM.empty()) return (nullptr);
  22055. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22056. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22057. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22058. BIO_free(pbPrivKey);
  22059. return (pPrivateKey);
  22060. }
  22061. TEST(BindServerTest, UpdateCerts) {
  22062. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22063. int port = svr.bind_to_any_port("0.0.0.0");
  22064. ASSERT_TRUE(svr.is_valid());
  22065. ASSERT_TRUE(port > 0);
  22066. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22067. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22068. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22069. ASSERT_TRUE(cert != nullptr);
  22070. ASSERT_TRUE(ca_cert != nullptr);
  22071. ASSERT_TRUE(key != nullptr);
  22072. X509_STORE *cert_store = X509_STORE_new();
  22073. X509_STORE_add_cert(cert_store, ca_cert);
  22074. // svr.update_certs(cert, key, cert_store); // deprecated
  22075. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22076. CLIENT_CA_CERT_FILE);
  22077. ASSERT_TRUE(svr.is_valid());
  22078. svr.stop();
  22079. X509_STORE_free(cert_store);
  22080. X509_free(cert);
  22081. X509_free(ca_cert);
  22082. EVP_PKEY_free(key);
  22083. }
  22084. // Test that update_certs() updates client CA list correctly
  22085. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22086. // Start with file-based constructor
  22087. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22088. ASSERT_TRUE(svr.is_valid());
  22089. // Initially no client CA list should be set
  22090. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22091. ASSERT_TRUE(ssl_ctx != nullptr);
  22092. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22093. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22094. // Now update with client CA (PEM string)
  22095. std::string cert_pem, key_pem, ca_pem;
  22096. read_file(SERVER_CERT_FILE, cert_pem);
  22097. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22098. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22099. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22100. ASSERT_TRUE(svr.is_valid());
  22101. // Now client CA list should be set
  22102. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22103. ASSERT_TRUE(ca_list_after != nullptr);
  22104. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22105. }
  22106. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22107. // Test that the file-path SSLServer constructor properly sets the client CA
  22108. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22110. ASSERT_TRUE(svr.is_valid());
  22111. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22112. ASSERT_TRUE(ssl_ctx != nullptr);
  22113. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22114. ASSERT_TRUE(ca_list != nullptr);
  22115. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22116. }
  22117. #endif
  22118. // ============================================================================
  22119. // MbedTLS-Specific Tests
  22120. // ============================================================================
  22121. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22122. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22123. using namespace httplib::tls;
  22124. // Track if callback was invoked
  22125. bool callback_invoked = false;
  22126. // The callback receives void* ctx which is actually MbedTlsContext*
  22127. // We can access the mbedtls_ssl_config via the context
  22128. auto setup_callback = [&callback_invoked](void *ctx) {
  22129. callback_invoked = true;
  22130. // Cast to MbedTlsContext* to access the ssl config
  22131. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22132. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22133. // Use static variables to hold certificate data (simplified for test)
  22134. static mbedtls_x509_crt own_cert;
  22135. static mbedtls_pk_context own_key;
  22136. static mbedtls_x509_crt ca_chain;
  22137. static bool initialized = false;
  22138. if (!initialized) {
  22139. mbedtls_x509_crt_init(&own_cert);
  22140. mbedtls_pk_init(&own_key);
  22141. mbedtls_x509_crt_init(&ca_chain);
  22142. // Load server certificate
  22143. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22144. return false;
  22145. }
  22146. // Load server private key.
  22147. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22148. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22149. #if MBEDTLS_VERSION_MAJOR == 3
  22150. ,
  22151. mbedtls_ctr_drbg_random, nullptr
  22152. #endif
  22153. ) != 0) {
  22154. return false;
  22155. }
  22156. // Load CA chain for client verification
  22157. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22158. return false;
  22159. }
  22160. initialized = true;
  22161. }
  22162. // Configure the SSL config
  22163. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22164. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22165. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22166. // Set minimum TLS version using mbedTLS native API
  22167. #if MBEDTLS_VERSION_MAJOR >= 3
  22168. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22169. #else
  22170. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22171. MBEDTLS_SSL_MINOR_VERSION_3);
  22172. #endif
  22173. return true;
  22174. };
  22175. SSLServer svr(setup_callback);
  22176. ASSERT_TRUE(svr.is_valid());
  22177. ASSERT_TRUE(callback_invoked);
  22178. svr.Get("/test", [&](const Request &req, Response &res) {
  22179. res.set_content("test", "text/plain");
  22180. auto cert = req.peer_cert();
  22181. ASSERT_TRUE(static_cast<bool>(cert));
  22182. auto common_name = cert.subject_cn();
  22183. EXPECT_EQ("Common Name", common_name);
  22184. });
  22185. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22186. auto se = detail::scope_exit([&] {
  22187. svr.stop();
  22188. t.join();
  22189. ASSERT_FALSE(svr.is_running());
  22190. });
  22191. svr.wait_until_ready();
  22192. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22193. cli.enable_server_certificate_verification(false);
  22194. cli.set_connection_timeout(30);
  22195. auto res = cli.Get("/test");
  22196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22197. ASSERT_EQ(StatusCode::OK_200, res->status);
  22198. }
  22199. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22200. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22201. // keep-alive SSL session, which reads through that config in
  22202. // mbedtls_ssl_close_notify.
  22203. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22204. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22205. ASSERT_TRUE(svr.is_valid());
  22206. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22207. res.set_content("test", "text/plain");
  22208. });
  22209. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22210. auto se = detail::scope_exit([&] {
  22211. svr.stop();
  22212. t.join();
  22213. ASSERT_FALSE(svr.is_running());
  22214. });
  22215. svr.wait_until_ready();
  22216. {
  22217. SSLClient cli(HOST, PORT);
  22218. cli.enable_server_certificate_verification(false);
  22219. cli.set_keep_alive(true);
  22220. auto res = cli.Get("/test");
  22221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22222. ASSERT_EQ(StatusCode::OK_200, res->status);
  22223. // cli is destructed here with the keep-alive SSL session still open.
  22224. }
  22225. }
  22226. #endif
  22227. // WebSocket Tests
  22228. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22229. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22230. // defining the meaning of these bits has been negotiated.
  22231. auto make_frame = [](uint8_t first_byte) {
  22232. std::string frame;
  22233. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22234. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22235. frame += "Hello";
  22236. return frame;
  22237. };
  22238. // RSV1 set (0x40)
  22239. {
  22240. detail::BufferStream strm;
  22241. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22242. ws::Opcode opcode;
  22243. std::string payload;
  22244. bool fin;
  22245. EXPECT_EQ(
  22246. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22247. ws::impl::FrameRead::Fail);
  22248. }
  22249. // RSV2 set (0x20)
  22250. {
  22251. detail::BufferStream strm;
  22252. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22253. ws::Opcode opcode;
  22254. std::string payload;
  22255. bool fin;
  22256. EXPECT_EQ(
  22257. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22258. ws::impl::FrameRead::Fail);
  22259. }
  22260. // RSV3 set (0x10)
  22261. {
  22262. detail::BufferStream strm;
  22263. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22264. ws::Opcode opcode;
  22265. std::string payload;
  22266. bool fin;
  22267. EXPECT_EQ(
  22268. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22269. ws::impl::FrameRead::Fail);
  22270. }
  22271. // No RSV bits set - should succeed
  22272. {
  22273. detail::BufferStream strm;
  22274. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22275. ws::Opcode opcode;
  22276. std::string payload;
  22277. bool fin;
  22278. EXPECT_EQ(
  22279. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22280. ws::impl::FrameRead::Ok);
  22281. EXPECT_EQ(ws::Opcode::Text, opcode);
  22282. EXPECT_EQ("Hello", payload);
  22283. EXPECT_TRUE(fin);
  22284. }
  22285. }
  22286. TEST(WebSocketTest, ControlFrameValidation) {
  22287. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22288. // payload length <= 125.
  22289. // Ping with FIN=0 - must be rejected
  22290. {
  22291. detail::BufferStream strm;
  22292. std::string frame;
  22293. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22294. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22295. strm.write(frame.data(), frame.size());
  22296. ws::Opcode opcode;
  22297. std::string payload;
  22298. bool fin;
  22299. EXPECT_EQ(
  22300. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22301. ws::impl::FrameRead::Fail);
  22302. }
  22303. // Close with FIN=0 - must be rejected
  22304. {
  22305. detail::BufferStream strm;
  22306. std::string frame;
  22307. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22308. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22309. strm.write(frame.data(), frame.size());
  22310. ws::Opcode opcode;
  22311. std::string payload;
  22312. bool fin;
  22313. EXPECT_EQ(
  22314. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22315. ws::impl::FrameRead::Fail);
  22316. }
  22317. // Ping with payload_len=126 (extended length) - must be rejected
  22318. {
  22319. detail::BufferStream strm;
  22320. std::string frame;
  22321. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22322. frame += static_cast<char>(126); // payload_len=126 (>125)
  22323. frame += static_cast<char>(0x00); // extended length high byte
  22324. frame += static_cast<char>(126); // extended length low byte
  22325. frame += std::string(126, 'x');
  22326. strm.write(frame.data(), frame.size());
  22327. ws::Opcode opcode;
  22328. std::string payload;
  22329. bool fin;
  22330. EXPECT_EQ(
  22331. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22332. ws::impl::FrameRead::Fail);
  22333. }
  22334. // Ping with FIN=1 and payload_len=125 - should succeed
  22335. {
  22336. detail::BufferStream strm;
  22337. std::string frame;
  22338. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22339. frame += static_cast<char>(125); // payload_len=125
  22340. frame += std::string(125, 'x');
  22341. strm.write(frame.data(), frame.size());
  22342. ws::Opcode opcode;
  22343. std::string payload;
  22344. bool fin;
  22345. EXPECT_EQ(
  22346. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22347. ws::impl::FrameRead::Ok);
  22348. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22349. EXPECT_EQ(125u, payload.size());
  22350. EXPECT_TRUE(fin);
  22351. }
  22352. }
  22353. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22354. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22355. // length MUST be 0.
  22356. // MSB set - must be rejected
  22357. {
  22358. detail::BufferStream strm;
  22359. std::string frame;
  22360. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22361. frame += static_cast<char>(127); // 64-bit extended length
  22362. frame += static_cast<char>(0x80); // MSB set (invalid)
  22363. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22364. strm.write(frame.data(), frame.size());
  22365. ws::Opcode opcode;
  22366. std::string payload;
  22367. bool fin;
  22368. EXPECT_EQ(
  22369. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22370. ws::impl::FrameRead::Fail);
  22371. }
  22372. // MSB clear - should pass length parsing (will be rejected by max_len,
  22373. // but that's a different check; use a small length to verify)
  22374. {
  22375. detail::BufferStream strm;
  22376. std::string frame;
  22377. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22378. frame += static_cast<char>(127); // 64-bit extended length
  22379. frame += std::string(7, '\0'); // high bytes = 0
  22380. frame += static_cast<char>(0x03); // length = 3
  22381. frame += "abc";
  22382. strm.write(frame.data(), frame.size());
  22383. ws::Opcode opcode;
  22384. std::string payload;
  22385. bool fin;
  22386. EXPECT_EQ(
  22387. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22388. ws::impl::FrameRead::Ok);
  22389. EXPECT_EQ(ws::Opcode::Text, opcode);
  22390. EXPECT_EQ("abc", payload);
  22391. }
  22392. }
  22393. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22394. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22395. // Valid UTF-8
  22396. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22397. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22398. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22399. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22400. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22401. // Invalid UTF-8
  22402. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22403. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22404. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22405. EXPECT_FALSE(
  22406. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22407. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22408. }
  22409. TEST(WebSocketTest, ConnectAndDisconnect) {
  22410. Server svr;
  22411. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22412. std::string msg;
  22413. while (ws.read(msg)) {}
  22414. });
  22415. auto port = svr.bind_to_any_port(HOST);
  22416. std::thread t([&]() { svr.listen_after_bind(); });
  22417. svr.wait_until_ready();
  22418. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22419. auto res = client.connect();
  22420. ASSERT_TRUE(res);
  22421. EXPECT_EQ(Error::Success, res.error());
  22422. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22423. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22424. EXPECT_TRUE(client.is_open());
  22425. client.close();
  22426. EXPECT_FALSE(client.is_open());
  22427. svr.stop();
  22428. t.join();
  22429. }
  22430. TEST(WebSocketTest, ValidURL) {
  22431. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22432. EXPECT_TRUE(ws1.is_valid());
  22433. ws::WebSocketClient ws2("ws://example.com/path");
  22434. EXPECT_TRUE(ws2.is_valid());
  22435. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22436. EXPECT_TRUE(ws3.is_valid());
  22437. #ifdef CPPHTTPLIB_SSL_ENABLED
  22438. ws::WebSocketClient wss1("wss://example.com/path");
  22439. EXPECT_TRUE(wss1.is_valid());
  22440. ws::WebSocketClient wss2("wss://example.com:443/path");
  22441. EXPECT_TRUE(wss2.is_valid());
  22442. #endif
  22443. }
  22444. TEST(WebSocketTest, InvalidURL) {
  22445. // No scheme
  22446. ws::WebSocketClient ws1("localhost:8080/path");
  22447. EXPECT_FALSE(ws1.is_valid());
  22448. // No path
  22449. ws::WebSocketClient ws2("ws://localhost:8080");
  22450. EXPECT_FALSE(ws2.is_valid());
  22451. // Empty string
  22452. ws::WebSocketClient ws3("");
  22453. EXPECT_FALSE(ws3.is_valid());
  22454. // Missing host
  22455. ws::WebSocketClient ws4("ws://:8080/path");
  22456. EXPECT_FALSE(ws4.is_valid());
  22457. // Port number overflow — should not crash
  22458. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22459. EXPECT_FALSE(ws5.is_valid());
  22460. // Port out of range
  22461. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22462. EXPECT_FALSE(ws6.is_valid());
  22463. }
  22464. TEST(WebSocketTest, UnsupportedScheme) {
  22465. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22466. ws::WebSocketClient ws1("http://localhost:8080/path");
  22467. EXPECT_FALSE(ws1.is_valid());
  22468. ws::WebSocketClient ws2("https://localhost:8080/path");
  22469. EXPECT_FALSE(ws2.is_valid());
  22470. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22471. EXPECT_FALSE(ws3.is_valid());
  22472. #else
  22473. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22474. std::invalid_argument);
  22475. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22476. std::invalid_argument);
  22477. #endif
  22478. }
  22479. TEST(WebSocketTest, ConnectWhenInvalid) {
  22480. ws::WebSocketClient ws("not a valid url");
  22481. EXPECT_FALSE(ws.is_valid());
  22482. auto res = ws.connect();
  22483. EXPECT_FALSE(res);
  22484. EXPECT_EQ(Error::Connection, res.error());
  22485. EXPECT_EQ(-1, res.status());
  22486. }
  22487. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22488. // Grab a port that is free, then close it again so nothing listens there
  22489. Server svr;
  22490. auto port = svr.bind_to_any_port(HOST);
  22491. svr.stop();
  22492. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22493. auto res = client.connect();
  22494. ASSERT_FALSE(res);
  22495. EXPECT_EQ(Error::Connection, res.error());
  22496. EXPECT_EQ(-1, res.status());
  22497. }
  22498. TEST(WebSocketTest, DefaultPort) {
  22499. ws::WebSocketClient ws1("ws://example.com/path");
  22500. EXPECT_TRUE(ws1.is_valid());
  22501. // ws:// defaults to port 80 (verified by successful parse)
  22502. #ifdef CPPHTTPLIB_SSL_ENABLED
  22503. ws::WebSocketClient ws2("wss://example.com/path");
  22504. EXPECT_TRUE(ws2.is_valid());
  22505. // wss:// defaults to port 443 (verified by successful parse)
  22506. #endif
  22507. }
  22508. TEST(WebSocketTest, IPv6LiteralAddress) {
  22509. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22510. EXPECT_TRUE(ws1.is_valid());
  22511. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22512. EXPECT_TRUE(ws2.is_valid());
  22513. }
  22514. TEST(WebSocketTest, ComplexPath) {
  22515. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22516. EXPECT_TRUE(ws1.is_valid());
  22517. ws::WebSocketClient ws2("ws://localhost:8080/");
  22518. EXPECT_TRUE(ws2.is_valid());
  22519. }
  22520. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22521. Server svr;
  22522. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22523. std::string msg;
  22524. while (ws.read(msg)) {}
  22525. });
  22526. auto port = svr.bind_to_any_port(HOST);
  22527. std::thread t([&]() { svr.listen_after_bind(); });
  22528. svr.wait_until_ready();
  22529. auto another_host = "example.com";
  22530. auto wrong_ip = "192.0.2.1";
  22531. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22532. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22533. ASSERT_TRUE(client.connect());
  22534. EXPECT_TRUE(client.is_open());
  22535. client.close();
  22536. svr.stop();
  22537. t.join();
  22538. }
  22539. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22540. Server svr;
  22541. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22542. std::string msg;
  22543. while (ws.read(msg)) {}
  22544. });
  22545. auto port = svr.bind_to_any_port(HOST);
  22546. std::thread t([&]() { svr.listen_after_bind(); });
  22547. svr.wait_until_ready();
  22548. auto wrong_ip = "192.0.2.1";
  22549. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22550. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22551. client.set_connection_timeout(1);
  22552. client.set_read_timeout(1);
  22553. client.set_write_timeout(1);
  22554. EXPECT_FALSE(client.connect());
  22555. EXPECT_FALSE(client.is_open());
  22556. svr.stop();
  22557. t.join();
  22558. }
  22559. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22560. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22561. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22562. // (RFC 6761) is only a map key and the Host header value.
  22563. auto host = "target.invalid";
  22564. Server svr;
  22565. std::string received_host;
  22566. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22567. received_host = req.get_header_value("Host");
  22568. std::string msg;
  22569. while (ws.read(msg)) {}
  22570. });
  22571. auto port = svr.bind_to_any_port(HOST);
  22572. std::thread t([&]() { svr.listen_after_bind(); });
  22573. // ASSERT_* below returns from the test body, which would leave t joinable
  22574. // and make ~thread call std::terminate.
  22575. auto se = detail::scope_exit([&] {
  22576. svr.stop();
  22577. if (t.joinable()) { t.join(); }
  22578. });
  22579. svr.wait_until_ready();
  22580. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22581. std::to_string(port) + "/ws");
  22582. client.set_hostname_addr_map({{host, HOST}});
  22583. ASSERT_TRUE(client.connect());
  22584. EXPECT_TRUE(client.is_open());
  22585. client.close();
  22586. svr.stop();
  22587. t.join();
  22588. // The mapping only redirects the connection; the identity stays host_.
  22589. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22590. }
  22591. class WebSocketIntegrationTest : public ::testing::Test {
  22592. protected:
  22593. void SetUp() override {
  22594. server_ = httplib::detail::make_unique<Server>();
  22595. setup_server();
  22596. start_server();
  22597. }
  22598. void TearDown() override {
  22599. server_->stop();
  22600. if (server_thread_.joinable()) { server_thread_.join(); }
  22601. }
  22602. void setup_server() {
  22603. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22604. std::string msg;
  22605. ws::ReadResult ret;
  22606. while ((ret = ws.read(msg))) {
  22607. if (ret == ws::Binary) {
  22608. ws.send(msg.data(), msg.size());
  22609. } else {
  22610. ws.send(msg);
  22611. }
  22612. }
  22613. });
  22614. server_->WebSocket("/ws-echo-string",
  22615. [](const Request &, ws::WebSocket &ws) {
  22616. std::string msg;
  22617. while (ws.read(msg)) {
  22618. ws.send("echo: " + msg);
  22619. }
  22620. });
  22621. server_->WebSocket(
  22622. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22623. // Echo back request metadata
  22624. ws.send("path:" + req.path);
  22625. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22626. std::string msg;
  22627. while (ws.read(msg)) {}
  22628. });
  22629. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22630. std::string msg;
  22631. ws.read(msg); // wait for a message
  22632. ws.close();
  22633. });
  22634. server_->WebSocket("/ws-close-status",
  22635. [](const Request &, ws::WebSocket &ws) {
  22636. std::string msg;
  22637. ws.read(msg); // wait for a message
  22638. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22639. });
  22640. server_->WebSocket(
  22641. "/ws-subprotocol",
  22642. [](const Request &, ws::WebSocket &ws) {
  22643. std::string msg;
  22644. while (ws.read(msg)) {
  22645. ws.send(msg);
  22646. }
  22647. },
  22648. [](const std::vector<std::string> &protocols) -> std::string {
  22649. for (const auto &p : protocols) {
  22650. if (p == "graphql-ws") { return p; }
  22651. }
  22652. return "";
  22653. });
  22654. server_->WebSocket(
  22655. "/ws-subprotocol-unoffered",
  22656. [](const Request &, ws::WebSocket &ws) {
  22657. std::string msg;
  22658. while (ws.read(msg)) {
  22659. ws.send(msg);
  22660. }
  22661. },
  22662. [](const std::vector<std::string> &) -> std::string {
  22663. return "admin";
  22664. });
  22665. }
  22666. void start_server() {
  22667. port_ = server_->bind_to_any_port(HOST);
  22668. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22669. server_->wait_until_ready();
  22670. }
  22671. std::unique_ptr<Server> server_;
  22672. std::thread server_thread_;
  22673. int port_ = 0;
  22674. };
  22675. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22676. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22677. "/ws-echo");
  22678. ASSERT_TRUE(client.connect());
  22679. ASSERT_TRUE(client.is_open());
  22680. ASSERT_TRUE(client.send("Hello WebSocket"));
  22681. std::string msg;
  22682. EXPECT_EQ(ws::Text, client.read(msg));
  22683. EXPECT_EQ("Hello WebSocket", msg);
  22684. client.close();
  22685. }
  22686. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22687. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22688. "/ws-echo");
  22689. ASSERT_TRUE(client.connect());
  22690. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22691. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22692. std::string msg;
  22693. EXPECT_EQ(ws::Binary, client.read(msg));
  22694. EXPECT_EQ(binary_data, msg);
  22695. client.close();
  22696. }
  22697. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22698. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22699. "/ws-echo");
  22700. ASSERT_TRUE(client.connect());
  22701. for (int i = 0; i < 10; i++) {
  22702. auto text = "message " + std::to_string(i);
  22703. ASSERT_TRUE(client.send(text));
  22704. std::string msg;
  22705. ASSERT_TRUE(client.read(msg));
  22706. EXPECT_EQ(text, msg);
  22707. }
  22708. client.close();
  22709. }
  22710. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22711. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22712. "/ws-close");
  22713. ASSERT_TRUE(client.connect());
  22714. // Send a message to trigger the server to close
  22715. ASSERT_TRUE(client.send("trigger close"));
  22716. // The server will close, so read should return false
  22717. std::string msg;
  22718. EXPECT_FALSE(client.read(msg));
  22719. EXPECT_FALSE(client.is_open());
  22720. }
  22721. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22722. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22723. "/ws-echo");
  22724. ASSERT_TRUE(client.connect());
  22725. // 128KB message
  22726. std::string large_data(128 * 1024, 'X');
  22727. ASSERT_TRUE(client.send(large_data));
  22728. std::string msg;
  22729. ASSERT_TRUE(client.read(msg));
  22730. EXPECT_EQ(large_data, msg);
  22731. client.close();
  22732. }
  22733. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22734. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22735. "/ws-echo");
  22736. ASSERT_TRUE(client.connect());
  22737. const int num_threads = 4;
  22738. std::vector<std::thread> threads;
  22739. std::atomic<int> send_count{0};
  22740. for (int t = 0; t < num_threads; t++) {
  22741. threads.emplace_back([&client, &send_count, t]() {
  22742. for (int i = 0; i < 5; i++) {
  22743. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22744. if (client.send(text)) { send_count++; }
  22745. }
  22746. });
  22747. }
  22748. for (auto &th : threads) {
  22749. th.join();
  22750. }
  22751. int received = 0;
  22752. std::string msg;
  22753. while (received < send_count.load()) {
  22754. if (!client.read(msg)) { break; }
  22755. received++;
  22756. }
  22757. EXPECT_EQ(send_count.load(), received);
  22758. client.close();
  22759. }
  22760. TEST_F(WebSocketIntegrationTest, ReadString) {
  22761. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22762. "/ws-echo-string");
  22763. ASSERT_TRUE(client.connect());
  22764. ASSERT_TRUE(client.send("hello"));
  22765. std::string msg;
  22766. ASSERT_TRUE(client.read(msg));
  22767. EXPECT_EQ("echo: hello", msg);
  22768. ASSERT_TRUE(client.send("world"));
  22769. ASSERT_TRUE(client.read(msg));
  22770. EXPECT_EQ("echo: world", msg);
  22771. client.close();
  22772. }
  22773. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22774. Headers headers = {{"X-Test-Header", "test-value"}};
  22775. ws::WebSocketClient client(
  22776. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22777. ASSERT_TRUE(client.connect());
  22778. std::string msg;
  22779. ASSERT_TRUE(client.read(msg));
  22780. EXPECT_EQ("path:/ws-request-info", msg);
  22781. ASSERT_TRUE(client.read(msg));
  22782. EXPECT_EQ("header:test-value", msg);
  22783. client.close();
  22784. }
  22785. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22786. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22787. "/ws-echo");
  22788. client.set_read_timeout(1, 0); // 1 second
  22789. ASSERT_TRUE(client.connect());
  22790. // Don't send anything — server echo handler waits for a message, so read()
  22791. // should time out. The connection survives it: nothing was consumed.
  22792. std::string msg;
  22793. EXPECT_EQ(client.read(msg), ws::Timeout);
  22794. EXPECT_TRUE(client.is_open());
  22795. // And it is still usable afterwards.
  22796. EXPECT_TRUE(client.send("after timeout"));
  22797. EXPECT_EQ(client.read(msg), ws::Text);
  22798. EXPECT_EQ(msg, "after timeout");
  22799. }
  22800. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22801. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22802. "/ws-echo");
  22803. client.set_read_timeout(1, 0);
  22804. ASSERT_TRUE(client.connect());
  22805. ASSERT_TRUE(client.send("first"));
  22806. std::string msg;
  22807. ASSERT_EQ(client.read(msg), ws::Text);
  22808. ASSERT_EQ(msg, "first");
  22809. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22810. // not be used with a read timeout: it would reprocess the previous message.
  22811. EXPECT_EQ(client.read(msg), ws::Timeout);
  22812. EXPECT_EQ(msg, "first");
  22813. }
  22814. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22815. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22816. "/ws-echo");
  22817. ASSERT_TRUE(client.connect());
  22818. // Setting it once the connection is open reaches the live stream, not just
  22819. // the seed for the next connect().
  22820. client.set_read_timeout(1, 0);
  22821. std::string msg;
  22822. EXPECT_EQ(client.read(msg), ws::Timeout);
  22823. EXPECT_TRUE(client.is_open());
  22824. }
  22825. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22826. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22827. "/ws-echo");
  22828. client.set_read_timeout(5, 0);
  22829. ASSERT_TRUE(client.connect());
  22830. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22831. // The server should reject it and close the connection.
  22832. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22833. client.send(oversized);
  22834. // The server's read() should have failed due to payload limit,
  22835. // so our read() should return false (connection closed).
  22836. std::string msg;
  22837. EXPECT_FALSE(client.read(msg));
  22838. }
  22839. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22840. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22841. "/ws-echo");
  22842. client.set_read_timeout(10, 0);
  22843. ASSERT_TRUE(client.connect());
  22844. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22845. // This should succeed.
  22846. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22847. ASSERT_TRUE(client.send(at_limit));
  22848. std::string msg;
  22849. ASSERT_TRUE(client.read(msg));
  22850. EXPECT_EQ(at_limit.size(), msg.size());
  22851. client.close();
  22852. }
  22853. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22854. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22855. "/nonexistent");
  22856. auto res = client.connect();
  22857. EXPECT_FALSE(res);
  22858. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22859. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22860. EXPECT_FALSE(client.is_open());
  22861. }
  22862. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22863. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22864. "/ws-echo");
  22865. ASSERT_TRUE(client.connect());
  22866. ASSERT_TRUE(client.send(""));
  22867. std::string msg;
  22868. EXPECT_EQ(ws::Text, client.read(msg));
  22869. EXPECT_EQ("", msg);
  22870. client.close();
  22871. }
  22872. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22873. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22874. "/ws-echo");
  22875. // First connection
  22876. ASSERT_TRUE(client.connect());
  22877. ASSERT_TRUE(client.send("first"));
  22878. std::string msg;
  22879. ASSERT_TRUE(client.read(msg));
  22880. EXPECT_EQ("first", msg);
  22881. client.close();
  22882. EXPECT_FALSE(client.is_open());
  22883. // Reconnect using the same client object
  22884. ASSERT_TRUE(client.connect());
  22885. ASSERT_TRUE(client.is_open());
  22886. ASSERT_TRUE(client.send("second"));
  22887. ASSERT_TRUE(client.read(msg));
  22888. EXPECT_EQ("second", msg);
  22889. client.close();
  22890. }
  22891. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22892. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22893. "/ws-close-status");
  22894. ASSERT_TRUE(client.connect());
  22895. // Trigger the server to close with GoingAway status
  22896. ASSERT_TRUE(client.send("trigger"));
  22897. // read() should return false after receiving the close frame
  22898. std::string msg;
  22899. EXPECT_FALSE(client.read(msg));
  22900. EXPECT_FALSE(client.is_open());
  22901. }
  22902. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22903. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22904. "/ws-echo");
  22905. ASSERT_TRUE(client.connect());
  22906. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22907. EXPECT_FALSE(client.is_open());
  22908. }
  22909. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22910. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22911. ws::WebSocketClient client(
  22912. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22913. ASSERT_TRUE(client.connect());
  22914. // Server should have selected graphql-ws
  22915. EXPECT_EQ("graphql-ws", client.subprotocol());
  22916. client.close();
  22917. }
  22918. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22919. Headers headers;
  22920. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22921. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22922. ws::WebSocketClient client(
  22923. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22924. ASSERT_TRUE(client.connect());
  22925. // The offer on the second field line counts too, so graphql-ws is selected
  22926. EXPECT_EQ("graphql-ws", client.subprotocol());
  22927. client.close();
  22928. }
  22929. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22930. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22931. ws::WebSocketClient client(
  22932. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22933. ASSERT_TRUE(client.connect());
  22934. // Server should not have selected any subprotocol
  22935. EXPECT_TRUE(client.subprotocol().empty());
  22936. client.close();
  22937. }
  22938. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22939. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22940. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22941. "/ws-subprotocol-unoffered",
  22942. headers);
  22943. ASSERT_TRUE(client.connect());
  22944. EXPECT_TRUE(client.subprotocol().empty());
  22945. client.close();
  22946. }
  22947. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22948. // Connect without requesting any subprotocol
  22949. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22950. "/ws-subprotocol");
  22951. ASSERT_TRUE(client.connect());
  22952. EXPECT_TRUE(client.subprotocol().empty());
  22953. client.close();
  22954. }
  22955. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22956. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22957. "/ws-echo");
  22958. client.set_tcp_nodelay(true);
  22959. client.set_connection_timeout(3, 0);
  22960. bool socket_options_called = false;
  22961. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22962. ASSERT_TRUE(client.connect());
  22963. ASSERT_TRUE(client.is_open());
  22964. EXPECT_TRUE(socket_options_called);
  22965. ASSERT_TRUE(client.send("hello"));
  22966. std::string msg;
  22967. auto result = client.read(msg);
  22968. EXPECT_EQ(result, ws::ReadResult::Text);
  22969. EXPECT_EQ(msg, "hello");
  22970. client.close();
  22971. }
  22972. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22973. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22974. "/ws-echo");
  22975. client.set_connection_timeout(std::chrono::seconds(3));
  22976. client.set_write_timeout(std::chrono::seconds(3));
  22977. // A sub-second remainder exercises the seconds/microseconds split.
  22978. client.set_read_timeout(std::chrono::milliseconds(1500));
  22979. ASSERT_TRUE(client.connect());
  22980. auto start = std::chrono::steady_clock::now();
  22981. std::string msg;
  22982. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22983. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22984. std::chrono::steady_clock::now() - start)
  22985. .count();
  22986. // Above 1s so that dropping the microseconds half of the split fails here.
  22987. // Ignoring the setter altogether would not reach this line at all: a client
  22988. // waits forever by default.
  22989. EXPECT_GE(elapsed, 1400);
  22990. EXPECT_LT(elapsed, 30000);
  22991. }
  22992. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22993. Server svr;
  22994. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22995. if (!req.has_header("Authorization")) {
  22996. res.status = StatusCode::Unauthorized_401;
  22997. res.set_content("Unauthorized", "text/plain");
  22998. return Server::HandlerResponse::Handled;
  22999. }
  23000. return Server::HandlerResponse::Unhandled;
  23001. });
  23002. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23003. std::string msg;
  23004. while (ws.read(msg)) {
  23005. ws.send(msg);
  23006. }
  23007. });
  23008. auto port = svr.bind_to_any_port("localhost");
  23009. std::thread t([&]() { svr.listen_after_bind(); });
  23010. svr.wait_until_ready();
  23011. // Without Authorization header - should be rejected before upgrade
  23012. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23013. EXPECT_FALSE(client1.connect());
  23014. // The rejection is framed like any other HTTP response
  23015. {
  23016. Client cli("localhost", port);
  23017. Headers headers = {{"Upgrade", "websocket"},
  23018. {"Connection", "Upgrade"},
  23019. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23020. {"Sec-WebSocket-Version", "13"}};
  23021. auto res = cli.Get("/ws", headers);
  23022. ASSERT_TRUE(res);
  23023. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23024. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23025. EXPECT_EQ("Unauthorized", res->body);
  23026. }
  23027. // With Authorization header - should succeed
  23028. Headers headers = {{"Authorization", "Bearer token123"}};
  23029. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23030. headers);
  23031. ASSERT_TRUE(client2.connect());
  23032. ASSERT_TRUE(client2.send("hello"));
  23033. std::string msg;
  23034. ASSERT_TRUE(client2.read(msg));
  23035. EXPECT_EQ("hello", msg);
  23036. client2.close();
  23037. svr.stop();
  23038. t.join();
  23039. }
  23040. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23041. Server svr;
  23042. std::atomic<int> pre_request_calls{0};
  23043. std::atomic<bool> route_matched{false};
  23044. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23045. pre_request_calls++;
  23046. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23047. if (req.get_header_value("Authorization") != "Bearer token123") {
  23048. res.status = StatusCode::Unauthorized_401;
  23049. res.set_content("Unauthorized", "text/plain");
  23050. return Server::HandlerResponse::Handled;
  23051. }
  23052. return Server::HandlerResponse::Unhandled;
  23053. });
  23054. std::atomic<bool> handler_called{false};
  23055. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23056. handler_called = true;
  23057. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23058. });
  23059. auto port = svr.bind_to_any_port("localhost");
  23060. std::thread t([&]() { svr.listen_after_bind(); });
  23061. svr.wait_until_ready();
  23062. // Without Authorization header - should be rejected before upgrade
  23063. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23064. "/ws/1");
  23065. EXPECT_FALSE(client1.connect());
  23066. EXPECT_FALSE(handler_called);
  23067. EXPECT_EQ(1, pre_request_calls);
  23068. EXPECT_TRUE(route_matched);
  23069. // The rejection is an ordinary HTTP response, not a protocol switch
  23070. {
  23071. Client cli("localhost", port);
  23072. Headers headers = {{"Upgrade", "websocket"},
  23073. {"Connection", "Upgrade"},
  23074. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23075. {"Sec-WebSocket-Version", "13"}};
  23076. auto res = cli.Get("/ws/1", headers);
  23077. ASSERT_TRUE(res);
  23078. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23079. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23080. EXPECT_EQ("Unauthorized", res->body);
  23081. }
  23082. EXPECT_FALSE(handler_called);
  23083. // With Authorization header - should succeed
  23084. Headers headers = {{"Authorization", "Bearer token123"}};
  23085. ws::WebSocketClient client2(
  23086. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23087. ASSERT_TRUE(client2.connect());
  23088. std::string msg;
  23089. ASSERT_TRUE(client2.read(msg));
  23090. EXPECT_EQ("/ws/:id 2", msg);
  23091. EXPECT_TRUE(handler_called);
  23092. client2.close();
  23093. svr.stop();
  23094. t.join();
  23095. }
  23096. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23097. Server svr;
  23098. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23099. // A read timeout is how a handler gets control back. Without it, a handler
  23100. // parked in read() can never write on the connection it is reading.
  23101. ws.set_read_timeout(std::chrono::milliseconds(100));
  23102. std::string msg;
  23103. while (ws.is_open()) {
  23104. auto r = ws.read(msg);
  23105. if (r == httplib::ws::Timeout) {
  23106. ws.send("tick");
  23107. continue;
  23108. }
  23109. if (r == httplib::ws::Fail) { break; }
  23110. ws.send(msg);
  23111. }
  23112. });
  23113. auto port = svr.bind_to_any_port("localhost");
  23114. std::thread t([&]() { svr.listen_after_bind(); });
  23115. svr.wait_until_ready();
  23116. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23117. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23118. ASSERT_TRUE(client.connect());
  23119. // The client sends nothing, so anything it receives came out of the
  23120. // handler's timeout path.
  23121. std::string msg;
  23122. ASSERT_EQ(client.read(msg), ws::Text);
  23123. EXPECT_EQ("tick", msg);
  23124. client.close();
  23125. svr.stop();
  23126. t.join();
  23127. }
  23128. // Stream::read may return fewer bytes than asked for. This is that contract at
  23129. // its worst -- one byte per call -- which is what a frame header straddling a
  23130. // read buffer's boundary looks like to the frame parser.
  23131. class WsByteAtATimeStream : public Stream {
  23132. public:
  23133. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23134. bool is_readable() const override { return true; }
  23135. bool wait_readable() const override { return true; }
  23136. bool wait_writable() const override { return true; }
  23137. ssize_t read(char *ptr, size_t size) override {
  23138. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23139. *ptr = data_[pos_++];
  23140. return 1;
  23141. }
  23142. ssize_t write(const char *, size_t size) override {
  23143. return static_cast<ssize_t>(size);
  23144. }
  23145. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23146. ip = "127.0.0.1";
  23147. port = 0;
  23148. }
  23149. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23150. ip = "127.0.0.1";
  23151. port = 0;
  23152. }
  23153. socket_t socket() const override { return INVALID_SOCKET; }
  23154. time_t duration() const override { return 0; }
  23155. private:
  23156. std::string data_;
  23157. size_t pos_ = 0;
  23158. };
  23159. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23160. // The payload uses the 16-bit extended length, so the header, the length
  23161. // and the mask key are all multi-byte fields here. Each used to be read
  23162. // with a single read() call, which fails as soon as one is split. The
  23163. // payload is also a little over one read chunk, so it is read in two.
  23164. std::string body;
  23165. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23166. body += static_cast<char>(i % 251);
  23167. }
  23168. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23169. std::string frame;
  23170. frame += static_cast<char>(0x81); // FIN + Text
  23171. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23172. frame += static_cast<char>(body.size() >> 8);
  23173. frame += static_cast<char>(body.size() & 0xff);
  23174. for (size_t i = 0; i < 4; i++) {
  23175. frame += static_cast<char>(mask[i]);
  23176. }
  23177. for (size_t i = 0; i < body.size(); i++) {
  23178. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23179. }
  23180. WsByteAtATimeStream strm(frame);
  23181. ws::Opcode opcode;
  23182. std::string payload;
  23183. bool fin = false;
  23184. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23185. /*expect_masked=*/true, body.size()),
  23186. ws::impl::FrameRead::Ok);
  23187. EXPECT_TRUE(fin);
  23188. EXPECT_EQ(opcode, ws::Opcode::Text);
  23189. EXPECT_EQ(payload, body);
  23190. }
  23191. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23192. std::string body(2000, 'x');
  23193. std::string frame;
  23194. frame += static_cast<char>(0x82); // FIN + Binary
  23195. frame += static_cast<char>(126); // 16-bit length follows
  23196. frame += static_cast<char>(body.size() >> 8);
  23197. frame += static_cast<char>(body.size() & 0xff);
  23198. frame += body;
  23199. detail::BufferStream strm;
  23200. strm.write(frame.data(), frame.size());
  23201. ws::Opcode opcode;
  23202. std::string payload;
  23203. bool fin;
  23204. EXPECT_EQ(
  23205. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23206. ws::impl::FrameRead::Ok);
  23207. EXPECT_EQ(body, payload);
  23208. }
  23209. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23210. // The header announces the largest payload allowed, and only 3 bytes of it
  23211. // ever arrive.
  23212. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23213. std::string frame;
  23214. frame += static_cast<char>(0x82); // FIN + Binary
  23215. frame += static_cast<char>(127); // 64-bit length follows
  23216. for (int shift = 56; shift >= 0; shift -= 8) {
  23217. frame += static_cast<char>((len >> shift) & 0xff);
  23218. }
  23219. frame += "abc";
  23220. detail::BufferStream strm;
  23221. strm.write(frame.data(), frame.size());
  23222. ws::Opcode opcode;
  23223. std::string payload;
  23224. bool fin;
  23225. EXPECT_EQ(
  23226. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23227. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23228. ws::impl::FrameRead::Fail);
  23229. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23230. }
  23231. TEST(WebSocketTest, QueryStringInHandshake) {
  23232. Server svr;
  23233. std::mutex mtx;
  23234. std::string received_target;
  23235. std::string received_token;
  23236. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23237. {
  23238. std::lock_guard<std::mutex> lock(mtx);
  23239. received_target = req.target;
  23240. if (req.has_param("token")) {
  23241. received_token = req.get_param_value("token");
  23242. }
  23243. }
  23244. std::string msg;
  23245. while (ws.read(msg)) {
  23246. ws.send(msg);
  23247. }
  23248. });
  23249. auto port = svr.bind_to_any_port("localhost");
  23250. std::thread t([&]() { svr.listen_after_bind(); });
  23251. svr.wait_until_ready();
  23252. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23253. "/ws?token=ABC&session=123");
  23254. ASSERT_TRUE(client.connect());
  23255. // Round-trip ensures the handler has run and captured the request.
  23256. ASSERT_TRUE(client.send("hello"));
  23257. std::string msg;
  23258. ASSERT_TRUE(client.read(msg));
  23259. EXPECT_EQ("hello", msg);
  23260. client.close();
  23261. {
  23262. std::lock_guard<std::mutex> lock(mtx);
  23263. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23264. EXPECT_EQ("ABC", received_token);
  23265. }
  23266. svr.stop();
  23267. t.join();
  23268. }
  23269. // Run a handshake against a throwaway server and hand the request the server
  23270. // received back to the caller, so tests can assert on the headers the client
  23271. // actually put on the wire.
  23272. static void capture_websocket_handshake_request(
  23273. const Headers &client_headers,
  23274. std::function<void(const Request &, int port)> verify) {
  23275. Server svr;
  23276. std::mutex mtx;
  23277. Request received;
  23278. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23279. {
  23280. std::lock_guard<std::mutex> lock(mtx);
  23281. received = req;
  23282. }
  23283. std::string msg;
  23284. while (ws.read(msg)) {
  23285. ws.send(msg);
  23286. }
  23287. });
  23288. auto port = svr.bind_to_any_port("localhost");
  23289. std::thread t([&]() { svr.listen_after_bind(); });
  23290. auto se = detail::scope_exit([&] {
  23291. svr.stop();
  23292. t.join();
  23293. });
  23294. svr.wait_until_ready();
  23295. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23296. client_headers);
  23297. ASSERT_TRUE(client.connect());
  23298. ASSERT_TRUE(client.send("hello"));
  23299. std::string msg;
  23300. ASSERT_TRUE(client.read(msg));
  23301. client.close();
  23302. {
  23303. std::lock_guard<std::mutex> lock(mtx);
  23304. verify(received, port);
  23305. }
  23306. }
  23307. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23308. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23309. // Non-default port must be present in the Host header. Default ports
  23310. // (80/443) are omitted; that logic is covered by
  23311. // MakeHostAndPortStringTest.
  23312. EXPECT_EQ("localhost:" + std::to_string(port),
  23313. req.get_header_value("Host"));
  23314. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23315. req.get_header_value("User-Agent"));
  23316. EXPECT_FALSE(req.has_header("Accept"));
  23317. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23318. EXPECT_FALSE(req.has_header("Content-Length"));
  23319. });
  23320. }
  23321. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23322. capture_websocket_handshake_request(
  23323. {{"Host", "example.com"},
  23324. {"User-Agent", "custom-agent"},
  23325. {"X-Custom", "value"}},
  23326. [](const Request &req, int) {
  23327. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23328. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23329. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23330. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23331. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23332. });
  23333. }
  23334. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23335. capture_websocket_handshake_request(
  23336. {{"Upgrade", "bogus"},
  23337. {"Connection", "close"},
  23338. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23339. {"Sec-WebSocket-Version", "8"}},
  23340. [](const Request &req, int) {
  23341. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23342. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23343. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23344. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23345. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23346. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23347. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23348. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23349. req.get_header_value("Sec-WebSocket-Key"));
  23350. });
  23351. }
  23352. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23353. // A header the client refuses to send must abort the handshake before any
  23354. // part of it reaches the wire; a lone request line would otherwise sit in
  23355. // the peer's buffer as a truncated request.
  23356. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23357. ASSERT_NE(INVALID_SOCKET, srv);
  23358. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23359. sockaddr_in addr{};
  23360. addr.sin_family = AF_INET;
  23361. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23362. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23363. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23364. ASSERT_EQ(0, ::listen(srv, 1));
  23365. sockaddr_in bound{};
  23366. socklen_t bound_len = sizeof(bound);
  23367. ASSERT_EQ(
  23368. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23369. auto port = ntohs(bound.sin_port);
  23370. ssize_t received = -1;
  23371. std::thread t([&] {
  23372. // Bound every blocking call so a regression fails the test with a bad
  23373. // value instead of hanging the suite.
  23374. fd_set rfds;
  23375. FD_ZERO(&rfds);
  23376. FD_SET(srv, &rfds);
  23377. timeval tv{5, 0};
  23378. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23379. 0) {
  23380. return;
  23381. }
  23382. sockaddr_in cli_addr{};
  23383. socklen_t cli_len = sizeof(cli_addr);
  23384. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23385. if (cli == INVALID_SOCKET) { return; }
  23386. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23387. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23388. char buf[4096];
  23389. received = ::recv(cli, buf, sizeof(buf), 0);
  23390. });
  23391. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23392. // connect() has already shut the socket down by the time it returns false,
  23393. // so the peer sees EOF without waiting for the client to be destroyed.
  23394. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23395. {{"X-Bad", "a\r\nInjected: 1"}});
  23396. EXPECT_FALSE(client.connect());
  23397. t.join();
  23398. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23399. EXPECT_EQ(0, received);
  23400. }
  23401. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23402. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23403. // contains "upgrade" as a substring is a different token and must not
  23404. // start a WebSocket handshake.
  23405. auto make_request = [](const std::vector<std::string> &connection_values) {
  23406. Request req;
  23407. req.method = "GET";
  23408. req.headers.emplace("Upgrade", "websocket");
  23409. for (const auto &value : connection_values) {
  23410. req.headers.emplace("Connection", value);
  23411. }
  23412. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23413. req.headers.emplace("Sec-WebSocket-Version", "13");
  23414. return req;
  23415. };
  23416. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23417. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23418. EXPECT_TRUE(
  23419. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23420. EXPECT_TRUE(
  23421. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23422. EXPECT_TRUE(
  23423. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23424. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23425. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23426. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23427. EXPECT_FALSE(
  23428. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23429. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23430. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23431. }
  23432. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23433. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23434. // asks recipients to match each protocol-name case-insensitively, and RFC
  23435. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23436. // client naming websocket alongside another protocol, or on a second field
  23437. // line, is offering websocket; a value that merely contains "websocket" as a
  23438. // substring is a different protocol name and is not.
  23439. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23440. Request req;
  23441. req.method = "GET";
  23442. for (const auto &value : upgrade_values) {
  23443. req.headers.emplace("Upgrade", value);
  23444. }
  23445. req.headers.emplace("Connection", "Upgrade");
  23446. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23447. req.headers.emplace("Sec-WebSocket-Version", "13");
  23448. return req;
  23449. };
  23450. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23451. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23452. EXPECT_TRUE(
  23453. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23454. EXPECT_TRUE(
  23455. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23456. EXPECT_TRUE(
  23457. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23458. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23459. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23460. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23461. EXPECT_FALSE(
  23462. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23463. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23464. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23465. }
  23466. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23467. Server svr;
  23468. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23469. auto port = svr.bind_to_any_port("localhost");
  23470. std::thread t([&]() { svr.listen_after_bind(); });
  23471. auto se = detail::scope_exit([&] {
  23472. svr.stop();
  23473. t.join();
  23474. });
  23475. svr.wait_until_ready();
  23476. Headers headers = {{"Upgrade", "websocket"},
  23477. {"Connection", "notupgrade"},
  23478. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23479. {"Sec-WebSocket-Version", "13"}};
  23480. Client cli("localhost", port);
  23481. auto res = cli.Get("/ws", headers);
  23482. // The route exists only as a WebSocket route, so a request that fails the
  23483. // handshake check falls through to ordinary routing.
  23484. ASSERT_TRUE(res);
  23485. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23486. }
  23487. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  23488. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  23489. // Connection value is the only thing left for the client to reject.
  23490. Server svr;
  23491. svr.Get("/ws", [](const Request &req, Response &res) {
  23492. res.status = StatusCode::SwitchingProtocol_101;
  23493. res.set_header("Upgrade", "websocket");
  23494. res.set_header("Connection", "notupgrade");
  23495. res.set_header("Sec-WebSocket-Accept",
  23496. detail::websocket_accept_key(
  23497. req.get_header_value("Sec-WebSocket-Key")));
  23498. });
  23499. auto port = svr.bind_to_any_port("localhost");
  23500. std::thread t([&]() { svr.listen_after_bind(); });
  23501. auto se = detail::scope_exit([&] {
  23502. svr.stop();
  23503. t.join();
  23504. });
  23505. svr.wait_until_ready();
  23506. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23507. auto res = client.connect();
  23508. EXPECT_FALSE(res);
  23509. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23510. EXPECT_FALSE(client.is_open());
  23511. }
  23512. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  23513. Server svr;
  23514. svr.Get("/ws", [](const Request &req, Response &res) {
  23515. res.status = StatusCode::SwitchingProtocol_101;
  23516. res.set_header("Upgrade", "websocket");
  23517. res.set_header("Connection", "Upgrade");
  23518. res.set_header("Sec-WebSocket-Accept",
  23519. detail::websocket_accept_key(
  23520. req.get_header_value("Sec-WebSocket-Key")));
  23521. res.set_header("Sec-WebSocket-Protocol", "admin");
  23522. });
  23523. auto port = svr.bind_to_any_port("localhost");
  23524. std::thread t([&]() { svr.listen_after_bind(); });
  23525. auto se = detail::scope_exit([&] {
  23526. svr.stop();
  23527. t.join();
  23528. });
  23529. svr.wait_until_ready();
  23530. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23531. // Server selects a subprotocol the client never offered
  23532. {
  23533. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23534. ws::WebSocketClient client(url, headers);
  23535. auto res = client.connect();
  23536. EXPECT_FALSE(res);
  23537. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23538. EXPECT_FALSE(client.is_open());
  23539. EXPECT_TRUE(client.subprotocol().empty());
  23540. }
  23541. // Client offered none but the server named one anyway
  23542. {
  23543. ws::WebSocketClient client(url);
  23544. auto res = client.connect();
  23545. EXPECT_FALSE(res);
  23546. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23547. EXPECT_FALSE(client.is_open());
  23548. EXPECT_TRUE(client.subprotocol().empty());
  23549. }
  23550. }
  23551. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23552. // The socket path doubles as the URL host, so it must not contain '/'.
  23553. const char *shard = getenv("GTEST_SHARD_INDEX");
  23554. const std::string sock_path =
  23555. shard ? std::string("httplib-ws-") + shard + ".sock"
  23556. : std::string("httplib-ws.sock");
  23557. std::remove(sock_path.c_str());
  23558. Server svr;
  23559. std::mutex mtx;
  23560. std::string received_host;
  23561. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23562. {
  23563. std::lock_guard<std::mutex> lock(mtx);
  23564. received_host = req.get_header_value("Host");
  23565. }
  23566. std::string msg;
  23567. while (ws.read(msg)) {
  23568. ws.send(msg);
  23569. }
  23570. });
  23571. svr.set_address_family(AF_UNIX);
  23572. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  23573. auto se = detail::scope_exit([&] {
  23574. svr.stop();
  23575. t.join();
  23576. std::remove(sock_path.c_str());
  23577. });
  23578. svr.wait_until_ready();
  23579. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  23580. client.set_address_family(AF_UNIX);
  23581. ASSERT_TRUE(client.connect());
  23582. ASSERT_TRUE(client.send("hello"));
  23583. std::string msg;
  23584. ASSERT_TRUE(client.read(msg));
  23585. client.close();
  23586. {
  23587. std::lock_guard<std::mutex> lock(mtx);
  23588. // There is no host:port for a Unix socket, so the same "localhost"
  23589. // placeholder the HTTP client uses is expected.
  23590. EXPECT_EQ("localhost", received_host);
  23591. }
  23592. }
  23593. // Two threads must never parse WebSocket frames from the same stream.
  23594. // close() used to read the peer's Close reply with its own frame read, so it
  23595. // raced a reader thread that was in the middle of a payload: the payload loop
  23596. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  23597. // so bytes taken by close() were replaced with bytes from further along the
  23598. // stream. The message kept its length and silently changed content.
  23599. //
  23600. // The raw peer below sends a frame header plus part of the payload, waits for
  23601. // the handler to call close(), and only then sends the rest. Whichever thread
  23602. // would win the race for those bytes, the message must arrive intact, because
  23603. // close() must not touch the stream while read() owns it.
  23604. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23605. #ifndef _WIN32
  23606. signal(SIGPIPE, SIG_IGN);
  23607. #endif
  23608. const size_t payload_len = 120; // fits the 7-bit length field
  23609. const size_t prefix_len = 8;
  23610. const int attempts = 8;
  23611. std::string expected(payload_len, '\0');
  23612. for (size_t i = 0; i < payload_len; i++) {
  23613. expected[i] = static_cast<char>('a' + i % 26);
  23614. }
  23615. std::atomic<bool> peer_stalled{false};
  23616. std::atomic<bool> handler_done{false};
  23617. std::mutex received_mutex;
  23618. std::vector<std::string> received;
  23619. // Bound every wait, so a regression fails the test instead of hanging the
  23620. // suite.
  23621. auto wait_for = [](const std::atomic<bool> &flag) {
  23622. for (int i = 0; i < 500 && !flag; i++) {
  23623. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23624. }
  23625. };
  23626. Server svr;
  23627. svr.set_websocket_ping_interval(0);
  23628. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23629. std::thread reader([&]() {
  23630. std::string msg;
  23631. while (ws.read(msg)) {
  23632. std::lock_guard<std::mutex> guard(received_mutex);
  23633. received.push_back(msg);
  23634. }
  23635. });
  23636. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23637. // inside read_websocket_frame() when close() runs.
  23638. wait_for(peer_stalled);
  23639. ws.close();
  23640. reader.join();
  23641. handler_done = true;
  23642. });
  23643. auto port = svr.bind_to_any_port("127.0.0.1");
  23644. std::thread t([&]() { svr.listen_after_bind(); });
  23645. auto se = detail::scope_exit([&] {
  23646. svr.stop();
  23647. t.join();
  23648. });
  23649. svr.wait_until_ready();
  23650. auto send_bytes = [](socket_t s, const std::string &data) {
  23651. #ifdef _WIN32
  23652. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23653. #else
  23654. auto n = ::send(s, data.data(), data.size(), 0);
  23655. #endif
  23656. return n == static_cast<decltype(n)>(data.size());
  23657. };
  23658. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23659. // Every length used here fits the 7-bit length field.
  23660. auto masked_header = [](uint8_t first_byte, size_t len) {
  23661. std::string h;
  23662. h += static_cast<char>(first_byte);
  23663. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23664. h.append(4, '\0'); // mask key
  23665. return h;
  23666. };
  23667. for (int attempt = 0; attempt < attempts; attempt++) {
  23668. peer_stalled = false;
  23669. handler_done = false;
  23670. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23671. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23672. auto se_sock = detail::scope_exit([&] {
  23673. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23674. });
  23675. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23676. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23677. sockaddr_in addr{};
  23678. addr.sin_family = AF_INET;
  23679. addr.sin_port = htons(static_cast<uint16_t>(port));
  23680. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23681. ASSERT_EQ(
  23682. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23683. << "attempt " << attempt;
  23684. ASSERT_TRUE(send_bytes(sock,
  23685. "GET /ws HTTP/1.1\r\n"
  23686. "Host: 127.0.0.1\r\n"
  23687. "Upgrade: websocket\r\n"
  23688. "Connection: Upgrade\r\n"
  23689. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23690. "Sec-WebSocket-Version: 13\r\n"
  23691. "\r\n"))
  23692. << "attempt " << attempt;
  23693. std::string response;
  23694. while (response.find("\r\n\r\n") == std::string::npos) {
  23695. char buf[512];
  23696. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23697. if (n <= 0) { break; }
  23698. response.append(buf, static_cast<size_t>(n));
  23699. }
  23700. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23701. << "attempt " << attempt;
  23702. // Send the header of a Binary message but only the first prefix_len bytes
  23703. // of its payload, leaving the reader thread stalled inside the payload.
  23704. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23705. expected.substr(0, prefix_len)))
  23706. << "attempt " << attempt;
  23707. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23708. peer_stalled = true;
  23709. // Let close() send its Close frame and park in its own read before the
  23710. // rest of the payload arrives, so both threads are waiting for it.
  23711. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23712. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23713. close_frame += static_cast<char>(0x03); // status 1000
  23714. close_frame += static_cast<char>(0xE8);
  23715. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23716. << "attempt " << attempt;
  23717. // Closing the peer releases the reader thread even on the buggy path,
  23718. // where it waits for bytes another thread already consumed.
  23719. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23720. detail::close_socket(sock);
  23721. sock = INVALID_SOCKET;
  23722. wait_for(handler_done);
  23723. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23724. }
  23725. std::lock_guard<std::mutex> guard(received_mutex);
  23726. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23727. << "a message in flight when close() ran was dropped";
  23728. for (size_t i = 0; i < received.size(); i++) {
  23729. EXPECT_EQ(expected, received[i]) << "message " << i;
  23730. }
  23731. }
  23732. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23733. // returning the socket, or INVALID_SOCKET.
  23734. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23735. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23736. if (sock == INVALID_SOCKET) { return sock; }
  23737. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23738. sockaddr_in addr{};
  23739. addr.sin_family = AF_INET;
  23740. addr.sin_port = htons(static_cast<uint16_t>(port));
  23741. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23742. std::string req = "GET " + path +
  23743. " HTTP/1.1\r\n"
  23744. "Host: 127.0.0.1\r\n"
  23745. "Upgrade: websocket\r\n"
  23746. "Connection: Upgrade\r\n"
  23747. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23748. "Sec-WebSocket-Version: 13\r\n"
  23749. "\r\n";
  23750. std::string res;
  23751. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23752. detail::send_socket(sock, req.data(), req.size(), 0) ==
  23753. static_cast<ssize_t>(req.size())) {
  23754. char c;
  23755. while (res.find("\r\n\r\n") == std::string::npos &&
  23756. ::recv(sock, &c, 1, 0) == 1) {
  23757. res += c;
  23758. }
  23759. }
  23760. if (res.find(" 101 ") == std::string::npos) {
  23761. detail::close_socket(sock);
  23762. return INVALID_SOCKET;
  23763. }
  23764. return sock;
  23765. }
  23766. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23767. // The payload must fit the 7-bit length field.
  23768. static std::string masked_frame(uint8_t first_byte,
  23769. const std::string &payload) {
  23770. std::string f;
  23771. f += static_cast<char>(first_byte);
  23772. f += static_cast<char>(0x80 | payload.size());
  23773. f.append(4, '\0');
  23774. return f + payload;
  23775. }
  23776. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23777. std::atomic<bool> done{false};
  23778. std::string received;
  23779. Server svr;
  23780. svr.set_websocket_ping_interval(0);
  23781. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23782. std::string msg;
  23783. if (ws.read(msg) == ws::Binary) { received = msg; }
  23784. done = true;
  23785. });
  23786. auto port = svr.bind_to_any_port("127.0.0.1");
  23787. std::thread t([&]() { svr.listen_after_bind(); });
  23788. auto se = detail::scope_exit([&] {
  23789. svr.stop();
  23790. t.join();
  23791. });
  23792. svr.wait_until_ready();
  23793. auto sock = connect_raw_websocket(port, "/ws");
  23794. ASSERT_NE(INVALID_SOCKET, sock);
  23795. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23796. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23797. masked_frame(0x89, "p") + // FIN + Ping
  23798. masked_frame(0x80, "lo"); // FIN + Continuation
  23799. detail::send_socket(sock, frames.data(), frames.size(), 0);
  23800. for (int i = 0; i < 500 && !done; i++) {
  23801. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23802. }
  23803. ASSERT_TRUE(done);
  23804. EXPECT_EQ("Hello", received);
  23805. // The Ping between the fragments is answered with a Pong.
  23806. char pong[3];
  23807. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23808. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23809. }
  23810. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23811. Server svr;
  23812. svr.set_websocket_ping_interval(-1);
  23813. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23814. std::string msg;
  23815. while (ws.read(msg)) {}
  23816. });
  23817. auto port = svr.bind_to_any_port("127.0.0.1");
  23818. std::thread t([&]() { svr.listen_after_bind(); });
  23819. auto se = detail::scope_exit([&] {
  23820. svr.stop();
  23821. t.join();
  23822. });
  23823. svr.wait_until_ready();
  23824. auto sock = connect_raw_websocket(port, "/ws");
  23825. ASSERT_NE(INVALID_SOCKET, sock);
  23826. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23827. // Nothing comes while the client stays quiet.
  23828. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23829. char c;
  23830. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23831. }
  23832. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23833. Server svr;
  23834. svr.set_websocket_ping_interval(0);
  23835. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23836. std::string msg;
  23837. while (ws.read(msg)) {}
  23838. });
  23839. auto port = svr.bind_to_any_port("127.0.0.1");
  23840. std::thread t([&]() { svr.listen_after_bind(); });
  23841. auto se = detail::scope_exit([&] {
  23842. svr.stop();
  23843. t.join();
  23844. });
  23845. svr.wait_until_ready();
  23846. // Each Close payload and the reply it should get: an echo when valid, 1002
  23847. // otherwise.
  23848. std::vector<std::pair<std::string, std::string>> cases = {
  23849. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23850. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23851. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23852. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23853. };
  23854. // Also between the fragments of a message.
  23855. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23856. for (const auto &c : cases) {
  23857. auto sock = connect_raw_websocket(port, "/ws");
  23858. ASSERT_NE(INVALID_SOCKET, sock);
  23859. auto frames = prefix + masked_frame(0x88, c.first);
  23860. detail::send_socket(sock, frames.data(), frames.size(), 0);
  23861. std::string reply;
  23862. char buf[256];
  23863. while (reply.size() < 2 + c.second.size()) {
  23864. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23865. if (n <= 0) { break; }
  23866. reply.append(buf, static_cast<size_t>(n));
  23867. }
  23868. detail::close_socket(sock);
  23869. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23870. c.second,
  23871. reply);
  23872. }
  23873. }
  23874. }
  23875. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23876. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23877. protected:
  23878. void SetUp() override {
  23879. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23880. SERVER_PRIVATE_KEY_FILE);
  23881. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23882. std::string msg;
  23883. ws::ReadResult ret;
  23884. while ((ret = ws.read(msg))) {
  23885. if (ret == ws::Binary) {
  23886. ws.send(msg.data(), msg.size());
  23887. } else {
  23888. ws.send(msg);
  23889. }
  23890. }
  23891. });
  23892. port_ = server_->bind_to_any_port(HOST);
  23893. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23894. server_->wait_until_ready();
  23895. }
  23896. void TearDown() override {
  23897. server_->stop();
  23898. if (server_thread_.joinable()) { server_thread_.join(); }
  23899. }
  23900. std::unique_ptr<SSLServer> server_;
  23901. std::thread server_thread_;
  23902. int port_ = 0;
  23903. };
  23904. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23905. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23906. {
  23907. ws::WebSocketClient client(url);
  23908. client.enable_server_certificate_verification(false);
  23909. auto calls = 0;
  23910. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23911. calls++;
  23912. return false;
  23913. });
  23914. EXPECT_FALSE(client.connect());
  23915. EXPECT_GT(calls, 0);
  23916. }
  23917. {
  23918. ws::WebSocketClient client(url);
  23919. client.enable_server_certificate_verification(false);
  23920. client.set_session_verifier([](tls::session_t) {
  23921. return SSLVerifierResponse::CertificateRejected;
  23922. });
  23923. EXPECT_FALSE(client.connect());
  23924. }
  23925. {
  23926. ws::WebSocketClient client(url);
  23927. client.enable_server_certificate_verification(false);
  23928. client.set_session_verifier([](tls::session_t) {
  23929. return SSLVerifierResponse::CertificateAccepted;
  23930. });
  23931. EXPECT_TRUE(client.connect());
  23932. }
  23933. }
  23934. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23935. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23936. "/ws-echo");
  23937. client.enable_server_certificate_verification(false);
  23938. ASSERT_TRUE(client.connect());
  23939. ASSERT_TRUE(client.is_open());
  23940. ASSERT_TRUE(client.send("Hello WSS"));
  23941. std::string msg;
  23942. EXPECT_EQ(ws::Text, client.read(msg));
  23943. EXPECT_EQ("Hello WSS", msg);
  23944. client.close();
  23945. }
  23946. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23947. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23948. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23949. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23950. // client (without calling close() first) is the only path that runs
  23951. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23952. // bug exactly.
  23953. //
  23954. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23955. // when linked against an instrumented libssl; run under Valgrind to catch it
  23956. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23957. // suite (the freed session otherwise stalls on the close handshake) — this test
  23958. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23959. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23960. {
  23961. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23962. "/ws-echo");
  23963. client.enable_server_certificate_verification(false);
  23964. client.set_read_timeout(2, 0);
  23965. client.set_write_timeout(2, 0);
  23966. ASSERT_TRUE(client.connect());
  23967. ASSERT_TRUE(client.is_open());
  23968. ASSERT_TRUE(client.send("still open"));
  23969. // Intentionally do NOT call client.close(): leaving scope runs
  23970. // shutdown_and_close() with the WebSocket still open, which must send the
  23971. // close frame while the TLS session is still alive.
  23972. }
  23973. }
  23974. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23975. // shutdown_and_close() at the start of connect(), reproducing the same
  23976. // use-after-free within the test body rather than at scope exit. The second
  23977. // connect must succeed and echo, proving the close handshake ran over a live
  23978. // session. See the note above about memory-tool requirements.
  23979. TEST_F(WebSocketSSLIntegrationTest,
  23980. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23981. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23982. "/ws-echo");
  23983. client.enable_server_certificate_verification(false);
  23984. client.set_read_timeout(2, 0);
  23985. client.set_write_timeout(2, 0);
  23986. ASSERT_TRUE(client.connect());
  23987. ASSERT_TRUE(client.is_open());
  23988. ASSERT_TRUE(client.send("still open"));
  23989. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23990. // the still-open connection, which must not touch a freed TLS session.
  23991. ASSERT_TRUE(client.connect());
  23992. ASSERT_TRUE(client.is_open());
  23993. ASSERT_TRUE(client.send("after reconnect"));
  23994. std::string msg;
  23995. EXPECT_EQ(ws::Text, client.read(msg));
  23996. EXPECT_EQ("after reconnect", msg);
  23997. client.close();
  23998. }
  23999. #endif
  24000. #ifdef CPPHTTPLIB_SSL_ENABLED
  24001. class WebSocketSSLCATest : public ::testing::Test {
  24002. protected:
  24003. void SetUp() override {
  24004. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24005. SERVER_PRIVATE_KEY_FILE);
  24006. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24007. std::string msg;
  24008. while (ws.read(msg)) {
  24009. ws.send(msg);
  24010. }
  24011. });
  24012. port_ = server_->bind_to_any_port("127.0.0.1");
  24013. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24014. server_->wait_until_ready();
  24015. }
  24016. void TearDown() override {
  24017. server_->stop();
  24018. if (server_thread_.joinable()) { server_thread_.join(); }
  24019. }
  24020. std::string url() const {
  24021. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24022. }
  24023. std::unique_ptr<SSLServer> server_;
  24024. std::thread server_thread_;
  24025. int port_ = 0;
  24026. };
  24027. // A custom CA loaded as PEM verifies the server with full certificate
  24028. // verification enabled
  24029. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24030. ws::WebSocketClient client(url());
  24031. std::string cert;
  24032. read_file(SERVER_CERT2_FILE, cert);
  24033. client.load_ca_cert_store(cert.c_str(), cert.size());
  24034. ASSERT_TRUE(client.connect());
  24035. ASSERT_TRUE(client.send("hello"));
  24036. std::string msg;
  24037. EXPECT_EQ(ws::Text, client.read(msg));
  24038. EXPECT_EQ("hello", msg);
  24039. client.close();
  24040. }
  24041. // A custom CA that does not cover the server must fail verification (the
  24042. // custom CA is exclusive; system certs are not loaded alongside it)
  24043. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24044. ws::WebSocketClient client(url());
  24045. std::string cert;
  24046. read_file(CLIENT_CA_CERT_FILE, cert);
  24047. client.load_ca_cert_store(cert.c_str(), cert.size());
  24048. auto res = client.connect();
  24049. ASSERT_FALSE(res);
  24050. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24051. EXPECT_EQ(-1, res.status());
  24052. EXPECT_NE(0u, res.ssl_backend_error());
  24053. }
  24054. // The same CA as a file path rather than PEM in memory
  24055. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24056. ws::WebSocketClient client(url());
  24057. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24058. ASSERT_TRUE(client.connect());
  24059. ASSERT_TRUE(client.send("hello"));
  24060. std::string msg;
  24061. EXPECT_EQ(ws::Text, client.read(msg));
  24062. EXPECT_EQ("hello", msg);
  24063. client.close();
  24064. }
  24065. // ...and a CA file that does not cover the server still fails, so it is the
  24066. // path above that decides the outcome
  24067. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24068. ws::WebSocketClient client(url());
  24069. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24070. ASSERT_FALSE(client.connect());
  24071. }
  24072. // Regression test: reconnecting with a native custom CA store used to reuse
  24073. // a store handle the previous TLS context had already freed (use-after-free
  24074. // under the OpenSSL backend). The context now lives as long as the client.
  24075. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24076. ws::WebSocketClient client(url());
  24077. std::string cert;
  24078. read_file(SERVER_CERT2_FILE, cert);
  24079. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24080. ASSERT_TRUE(client.connect());
  24081. client.close();
  24082. ASSERT_TRUE(client.connect());
  24083. ASSERT_TRUE(client.send("again"));
  24084. std::string msg;
  24085. EXPECT_EQ(ws::Text, client.read(msg));
  24086. EXPECT_EQ("again", msg);
  24087. client.close();
  24088. }
  24089. // Regression test: a certificate with a trusted chain but no identity match
  24090. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24091. // verification entirely for IP hosts, so this connection succeeded there.
  24092. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24093. // chain verification while the identity check must still fail.
  24094. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24095. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24096. ASSERT_TRUE(svr.is_valid());
  24097. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24098. std::string msg;
  24099. while (ws.read(msg)) {
  24100. ws.send(msg);
  24101. }
  24102. });
  24103. auto port = svr.bind_to_any_port("127.0.0.1");
  24104. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24105. auto se = detail::scope_exit([&] {
  24106. svr.stop();
  24107. t.join();
  24108. });
  24109. svr.wait_until_ready();
  24110. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24111. "/echo");
  24112. std::string cert;
  24113. read_file(SERVER_CERT_FILE, cert);
  24114. client.load_ca_cert_store(cert.c_str(), cert.size());
  24115. ASSERT_FALSE(client.connect());
  24116. }
  24117. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24118. // SNI, so nothing binds the host name to the TLS session. These bind the
  24119. // server to "localhost" instead, the only shape that exercises the SNI and
  24120. // hostname-verification path with certificate verification left enabled.
  24121. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24122. protected:
  24123. void Start(const char *cert_file) {
  24124. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24125. SERVER_PRIVATE_KEY_FILE);
  24126. ASSERT_TRUE(server_->is_valid());
  24127. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24128. std::string msg;
  24129. while (ws.read(msg)) {
  24130. ws.send(msg);
  24131. }
  24132. });
  24133. port_ = server_->bind_to_any_port("localhost");
  24134. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24135. server_->wait_until_ready();
  24136. }
  24137. void TearDown() override {
  24138. if (server_) { server_->stop(); }
  24139. if (server_thread_.joinable()) { server_thread_.join(); }
  24140. }
  24141. std::string url() const {
  24142. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24143. }
  24144. std::unique_ptr<SSLServer> server_;
  24145. std::thread server_thread_;
  24146. int port_ = 0;
  24147. };
  24148. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24149. // out and the connection is usable
  24150. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24151. Start(SERVER_CERT2_FILE);
  24152. ws::WebSocketClient client(url());
  24153. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24154. ASSERT_TRUE(client.connect());
  24155. ASSERT_TRUE(client.send("hello"));
  24156. std::string msg;
  24157. EXPECT_EQ(ws::Text, client.read(msg));
  24158. EXPECT_EQ("hello", msg);
  24159. client.close();
  24160. }
  24161. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24162. // while the identity check must still reject "localhost"
  24163. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24164. Start(SERVER_CERT_FILE);
  24165. ws::WebSocketClient client(url());
  24166. client.set_ca_cert_path(SERVER_CERT_FILE);
  24167. auto res = client.connect();
  24168. ASSERT_FALSE(res);
  24169. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24170. EXPECT_EQ(-1, res.status());
  24171. }
  24172. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24173. // disabled: the chain is still checked, only the identity check is skipped
  24174. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24175. Start(SERVER_CERT_FILE);
  24176. ws::WebSocketClient client(url());
  24177. client.set_ca_cert_path(SERVER_CERT_FILE);
  24178. client.enable_server_hostname_verification(false);
  24179. ASSERT_TRUE(client.connect());
  24180. ASSERT_TRUE(client.send("hello"));
  24181. std::string msg;
  24182. EXPECT_EQ(ws::Text, client.read(msg));
  24183. EXPECT_EQ("hello", msg);
  24184. client.close();
  24185. }
  24186. // A CA that did not sign the server certificate fails the chain, even though
  24187. // the name would match
  24188. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24189. Start(SERVER_CERT2_FILE);
  24190. ws::WebSocketClient client(url());
  24191. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24192. ASSERT_FALSE(client.connect());
  24193. }
  24194. // With verification disabled, neither the chain nor the name is checked
  24195. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24196. Start(SERVER_CERT_FILE);
  24197. ws::WebSocketClient client(url());
  24198. client.enable_server_certificate_verification(false);
  24199. ASSERT_TRUE(client.connect());
  24200. ASSERT_TRUE(client.send("hello"));
  24201. std::string msg;
  24202. EXPECT_EQ(ws::Text, client.read(msg));
  24203. EXPECT_EQ("hello", msg);
  24204. client.close();
  24205. }
  24206. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24207. protected:
  24208. void SetUp() override {
  24209. server_ = httplib::detail::make_unique<SSLServer>(
  24210. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24211. ASSERT_TRUE(server_->is_valid());
  24212. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24213. std::string msg;
  24214. while (ws.read(msg)) {
  24215. ws.send(msg);
  24216. }
  24217. });
  24218. port_ = server_->bind_to_any_port("localhost");
  24219. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24220. server_->wait_until_ready();
  24221. }
  24222. void TearDown() override {
  24223. server_->stop();
  24224. if (server_thread_.joinable()) { server_thread_.join(); }
  24225. }
  24226. std::string url() const {
  24227. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24228. }
  24229. void ConnectWithClientCert(const std::string &client_cert_file,
  24230. const std::string &client_private_key_file,
  24231. const char *private_key_password) {
  24232. std::string cert_pem, key_pem;
  24233. read_file(client_cert_file, cert_pem);
  24234. read_file(client_private_key_file, key_pem);
  24235. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24236. key_pem.c_str(), key_pem.size(),
  24237. private_key_password};
  24238. ConnectWithPem(pem);
  24239. }
  24240. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24241. ws::WebSocketClient client(url(), pem);
  24242. ASSERT_TRUE(client.is_valid());
  24243. client.enable_server_certificate_verification(false);
  24244. ASSERT_TRUE(client.connect());
  24245. ASSERT_TRUE(client.send("hello"));
  24246. std::string msg;
  24247. EXPECT_EQ(ws::Text, client.read(msg));
  24248. EXPECT_EQ("hello", msg);
  24249. client.close();
  24250. }
  24251. std::unique_ptr<SSLServer> server_;
  24252. std::thread server_thread_;
  24253. int port_ = 0;
  24254. };
  24255. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24256. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24257. }
  24258. // Control for the tests above: the fixture's server really does require a
  24259. // client certificate, so it is the PEM the constructor installed that decides
  24260. // the outcome.
  24261. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24262. ws::WebSocketClient client(url());
  24263. ASSERT_TRUE(client.is_valid());
  24264. client.enable_server_certificate_verification(false);
  24265. EXPECT_FALSE(client.connect());
  24266. }
  24267. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24268. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24269. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24270. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24271. }
  24272. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  24273. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  24274. std::string cert_pem, key_pem;
  24275. read_file(CLIENT_CERT_FILE, cert_pem);
  24276. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  24277. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  24278. std::vector<char> key(key_pem.begin(), key_pem.end());
  24279. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  24280. key.size(), nullptr};
  24281. ConnectWithPem(pem);
  24282. }
  24283. #endif
  24284. #if !defined(_WIN32)
  24285. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24286. auto secret_dir = std::string("./symlink_test_secret");
  24287. auto served_dir = std::string("./symlink_test_served");
  24288. auto secret_file = secret_dir + "/secret.txt";
  24289. auto symlink_path = served_dir + "/escape";
  24290. // Setup: create directories and files
  24291. mkdir(secret_dir.c_str(), 0755);
  24292. mkdir(served_dir.c_str(), 0755);
  24293. {
  24294. std::ofstream ofs(secret_file);
  24295. ofs << "SECRET_DATA";
  24296. }
  24297. // Create symlink using absolute path so it resolves correctly
  24298. #ifdef PATH_MAX
  24299. char abs_secret[PATH_MAX];
  24300. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24301. #else
  24302. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24303. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24304. ASSERT_NE(nullptr, abs_secret);
  24305. #endif
  24306. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24307. auto se = detail::scope_exit([&] {
  24308. unlink(symlink_path.c_str());
  24309. unlink(secret_file.c_str());
  24310. rmdir(served_dir.c_str());
  24311. rmdir(secret_dir.c_str());
  24312. });
  24313. Server svr;
  24314. svr.set_mount_point("/", served_dir);
  24315. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24316. auto se2 = detail::scope_exit([&] {
  24317. svr.stop();
  24318. listen_thread.join();
  24319. });
  24320. svr.wait_until_ready();
  24321. Client cli("localhost", PORT);
  24322. // Symlink pointing outside base dir should be blocked
  24323. auto res = cli.Get("/escape/secret.txt");
  24324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24325. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24326. }
  24327. #endif
  24328. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24329. // "GET /smuggled" request), reads the first response, and only then sends the
  24330. // embedded request as the body. Returns how many times /smuggled ran.
  24331. //
  24332. // The body is sent AFTER receiving the first response (as in the original
  24333. // PoC) so that the stream_line_reader cannot buffer it together with the
  24334. // headers of the first request.
  24335. static int count_smuggled_requests(const std::string &outer_head,
  24336. std::string &first_response) {
  24337. Server svr;
  24338. svr.set_mount_point("/", "./www");
  24339. std::atomic<int> smuggled_count(0);
  24340. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24341. smuggled_count++;
  24342. res.set_content("oops", "text/plain");
  24343. });
  24344. svr.Post("/post", [&](const Request &req, Response &res) {
  24345. res.set_content(req.body, "text/plain");
  24346. });
  24347. auto port = svr.bind_to_any_port("localhost");
  24348. thread t = thread([&] { svr.listen_after_bind(); });
  24349. auto se = detail::scope_exit([&] {
  24350. svr.stop();
  24351. t.join();
  24352. });
  24353. svr.wait_until_ready();
  24354. auto error = Error::Success;
  24355. auto sock = detail::create_client_socket(
  24356. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24357. /*connection_timeout_sec=*/2, 0,
  24358. /*read_timeout_sec=*/2, 0,
  24359. /*write_timeout_sec=*/2, 0, std::string(), error);
  24360. EXPECT_NE(INVALID_SOCKET, sock);
  24361. if (sock == INVALID_SOCKET) { return -1; }
  24362. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24363. // The "smuggled" request will be sent as the body of the outer request
  24364. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24365. "Host: localhost\r\n"
  24366. "Connection: close\r\n"
  24367. "\r\n";
  24368. auto head = outer_head;
  24369. auto len = std::to_string(smuggled.size());
  24370. for (auto pos = head.find("{len}"); pos != std::string::npos;
  24371. pos = head.find("{len}", pos + len.size())) {
  24372. head.replace(pos, 5, len);
  24373. }
  24374. // Step 1: Send only the outer request headers (no body yet)
  24375. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  24376. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  24377. // Step 2: Read the first response
  24378. char buf[4096];
  24379. for (;;) {
  24380. auto n = recv(sock, buf, sizeof(buf), 0);
  24381. if (n <= 0) break;
  24382. first_response.append(buf, static_cast<size_t>(n));
  24383. // Stop once we have a complete response (headers + body)
  24384. auto hdr_end = first_response.find("\r\n\r\n");
  24385. if (hdr_end != std::string::npos) {
  24386. // Check for Content-Length to know when the body is complete
  24387. auto cl_pos = first_response.find("Content-Length:");
  24388. if (cl_pos != std::string::npos) {
  24389. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  24390. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  24391. auto cl = std::stoul(
  24392. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  24393. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  24394. } else {
  24395. break; // No Content-Length, assume headers-only response
  24396. }
  24397. }
  24398. }
  24399. // Step 3: Now send the body, which looks like a new HTTP request. On a
  24400. // vulnerable server the keep-alive loop reads this as a second request. The
  24401. // server may already have closed the connection, so the result is ignored.
  24402. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  24403. // Half-close so that a server which drained the body sees EOF and closes,
  24404. // instead of the read below waiting for the read timeout.
  24405. #ifdef _WIN32
  24406. ::shutdown(sock, SD_SEND);
  24407. #else
  24408. ::shutdown(sock, SHUT_WR);
  24409. #endif
  24410. // Step 4: Read until the server closes the connection
  24411. for (;;) {
  24412. auto n = recv(sock, buf, sizeof(buf), 0);
  24413. if (n <= 0) break;
  24414. }
  24415. return smuggled_count.load();
  24416. }
  24417. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  24418. // A GET request with Content-Length to a static file handler must have its
  24419. // body drained before the keep-alive connection is reused. Otherwise the
  24420. // unread body bytes are interpreted as the next HTTP request.
  24421. std::string first_response;
  24422. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24423. "Host: localhost\r\n"
  24424. "Content-Length: {len}\r\n"
  24425. "\r\n",
  24426. first_response));
  24427. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  24428. }
  24429. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  24430. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  24431. // be answered with 400 and the connection closed. Treating it as "no body"
  24432. // leaves the body to be parsed as the next request.
  24433. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  24434. const char *targets[] = {
  24435. "GET /file", // handler that never reads the body
  24436. "GET /not-found", // no handler matches (404)
  24437. "POST /post", // handler that reads the body
  24438. };
  24439. for (auto target : targets) {
  24440. for (auto value : values) {
  24441. std::string first_response;
  24442. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  24443. " HTTP/1.1\r\n"
  24444. "Host: localhost\r\n"
  24445. "Content-Length: " +
  24446. value + "\r\n\r\n",
  24447. first_response))
  24448. << target << " with Content-Length: " << value;
  24449. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  24450. << target << " with Content-Length: " << value;
  24451. }
  24452. }
  24453. }
  24454. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  24455. // A 400 for an unparseable request line leaves the rest of the message
  24456. // unread, so the connection must be closed rather than reused.
  24457. std::string first_response;
  24458. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  24459. "Host: localhost\r\n"
  24460. "Content-Length: {len}\r\n"
  24461. "\r\n",
  24462. first_response));
  24463. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24464. }
  24465. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  24466. // Same as above for a header block that fails to parse.
  24467. std::string first_response;
  24468. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24469. "Host: localhost\r\n"
  24470. "Bad Header\r\n"
  24471. "Content-Length: {len}\r\n"
  24472. "\r\n",
  24473. first_response));
  24474. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24475. }
  24476. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  24477. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  24478. // server must not read another request on that connection, even when the
  24479. // request had no body to drain.
  24480. std::string first_response;
  24481. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  24482. "Host: localhost\r\n"
  24483. "\r\n",
  24484. first_response));
  24485. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  24486. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  24487. }
  24488. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  24489. // A content reader that stops early leaves the stream inside the body.
  24490. // Draining the whole Content-Length from there, or reading the body again,
  24491. // reads into the next request, and whatever follows is parsed as a request
  24492. // of its own.
  24493. Server svr;
  24494. std::atomic<int> smuggled_count(0);
  24495. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  24496. svr.Post("/upload", [](const Request &req, Response &res,
  24497. const ContentReader &content_reader) {
  24498. // Stop at the last chunk, so the whole body has been read however it
  24499. // arrives.
  24500. auto length = req.get_header_value_u64("Content-Length");
  24501. size_t total = 0;
  24502. auto consumed = content_reader([&](const char *, size_t n) {
  24503. total += n;
  24504. return total < length;
  24505. });
  24506. EXPECT_FALSE(consumed);
  24507. if (req.has_param("retry")) {
  24508. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  24509. }
  24510. // Replace the 400 the aborted read set, which would close the connection.
  24511. res.set_redirect("/done");
  24512. });
  24513. auto port = svr.bind_to_any_port(HOST);
  24514. thread t = thread([&] { svr.listen_after_bind(); });
  24515. auto se = detail::scope_exit([&] {
  24516. svr.stop();
  24517. t.join();
  24518. });
  24519. svr.wait_until_ready();
  24520. // A front end sees the second request as a POST whose body is the GET. The
  24521. // first body is as long as the POST's headers, so draining it again reads
  24522. // exactly those and leaves the GET to be parsed next.
  24523. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  24524. "Host: localhost\r\n"
  24525. "\r\n";
  24526. std::string second_head = "POST /post HTTP/1.1\r\n"
  24527. "Host: localhost\r\n"
  24528. "Content-Length: " +
  24529. std::to_string(inner.size()) +
  24530. "\r\n"
  24531. "\r\n";
  24532. for (auto target : {"/upload", "/upload?retry"}) {
  24533. smuggled_count = 0;
  24534. std::string request = "POST " + std::string(target) +
  24535. " HTTP/1.1\r\n"
  24536. "Host: localhost\r\n"
  24537. "Content-Length: " +
  24538. std::to_string(second_head.size()) +
  24539. "\r\n"
  24540. "\r\n" +
  24541. std::string(second_head.size(), 'A') + second_head +
  24542. inner;
  24543. std::string response;
  24544. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  24545. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  24546. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  24547. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  24548. EXPECT_EQ(0, smuggled_count.load()) << target;
  24549. }
  24550. }
  24551. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  24552. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  24553. // must be rejected with 400 Bad Request.
  24554. Server svr;
  24555. svr.Post("/test", [&](const Request &, Response &res) {
  24556. res.set_content("ok", "text/plain");
  24557. });
  24558. thread t = thread([&] { svr.listen(HOST, PORT); });
  24559. auto se = detail::scope_exit([&] {
  24560. svr.stop();
  24561. t.join();
  24562. ASSERT_FALSE(svr.is_running());
  24563. });
  24564. svr.wait_until_ready();
  24565. // Exact "chunked"
  24566. {
  24567. auto req = "POST /test HTTP/1.1\r\n"
  24568. "Host: localhost\r\n"
  24569. "Content-Length: 5\r\n"
  24570. "Transfer-Encoding: chunked\r\n"
  24571. "Connection: close\r\n"
  24572. "\r\n"
  24573. "hello";
  24574. std::string response;
  24575. ASSERT_TRUE(send_request(1, req, &response));
  24576. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24577. response.substr(0, response.find("\r\n")));
  24578. }
  24579. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  24580. {
  24581. auto req = "POST /test HTTP/1.1\r\n"
  24582. "Host: localhost\r\n"
  24583. "Content-Length: 5\r\n"
  24584. "Transfer-Encoding: gzip, chunked\r\n"
  24585. "Connection: close\r\n"
  24586. "\r\n"
  24587. "hello";
  24588. std::string response;
  24589. ASSERT_TRUE(send_request(1, req, &response));
  24590. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24591. response.substr(0, response.find("\r\n")));
  24592. }
  24593. }
  24594. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  24595. Server svr;
  24596. svr.Post("/test", [&](const Request &, Response &res) {
  24597. res.set_content("ok", "text/plain");
  24598. });
  24599. thread t = thread([&] { svr.listen(HOST, PORT); });
  24600. auto se = detail::scope_exit([&] {
  24601. svr.stop();
  24602. t.join();
  24603. ASSERT_FALSE(svr.is_running());
  24604. });
  24605. svr.wait_until_ready();
  24606. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  24607. // length cannot be determined, so the server must answer 400 and close
  24608. // rather than treat the request as bodyless and leave the body in the
  24609. // socket for the next request to pick up.
  24610. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  24611. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  24612. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  24613. std::string response;
  24614. ASSERT_TRUE(send_request(1, req, &response));
  24615. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24616. response.substr(0, response.find("\r\n")))
  24617. << transfer_encoding;
  24618. }
  24619. // RFC 9110 5.3: the codings may also be split across several
  24620. // Transfer-Encoding lines, which combine in the order they were received.
  24621. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24622. // just like the single-line "chunked, gzip" above.
  24623. {
  24624. auto req = "POST /test HTTP/1.1\r\n"
  24625. "Host: localhost\r\n"
  24626. "Transfer-Encoding: chunked\r\n"
  24627. "Transfer-Encoding: gzip\r\n"
  24628. "\r\n"
  24629. "0\r\n\r\n";
  24630. std::string response;
  24631. ASSERT_TRUE(send_request(1, req, &response));
  24632. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24633. response.substr(0, response.find("\r\n")));
  24634. }
  24635. // A sequence ending in chunked stays valid.
  24636. auto req = "POST /test HTTP/1.1\r\n"
  24637. "Host: localhost\r\n"
  24638. "Transfer-Encoding: gzip, chunked\r\n"
  24639. "Connection: close\r\n"
  24640. "\r\n"
  24641. "0\r\n\r\n";
  24642. std::string response;
  24643. ASSERT_TRUE(send_request(1, req, &response));
  24644. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24645. // ...including when it is spread over several lines.
  24646. auto split_req = "POST /test HTTP/1.1\r\n"
  24647. "Host: localhost\r\n"
  24648. "Transfer-Encoding: gzip\r\n"
  24649. "Transfer-Encoding: chunked\r\n"
  24650. "Connection: close\r\n"
  24651. "\r\n"
  24652. "0\r\n\r\n";
  24653. std::string split_response;
  24654. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24655. EXPECT_EQ("HTTP/1.1 200 OK",
  24656. split_response.substr(0, split_response.find("\r\n")));
  24657. }
  24658. // Regression for issue #2450: a DELETE without Content-Length on a
  24659. // keep-alive connection must not let the post-response drain consume the
  24660. // next request's bytes.
  24661. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24662. Server svr;
  24663. std::atomic<int> delete_count(0);
  24664. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24665. delete_count++;
  24666. res.status = StatusCode::NoContent_204;
  24667. });
  24668. auto port = svr.bind_to_any_port(HOST);
  24669. thread t = thread([&] { svr.listen_after_bind(); });
  24670. auto se = detail::scope_exit([&] {
  24671. svr.stop();
  24672. t.join();
  24673. });
  24674. svr.wait_until_ready();
  24675. auto error = Error::Success;
  24676. auto sock = detail::create_client_socket(
  24677. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24678. /*connection_timeout_sec=*/2, 0,
  24679. /*read_timeout_sec=*/2, 0,
  24680. /*write_timeout_sec=*/2, 0, std::string(), error);
  24681. ASSERT_NE(INVALID_SOCKET, sock);
  24682. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24683. auto send_request_and_read_response = [&](const std::string &req,
  24684. std::string &out) -> bool {
  24685. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  24686. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24687. char buf[4096];
  24688. for (;;) {
  24689. auto n = recv(sock, buf, sizeof(buf), 0);
  24690. if (n <= 0) { return !out.empty(); }
  24691. out.append(buf, static_cast<size_t>(n));
  24692. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24693. }
  24694. };
  24695. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24696. "Host: localhost\r\n"
  24697. "\r\n";
  24698. std::string resp1;
  24699. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24700. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24701. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24702. "Host: localhost\r\n"
  24703. "Connection: close\r\n"
  24704. "\r\n";
  24705. std::string resp2;
  24706. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24707. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24708. EXPECT_EQ(2, delete_count.load());
  24709. }
  24710. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24711. Server svr;
  24712. svr.Post("/ingest", [&](const Request &, Response &res,
  24713. const ContentReader &content_reader) {
  24714. auto consumed = content_reader([](const char *, size_t) { return false; });
  24715. EXPECT_FALSE(consumed);
  24716. res.status = StatusCode::Conflict_409;
  24717. res.set_header("Connection", "close");
  24718. });
  24719. auto port = svr.bind_to_any_port(HOST);
  24720. thread t = thread([&] { svr.listen_after_bind(); });
  24721. auto se = detail::scope_exit([&] {
  24722. svr.stop();
  24723. t.join();
  24724. });
  24725. svr.wait_until_ready();
  24726. auto error = Error::Success;
  24727. auto sock = detail::create_client_socket(
  24728. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24729. /*connection_timeout_sec=*/2, 0,
  24730. /*read_timeout_sec=*/1, 0,
  24731. /*write_timeout_sec=*/2, 0, std::string(), error);
  24732. ASSERT_NE(INVALID_SOCKET, sock);
  24733. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24734. std::string request = "POST /ingest HTTP/1.1\r\n"
  24735. "Host: localhost\r\n"
  24736. "Transfer-Encoding: chunked\r\n"
  24737. "\r\n"
  24738. "4\r\n"
  24739. "data\r\n";
  24740. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  24741. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24742. std::string response;
  24743. ssize_t received = 0;
  24744. do {
  24745. char buf[4096];
  24746. received = recv(sock, buf, sizeof(buf), 0);
  24747. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24748. } while (received > 0);
  24749. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24750. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24751. EXPECT_EQ(0, received);
  24752. }
  24753. namespace no_proxy_test {
  24754. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24755. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24756. // calling listen().
  24757. class ScopedServer {
  24758. public:
  24759. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24760. ~ScopedServer() {
  24761. svr_.stop();
  24762. if (th_.joinable()) { th_.join(); }
  24763. }
  24764. Server &svr() { return svr_; }
  24765. int port() const { return port_; }
  24766. void listen() {
  24767. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24768. svr_.wait_until_ready();
  24769. }
  24770. private:
  24771. Server svr_;
  24772. std::thread th_;
  24773. int port_ = 0;
  24774. };
  24775. class ProxyAndTargetServers {
  24776. public:
  24777. ProxyAndTargetServers() {
  24778. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24779. proxy_hits_++;
  24780. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24781. res.set_content("via-proxy", "text/plain");
  24782. });
  24783. target_.Get(".*", [this](const Request &req, Response &res) {
  24784. target_hits_++;
  24785. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24786. res.set_content("direct", "text/plain");
  24787. });
  24788. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24789. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24790. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24791. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24792. proxy_mock_.wait_until_ready();
  24793. target_.wait_until_ready();
  24794. }
  24795. ~ProxyAndTargetServers() {
  24796. proxy_mock_.stop();
  24797. target_.stop();
  24798. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24799. if (target_thread_.joinable()) { target_thread_.join(); }
  24800. }
  24801. Server &proxy_mock() { return proxy_mock_; }
  24802. Server &target() { return target_; }
  24803. int proxy_port() const { return proxy_port_; }
  24804. int target_port() const { return target_port_; }
  24805. int proxy_hits() const { return proxy_hits_.load(); }
  24806. int target_hits() const { return target_hits_.load(); }
  24807. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24808. void reset_counters() {
  24809. proxy_hits_ = 0;
  24810. target_hits_ = 0;
  24811. last_had_proxy_authz_ = false;
  24812. }
  24813. private:
  24814. Server proxy_mock_;
  24815. Server target_;
  24816. std::thread proxy_thread_;
  24817. std::thread target_thread_;
  24818. int proxy_port_ = 0;
  24819. int target_port_ = 0;
  24820. std::atomic<int> proxy_hits_{0};
  24821. std::atomic<int> target_hits_{0};
  24822. std::atomic<bool> last_had_proxy_authz_{false};
  24823. };
  24824. inline std::unique_ptr<Client> make_client(const std::string &host,
  24825. ProxyAndTargetServers &s) {
  24826. auto cli = detail::make_unique<Client>(host, s.target_port());
  24827. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24828. cli->set_proxy("127.0.0.1", s.proxy_port());
  24829. return cli;
  24830. }
  24831. } // namespace no_proxy_test
  24832. using no_proxy_test::make_client;
  24833. using no_proxy_test::ProxyAndTargetServers;
  24834. TEST(NoProxyTest, ExactHostnameBypasses) {
  24835. ProxyAndTargetServers s;
  24836. auto cli = make_client("example.com", s);
  24837. cli->set_no_proxy({"example.com"});
  24838. auto res = cli->Get("/");
  24839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24840. EXPECT_EQ(0, s.proxy_hits());
  24841. EXPECT_EQ(1, s.target_hits());
  24842. }
  24843. TEST(NoProxyTest, SubdomainBypasses) {
  24844. ProxyAndTargetServers s;
  24845. auto cli = make_client("foo.example.com", s);
  24846. cli->set_no_proxy({"example.com"});
  24847. auto res = cli->Get("/");
  24848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24849. EXPECT_EQ(0, s.proxy_hits());
  24850. EXPECT_EQ(1, s.target_hits());
  24851. }
  24852. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24853. // Regression guard: "evilexample.com" must not be considered a subdomain
  24854. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24855. // check would let traffic bypass the proxy and leak credentials direct
  24856. // to the attacker host.
  24857. ProxyAndTargetServers s;
  24858. auto cli = make_client("evilexample.com", s);
  24859. cli->set_no_proxy({"example.com"});
  24860. auto res = cli->Get("/");
  24861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24862. EXPECT_GE(s.proxy_hits(), 1);
  24863. EXPECT_EQ(0, s.target_hits());
  24864. }
  24865. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24866. ProxyAndTargetServers s;
  24867. auto cli = make_client("example.com.evil.com", s);
  24868. cli->set_no_proxy({"example.com"});
  24869. auto res = cli->Get("/");
  24870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24871. EXPECT_GE(s.proxy_hits(), 1);
  24872. EXPECT_EQ(0, s.target_hits());
  24873. }
  24874. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24875. ProxyAndTargetServers s;
  24876. auto cli = make_client("example.com", s);
  24877. cli->set_no_proxy({".example.com"});
  24878. auto res = cli->Get("/");
  24879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24880. EXPECT_EQ(0, s.proxy_hits());
  24881. EXPECT_EQ(1, s.target_hits());
  24882. }
  24883. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24884. ProxyAndTargetServers s;
  24885. auto cli = make_client("Example.COM", s);
  24886. cli->set_no_proxy({"EXAMPLE.com"});
  24887. auto res = cli->Get("/");
  24888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24889. EXPECT_EQ(0, s.proxy_hits());
  24890. EXPECT_EQ(1, s.target_hits());
  24891. }
  24892. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24893. ProxyAndTargetServers s;
  24894. auto cli = make_client("example.com.", s);
  24895. cli->set_no_proxy({"example.com"});
  24896. auto res = cli->Get("/");
  24897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24898. EXPECT_EQ(0, s.proxy_hits());
  24899. EXPECT_EQ(1, s.target_hits());
  24900. }
  24901. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24902. // Trailing dots must be normalized on BOTH sides — host and entry.
  24903. // An implementation that only strips the host-side trailing dot would
  24904. // fail to match host "example.com" against entry "example.com." because
  24905. // a literal substring search would compare 11 chars against 12.
  24906. ProxyAndTargetServers s;
  24907. auto cli = make_client("example.com", s);
  24908. cli->set_no_proxy({"example.com."});
  24909. auto res = cli->Get("/");
  24910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24911. EXPECT_EQ(0, s.proxy_hits());
  24912. EXPECT_EQ(1, s.target_hits());
  24913. }
  24914. TEST(NoProxyTest, WildcardBypassesEverything) {
  24915. ProxyAndTargetServers s;
  24916. auto cli = make_client("anything.invalid.test", s);
  24917. cli->set_no_proxy({"*"});
  24918. auto res = cli->Get("/");
  24919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24920. EXPECT_EQ(0, s.proxy_hits());
  24921. EXPECT_EQ(1, s.target_hits());
  24922. }
  24923. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24924. ProxyAndTargetServers s;
  24925. Client cli("127.0.0.1", s.target_port());
  24926. cli.set_proxy("127.0.0.1", s.proxy_port());
  24927. cli.set_no_proxy({"127.0.0.1"});
  24928. auto res = cli.Get("/");
  24929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24930. EXPECT_EQ(0, s.proxy_hits());
  24931. EXPECT_EQ(1, s.target_hits());
  24932. }
  24933. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24934. ProxyAndTargetServers s;
  24935. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24936. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24937. cli.set_proxy("127.0.0.1", s.proxy_port());
  24938. cli.set_no_proxy({"::1"});
  24939. auto res = cli.Get("/");
  24940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24941. EXPECT_EQ(0, s.proxy_hits());
  24942. EXPECT_EQ(1, s.target_hits());
  24943. }
  24944. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24945. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24946. // must still be recognized as IPv6 for CIDR matching. Implementations
  24947. // that detect IPv6 only when the host begins with '[' would parse the
  24948. // host as a hostname and miss the match.
  24949. ProxyAndTargetServers s;
  24950. Client cli("fe80::1", s.target_port());
  24951. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24952. cli.set_proxy("127.0.0.1", s.proxy_port());
  24953. cli.set_no_proxy({"fe80::/10"});
  24954. auto res = cli.Get("/");
  24955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24956. EXPECT_EQ(0, s.proxy_hits());
  24957. EXPECT_EQ(1, s.target_hits());
  24958. }
  24959. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24960. ProxyAndTargetServers s;
  24961. Client cli("::1", s.target_port());
  24962. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24963. cli.set_proxy("127.0.0.1", s.proxy_port());
  24964. cli.set_no_proxy({"[::1]"});
  24965. auto res = cli.Get("/");
  24966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24967. EXPECT_EQ(0, s.proxy_hits());
  24968. EXPECT_EQ(1, s.target_hits());
  24969. }
  24970. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24971. ProxyAndTargetServers s;
  24972. Client cli("fe80::1", s.target_port());
  24973. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24974. cli.set_proxy("127.0.0.1", s.proxy_port());
  24975. cli.set_no_proxy({"[fe80::]/10"});
  24976. auto res = cli.Get("/");
  24977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24978. EXPECT_EQ(0, s.proxy_hits());
  24979. EXPECT_EQ(1, s.target_hits());
  24980. }
  24981. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24982. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24983. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24984. // tricks via address-family conversion.
  24985. ProxyAndTargetServers s;
  24986. Client cli("::ffff:127.0.0.1", s.target_port());
  24987. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24988. cli.set_proxy("127.0.0.1", s.proxy_port());
  24989. cli.set_no_proxy({"127.0.0.1"});
  24990. auto res = cli.Get("/");
  24991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24992. EXPECT_GE(s.proxy_hits(), 1);
  24993. EXPECT_EQ(0, s.target_hits());
  24994. }
  24995. TEST(NoProxyTest, IPv4CidrMatch) {
  24996. ProxyAndTargetServers s;
  24997. Client cli("127.0.0.1", s.target_port());
  24998. cli.set_proxy("127.0.0.1", s.proxy_port());
  24999. cli.set_no_proxy({"127.0.0.0/8"});
  25000. auto res = cli.Get("/");
  25001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25002. EXPECT_EQ(0, s.proxy_hits());
  25003. EXPECT_EQ(1, s.target_hits());
  25004. }
  25005. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25006. ProxyAndTargetServers s;
  25007. Client cli("127.0.0.1", s.target_port());
  25008. cli.set_proxy("127.0.0.1", s.proxy_port());
  25009. cli.set_no_proxy({"10.0.0.0/8"});
  25010. auto res = cli.Get("/");
  25011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25012. EXPECT_GE(s.proxy_hits(), 1);
  25013. EXPECT_EQ(0, s.target_hits());
  25014. }
  25015. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25016. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25017. // IPv4 target matches.
  25018. ProxyAndTargetServers s;
  25019. Client cli("127.0.0.1", s.target_port());
  25020. cli.set_proxy("127.0.0.1", s.proxy_port());
  25021. cli.set_no_proxy({"0.0.0.0/0"});
  25022. auto res = cli.Get("/");
  25023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25024. EXPECT_EQ(0, s.proxy_hits());
  25025. EXPECT_EQ(1, s.target_hits());
  25026. }
  25027. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25028. ProxyAndTargetServers s;
  25029. Client cli("127.0.0.1", s.target_port());
  25030. cli.set_proxy("127.0.0.1", s.proxy_port());
  25031. cli.set_no_proxy({"127.0.0.1"});
  25032. auto res = cli.Get("/");
  25033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25034. EXPECT_EQ(0, s.proxy_hits());
  25035. EXPECT_EQ(1, s.target_hits());
  25036. }
  25037. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25038. ProxyAndTargetServers s;
  25039. Client cli("127.0.0.1", s.target_port());
  25040. cli.set_proxy("127.0.0.1", s.proxy_port());
  25041. cli.set_no_proxy({"127.0.0.0/33"});
  25042. auto res = cli.Get("/");
  25043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25044. EXPECT_GE(s.proxy_hits(), 1);
  25045. EXPECT_EQ(0, s.target_hits());
  25046. }
  25047. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25048. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25049. ProxyAndTargetServers s;
  25050. Client cli("127.0.0.1", s.target_port());
  25051. cli.set_proxy("127.0.0.1", s.proxy_port());
  25052. cli.set_no_proxy({"127.0.0.1/"});
  25053. auto res = cli.Get("/");
  25054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25055. EXPECT_GE(s.proxy_hits(), 1);
  25056. EXPECT_EQ(0, s.target_hits());
  25057. }
  25058. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25059. ProxyAndTargetServers s;
  25060. auto cli = make_client("internal.corp", s);
  25061. cli->set_proxy_basic_auth("u", "p");
  25062. cli->set_no_proxy({"internal.corp"});
  25063. auto res = cli->Get("/");
  25064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25065. EXPECT_EQ(1, s.target_hits());
  25066. EXPECT_EQ(0, s.proxy_hits());
  25067. EXPECT_FALSE(s.last_had_proxy_authz())
  25068. << "Proxy-Authorization must not be sent direct to the target";
  25069. }
  25070. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25071. ProxyAndTargetServers s;
  25072. auto cli = make_client("public.example", s);
  25073. cli->set_proxy_basic_auth("u", "p");
  25074. cli->set_no_proxy({"internal.corp"}); // does not match
  25075. auto res = cli->Get("/");
  25076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25077. EXPECT_GE(s.proxy_hits(), 1);
  25078. EXPECT_TRUE(s.last_had_proxy_authz());
  25079. }
  25080. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25081. std::atomic<int> hits{0};
  25082. std::atomic<int> hits_with_authz{0};
  25083. no_proxy_test::ScopedServer proxy_mock;
  25084. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25085. hits++;
  25086. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25087. if (req.target.find("/redir") != std::string::npos) {
  25088. res.set_redirect("http://other.example/landed");
  25089. } else {
  25090. res.set_content("via-proxy", "text/plain");
  25091. }
  25092. });
  25093. proxy_mock.listen();
  25094. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25095. hits = 0;
  25096. hits_with_authz = 0;
  25097. Client cli("public.example", 80);
  25098. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25099. cli.set_proxy_basic_auth(c.first, c.second);
  25100. cli.set_follow_location(true);
  25101. // The redirect to another host goes through the proxy as well
  25102. auto res = cli.Get("/redir");
  25103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25104. EXPECT_EQ(2, hits.load());
  25105. EXPECT_EQ(2, hits_with_authz.load());
  25106. }
  25107. }
  25108. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25109. ProxyAndTargetServers s;
  25110. auto cli = make_client("anything.test", s);
  25111. auto res = cli->Get("/");
  25112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25113. EXPECT_GE(s.proxy_hits(), 1);
  25114. EXPECT_EQ(0, s.target_hits());
  25115. }
  25116. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25117. ProxyAndTargetServers s;
  25118. auto cli = make_client("example.com", s);
  25119. cli->set_no_proxy({"example.com:8080"});
  25120. auto res = cli->Get("/");
  25121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25122. EXPECT_GE(s.proxy_hits(), 1);
  25123. EXPECT_EQ(0, s.target_hits());
  25124. }
  25125. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25126. ProxyAndTargetServers s;
  25127. auto cli = make_client("anything.test", s);
  25128. cli->set_no_proxy({"", " ", "\t"});
  25129. auto res = cli->Get("/");
  25130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25131. EXPECT_GE(s.proxy_hits(), 1);
  25132. EXPECT_EQ(0, s.target_hits());
  25133. }
  25134. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25135. // An entry with leading/trailing whitespace must still match — env-style
  25136. // values are commonly pasted with stray spaces and an implementation
  25137. // that feeds the raw token directly to inet_pton would fail to match
  25138. // valid CIDRs because of the spaces.
  25139. ProxyAndTargetServers s;
  25140. Client cli("127.0.0.1", s.target_port());
  25141. cli.set_proxy("127.0.0.1", s.proxy_port());
  25142. cli.set_no_proxy({" 127.0.0.0/8 "});
  25143. auto res = cli.Get("/");
  25144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25145. EXPECT_EQ(0, s.proxy_hits());
  25146. EXPECT_EQ(1, s.target_hits());
  25147. }
  25148. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25149. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25150. // go direct and must NOT carry Proxy-Authorization.
  25151. std::atomic<int> proxy_hits{0};
  25152. std::atomic<int> target_hits{0};
  25153. std::atomic<bool> target_saw_authz{false};
  25154. no_proxy_test::ScopedServer proxy_mock, target;
  25155. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25156. proxy_hits++;
  25157. res.status = 302;
  25158. res.set_header("Location", "http://127.0.0.1:" +
  25159. std::to_string(target.port()) + "/landed");
  25160. });
  25161. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25162. target_hits++;
  25163. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25164. res.set_content("direct", "text/plain");
  25165. });
  25166. proxy_mock.listen();
  25167. target.listen();
  25168. Client cli("public.example", target.port());
  25169. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25170. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25171. cli.set_proxy_basic_auth("u", "p");
  25172. cli.set_no_proxy({"127.0.0.1"});
  25173. cli.set_follow_location(true);
  25174. auto res = cli.Get("/redir");
  25175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25176. EXPECT_GE(proxy_hits.load(), 1);
  25177. EXPECT_GE(target_hits.load(), 1);
  25178. EXPECT_FALSE(target_saw_authz.load());
  25179. }
  25180. #ifdef CPPHTTPLIB_SSL_ENABLED
  25181. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25182. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25183. // proxy creds would be sent to the (possibly hostile) origin.
  25184. std::atomic<int> target_hits{0};
  25185. std::atomic<bool> target_saw_proxy_authz{false};
  25186. no_proxy_test::ScopedServer target;
  25187. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25188. target_hits++;
  25189. if (req.has_header("Proxy-Authorization")) {
  25190. target_saw_proxy_authz = true;
  25191. }
  25192. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25193. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25194. "nonce=\"abc\", algorithm=MD5");
  25195. });
  25196. target.listen();
  25197. // The proxy address is set to the target's port: the bypass MUST kick in;
  25198. // if it doesn't, the test still routes "via proxy" to the same server and
  25199. // the Proxy-Authorization assertion below catches the leak.
  25200. Client cli("evil.example", target.port());
  25201. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25202. cli.set_proxy("127.0.0.1", target.port());
  25203. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25204. cli.set_no_proxy({"evil.example"});
  25205. auto res = cli.Get("/x");
  25206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25207. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25208. EXPECT_EQ(1, target_hits.load());
  25209. EXPECT_FALSE(target_saw_proxy_authz.load());
  25210. }
  25211. #endif
  25212. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25213. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25214. std::atomic<int> proxy_hits{0};
  25215. std::atomic<int> bypass_hits{0};
  25216. std::atomic<bool> proxy_saw_c_url{false};
  25217. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25218. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25219. proxy_hits++;
  25220. if (req.path.find("/start") != std::string::npos) {
  25221. res.status = 302;
  25222. res.set_header("Location", "http://127.0.0.1:" +
  25223. std::to_string(bypass_server.port()) +
  25224. "/middle");
  25225. return;
  25226. }
  25227. if (req.path.find("/end") != std::string::npos) {
  25228. proxy_saw_c_url = true;
  25229. res.set_content("c-via-proxy", "text/plain");
  25230. return;
  25231. }
  25232. res.set_content("unexpected", "text/plain");
  25233. });
  25234. // public.example's "advertised" port is arbitrary (the request never lands
  25235. // there — it goes through the proxy), but use a dynamic value to stay
  25236. // friendly with sharded parallel runs.
  25237. int public_port = bypass_server.port();
  25238. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25239. bypass_hits++;
  25240. res.status = 302;
  25241. res.set_header("Location", "http://public.example:" +
  25242. std::to_string(public_port) + "/end");
  25243. });
  25244. proxy_mock.listen();
  25245. bypass_server.listen();
  25246. Client cli("public.example", public_port);
  25247. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25248. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25249. cli.set_no_proxy({"127.0.0.1"});
  25250. cli.set_follow_location(true);
  25251. auto res = cli.Get("/start");
  25252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25253. EXPECT_EQ(StatusCode::OK_200, res->status);
  25254. EXPECT_EQ("c-via-proxy", res->body);
  25255. EXPECT_GE(proxy_hits.load(), 2);
  25256. EXPECT_GE(bypass_hits.load(), 1);
  25257. EXPECT_TRUE(proxy_saw_c_url.load());
  25258. }
  25259. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  25260. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  25261. // request reconnects to the correct endpoint.
  25262. std::atomic<int> proxy_hits{0};
  25263. std::atomic<int> target_hits{0};
  25264. no_proxy_test::ScopedServer proxy_mock, target;
  25265. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25266. proxy_hits++;
  25267. res.set_content("via-proxy", "text/plain");
  25268. });
  25269. target.svr().Get(".*", [&](const Request &, Response &res) {
  25270. target_hits++;
  25271. res.set_content("direct", "text/plain");
  25272. });
  25273. proxy_mock.listen();
  25274. target.listen();
  25275. Client cli("public.example", target.port());
  25276. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25277. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25278. cli.set_keep_alive(true);
  25279. auto res1 = cli.Get("/a");
  25280. ASSERT_TRUE(res1);
  25281. EXPECT_EQ("via-proxy", res1->body);
  25282. EXPECT_EQ(1, proxy_hits.load());
  25283. EXPECT_EQ(0, target_hits.load());
  25284. cli.set_no_proxy({"public.example"});
  25285. auto res2 = cli.Get("/b");
  25286. ASSERT_TRUE(res2);
  25287. EXPECT_EQ("direct", res2->body);
  25288. EXPECT_EQ(1, proxy_hits.load());
  25289. EXPECT_EQ(1, target_hits.load());
  25290. }
  25291. // Forward declarations (see the base64_encode note).
  25292. namespace httplib {
  25293. namespace detail {
  25294. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  25295. int shutdown_socket(socket_t sock) noexcept;
  25296. } // namespace detail
  25297. } // namespace httplib
  25298. namespace proxy_tunnel_test {
  25299. const char *const kTunnelEstablished =
  25300. "HTTP/1.1 200 Connection established\r\n\r\n";
  25301. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  25302. using ConnectReply = std::function<std::string(const std::string &head)>;
  25303. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  25304. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  25305. class ScopedConnectProxy {
  25306. public:
  25307. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  25308. : forward_port_(forward_port), reply_(std::move(reply)) {
  25309. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25310. if (listen_sock_ == INVALID_SOCKET) { return; }
  25311. auto a = loopback(0);
  25312. auto addr = reinterpret_cast<sockaddr *>(&a);
  25313. socklen_t alen = sizeof(a);
  25314. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  25315. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  25316. ::listen(listen_sock_, 4) != 0) {
  25317. return;
  25318. }
  25319. port_ = ntohs(a.sin_port);
  25320. th_ = std::thread([this] { run(); });
  25321. }
  25322. ~ScopedConnectProxy() {
  25323. if (th_.joinable()) {
  25324. stop_ = true;
  25325. auto wake = connect_to(port_);
  25326. th_.join();
  25327. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  25328. }
  25329. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  25330. }
  25331. int port() const { return port_; }
  25332. int connect_hits() const { return connect_hits_.load(); }
  25333. // Head of the last CONNECT request, as the proxy saw it on the wire.
  25334. std::string connect_request() const {
  25335. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25336. return connect_request_;
  25337. }
  25338. private:
  25339. static sockaddr_in loopback(int port) {
  25340. sockaddr_in a{};
  25341. a.sin_family = AF_INET;
  25342. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25343. a.sin_port = htons(static_cast<unsigned short>(port));
  25344. return a;
  25345. }
  25346. static socket_t connect_to(int port) {
  25347. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25348. if (sock == INVALID_SOCKET) { return sock; }
  25349. auto a = loopback(port);
  25350. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  25351. detail::close_socket(sock);
  25352. return INVALID_SOCKET;
  25353. }
  25354. return sock;
  25355. }
  25356. static bool send_all(socket_t sock, const char *data, size_t size) {
  25357. while (size > 0) {
  25358. auto n = detail::send_socket(sock, data, size, 0);
  25359. if (n <= 0) { return false; }
  25360. data += n;
  25361. size -= static_cast<size_t>(n);
  25362. }
  25363. return true;
  25364. }
  25365. void run() {
  25366. for (;;) {
  25367. auto client = ::accept(listen_sock_, nullptr, nullptr);
  25368. if (stop_) {
  25369. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  25370. return;
  25371. }
  25372. if (client == INVALID_SOCKET) { continue; }
  25373. serve(client);
  25374. detail::close_socket(client);
  25375. }
  25376. }
  25377. void serve(socket_t client) {
  25378. std::string head;
  25379. char buf[2048];
  25380. while (head.find("\r\n\r\n") == std::string::npos) {
  25381. if (detail::select_read(client, 5, 0) <= 0) { return; }
  25382. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  25383. if (n <= 0) { return; }
  25384. head.append(buf, static_cast<size_t>(n));
  25385. }
  25386. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  25387. connect_hits_++;
  25388. {
  25389. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25390. connect_request_ = head;
  25391. }
  25392. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  25393. if (!send_all(client, res.data(), res.size()) ||
  25394. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  25395. return;
  25396. }
  25397. auto origin = connect_to(forward_port_);
  25398. if (origin == INVALID_SOCKET) { return; }
  25399. // When either side stops, shut both down so the other pump returns too.
  25400. auto pump = [&](socket_t from, socket_t to) {
  25401. char b[8192];
  25402. for (;;) {
  25403. auto n = detail::read_socket(from, b, sizeof(b), 0);
  25404. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  25405. }
  25406. detail::shutdown_socket(client);
  25407. detail::shutdown_socket(origin);
  25408. };
  25409. std::thread up([&] { pump(client, origin); });
  25410. pump(origin, client);
  25411. up.join();
  25412. detail::close_socket(origin);
  25413. }
  25414. int forward_port_;
  25415. ConnectReply reply_;
  25416. socket_t listen_sock_ = INVALID_SOCKET;
  25417. int port_ = 0;
  25418. std::thread th_;
  25419. std::atomic<bool> stop_{false};
  25420. std::atomic<int> connect_hits_{0};
  25421. mutable std::mutex connect_request_mutex_;
  25422. std::string connect_request_;
  25423. };
  25424. } // namespace proxy_tunnel_test
  25425. #ifdef CPPHTTPLIB_SSL_ENABLED
  25426. namespace proxy_tunnel_test {
  25427. // SSLServer counterpart to no_proxy_test::ScopedServer.
  25428. class ScopedSSLServer {
  25429. public:
  25430. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  25431. port_ = svr_.bind_to_any_port("127.0.0.1");
  25432. }
  25433. ~ScopedSSLServer() {
  25434. svr_.stop();
  25435. if (th_.joinable()) { th_.join(); }
  25436. }
  25437. SSLServer &svr() { return svr_; }
  25438. int port() const { return port_; }
  25439. void listen() {
  25440. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25441. svr_.wait_until_ready();
  25442. }
  25443. private:
  25444. SSLServer svr_;
  25445. std::thread th_;
  25446. int port_ = 0;
  25447. };
  25448. // Sends one request through the CONNECT proxy to the TLS origin with a
  25449. // credential configured for each hop, and checks that each credential reaches
  25450. // only the hop it was configured for: the proxy's on the CONNECT request, the
  25451. // origin's (every header in origin_headers) on the tunnelled request.
  25452. void CredentialsStayWithTheirHop(
  25453. const std::function<void(SSLClient &)> &set_credentials,
  25454. const std::string &scheme,
  25455. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  25456. std::atomic<int> origin_hits{0};
  25457. std::atomic<bool> origin_saw_proxy_authz{false};
  25458. std::atomic<bool> origin_saw_headers{false};
  25459. ScopedSSLServer origin;
  25460. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25461. origin_hits++;
  25462. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  25463. origin_saw_headers =
  25464. std::all_of(origin_headers.begin(), origin_headers.end(),
  25465. [&](const std::string &h) { return req.has_header(h); });
  25466. res.set_content("ok", "text/plain");
  25467. });
  25468. origin.listen();
  25469. ScopedConnectProxy proxy(origin.port());
  25470. ASSERT_NE(0, proxy.port());
  25471. // Pinned to 127.0.0.1 for the same reason as the test below.
  25472. SSLClient cli("127.0.0.1", origin.port());
  25473. cli.enable_server_certificate_verification(false);
  25474. cli.set_proxy("127.0.0.1", proxy.port());
  25475. set_credentials(cli);
  25476. auto res = cli.Get("/x");
  25477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25478. EXPECT_EQ(StatusCode::OK_200, res->status);
  25479. EXPECT_EQ(1, origin_hits.load());
  25480. EXPECT_EQ(1, proxy.connect_hits());
  25481. EXPECT_TRUE(origin_saw_headers.load());
  25482. EXPECT_FALSE(origin_saw_proxy_authz.load())
  25483. << "Proxy-Authorization must not be sent inside the tunnel";
  25484. auto connect_req = proxy.connect_request();
  25485. EXPECT_NE(std::string::npos,
  25486. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  25487. for (const auto &h : origin_headers) {
  25488. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  25489. << h << " must not be sent to the proxy on CONNECT";
  25490. }
  25491. }
  25492. } // namespace proxy_tunnel_test
  25493. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  25494. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25495. [](SSLClient &cli) {
  25496. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25497. cli.set_basic_auth("origin-user", "origin-pass");
  25498. },
  25499. "Basic");
  25500. }
  25501. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  25502. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25503. [](SSLClient &cli) {
  25504. cli.set_proxy_bearer_token_auth("proxy-token");
  25505. cli.set_bearer_token_auth("origin-token");
  25506. },
  25507. "Bearer");
  25508. }
  25509. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  25510. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25511. [](SSLClient &cli) {
  25512. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25513. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  25514. {"Cookie", "sid=origin-session"},
  25515. {"X-Api-Key", "origin-key"}});
  25516. },
  25517. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  25518. }
  25519. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  25520. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  25521. // retry; otherwise proxy creds would be sent to the origin.
  25522. std::atomic<int> origin_hits{0};
  25523. std::atomic<bool> origin_saw_proxy_authz{false};
  25524. proxy_tunnel_test::ScopedSSLServer origin;
  25525. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25526. origin_hits++;
  25527. if (req.has_header("Proxy-Authorization")) {
  25528. origin_saw_proxy_authz = true;
  25529. }
  25530. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25531. res.set_header("Proxy-Authenticate",
  25532. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  25533. "algorithm=MD5");
  25534. });
  25535. origin.listen();
  25536. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25537. ASSERT_NE(0, proxy.port());
  25538. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  25539. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  25540. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  25541. // and answer with its own status, making this test flaky.
  25542. SSLClient cli("127.0.0.1", origin.port());
  25543. cli.enable_server_certificate_verification(false);
  25544. cli.set_proxy("127.0.0.1", proxy.port());
  25545. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25546. auto res = cli.Get("/x");
  25547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25548. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25549. EXPECT_EQ(1, origin_hits.load());
  25550. EXPECT_FALSE(origin_saw_proxy_authz.load());
  25551. EXPECT_EQ(1, proxy.connect_hits());
  25552. }
  25553. #endif
  25554. namespace proxy_tunnel_test {
  25555. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  25556. // anything else gets a 407 with `challenge`.
  25557. ConnectReply require_proxy_auth(const std::string &expected,
  25558. const std::string &challenge) {
  25559. return [=](const std::string &head) -> std::string {
  25560. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  25561. std::string::npos) {
  25562. return kTunnelEstablished;
  25563. }
  25564. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  25565. "Proxy-Authenticate: " +
  25566. challenge + "\r\nContent-Length: 0\r\n\r\n";
  25567. };
  25568. }
  25569. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  25570. // request, then echoes.
  25571. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  25572. ws.send(
  25573. "authorization:" + req.get_header_value("Authorization") +
  25574. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  25575. std::string msg;
  25576. while (ws.read(msg)) {
  25577. ws.send(msg);
  25578. }
  25579. }
  25580. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  25581. class ScopedWebSocketOrigin {
  25582. public:
  25583. ScopedWebSocketOrigin() {
  25584. server_.svr().WebSocket("/ws", report_auth_then_echo);
  25585. server_.listen();
  25586. }
  25587. int port() const { return server_.port(); }
  25588. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  25589. std::string url() const {
  25590. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  25591. }
  25592. private:
  25593. no_proxy_test::ScopedServer server_;
  25594. };
  25595. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  25596. // passed as a constructor header, and checks that each reaches only its hop.
  25597. void WebSocketCredentialsStayWithTheirHop(
  25598. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  25599. const std::string &proxy_authz, const std::string &origin_authz) {
  25600. ScopedWebSocketOrigin origin;
  25601. ScopedConnectProxy proxy(
  25602. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  25603. ASSERT_NE(0, proxy.port());
  25604. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  25605. client.set_proxy("127.0.0.1", proxy.port());
  25606. set_proxy_credentials(client);
  25607. auto res = client.connect();
  25608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25609. std::string msg;
  25610. ASSERT_TRUE(client.read(msg));
  25611. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  25612. client.close();
  25613. EXPECT_EQ(1, proxy.connect_hits());
  25614. EXPECT_EQ(std::string::npos,
  25615. proxy.connect_request().find("\r\nAuthorization: "))
  25616. << "origin credentials must not be sent to the proxy";
  25617. }
  25618. } // namespace proxy_tunnel_test
  25619. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  25620. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25621. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25622. ASSERT_NE(0, proxy.port());
  25623. ws::WebSocketClient client(origin.url());
  25624. client.set_proxy("127.0.0.1", proxy.port());
  25625. auto res = client.connect();
  25626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25627. std::string msg;
  25628. ASSERT_TRUE(client.read(msg));
  25629. ASSERT_TRUE(client.send("hello"));
  25630. ASSERT_TRUE(client.read(msg));
  25631. EXPECT_EQ("hello", msg);
  25632. client.close();
  25633. EXPECT_EQ(1, proxy.connect_hits());
  25634. auto target = "127.0.0.1:" + std::to_string(origin.port());
  25635. auto connect_req = proxy.connect_request();
  25636. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  25637. EXPECT_NE(std::string::npos,
  25638. connect_req.find("\r\nHost: " + target + "\r\n"));
  25639. }
  25640. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  25641. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  25642. [](ws::WebSocketClient &cli) {
  25643. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25644. },
  25645. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  25646. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  25647. }
  25648. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  25649. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  25650. [](ws::WebSocketClient &cli) {
  25651. cli.set_proxy_bearer_token_auth("proxy-token");
  25652. },
  25653. "Bearer proxy-token", "Bearer origin-token");
  25654. }
  25655. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  25656. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25657. proxy_tunnel_test::ScopedConnectProxy proxy(
  25658. origin.port(), proxy_tunnel_test::require_proxy_auth(
  25659. "Basic " + detail::base64_encode("proxy-user:"),
  25660. "Basic realm=\"proxy\""));
  25661. ASSERT_NE(0, proxy.port());
  25662. ws::WebSocketClient client(origin.url());
  25663. client.set_proxy("127.0.0.1", proxy.port());
  25664. client.set_proxy_basic_auth("proxy-user", "");
  25665. auto res = client.connect();
  25666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25667. client.close();
  25668. EXPECT_EQ(1, proxy.connect_hits());
  25669. }
  25670. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  25671. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25672. proxy_tunnel_test::ScopedConnectProxy proxy(
  25673. origin.port(), proxy_tunnel_test::require_proxy_auth(
  25674. "Bearer proxy-token", "Basic realm=\"proxy\""));
  25675. ASSERT_NE(0, proxy.port());
  25676. ws::WebSocketClient client(origin.url());
  25677. client.set_proxy("127.0.0.1", proxy.port());
  25678. auto res = client.connect();
  25679. EXPECT_FALSE(res);
  25680. EXPECT_EQ(Error::ProxyConnection, res.error());
  25681. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  25682. EXPECT_EQ("Basic realm=\"proxy\"",
  25683. res.get_header_value("Proxy-Authenticate"));
  25684. EXPECT_FALSE(client.is_open());
  25685. }
  25686. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  25687. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25688. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25689. ASSERT_NE(0, proxy.port());
  25690. ws::WebSocketClient client(origin.url());
  25691. client.set_proxy("127.0.0.1", proxy.port());
  25692. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25693. client.set_no_proxy({"127.0.0.1"});
  25694. auto res = client.connect();
  25695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25696. std::string msg;
  25697. ASSERT_TRUE(client.read(msg));
  25698. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  25699. << "proxy credentials must not reach a bypassed origin";
  25700. client.close();
  25701. EXPECT_EQ(0, proxy.connect_hits());
  25702. }
  25703. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  25704. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25705. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25706. ASSERT_NE(0, proxy.port());
  25707. ws::WebSocketClient client(origin.url());
  25708. client.set_proxy("127.0.0.1", proxy.port());
  25709. ASSERT_TRUE(client.connect());
  25710. ASSERT_TRUE(client.connect());
  25711. client.close();
  25712. EXPECT_EQ(2, proxy.connect_hits());
  25713. }
  25714. #ifdef CPPHTTPLIB_SSL_ENABLED
  25715. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  25716. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25717. proxy_tunnel_test::ScopedConnectProxy proxy(
  25718. origin.port(), [](const std::string &head) -> std::string {
  25719. if (head.find(
  25720. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  25721. std::string::npos) {
  25722. return proxy_tunnel_test::kTunnelEstablished;
  25723. }
  25724. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  25725. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  25726. "nonce=\"abc\", algorithm=MD5\r\n"
  25727. "Content-Length: 0\r\n\r\n";
  25728. });
  25729. ASSERT_NE(0, proxy.port());
  25730. ws::WebSocketClient client(origin.url());
  25731. client.set_proxy("127.0.0.1", proxy.port());
  25732. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25733. auto res = client.connect();
  25734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25735. std::string msg;
  25736. ASSERT_TRUE(client.read(msg));
  25737. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  25738. client.close();
  25739. EXPECT_EQ(2, proxy.connect_hits());
  25740. }
  25741. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  25742. proxy_tunnel_test::ScopedSSLServer origin;
  25743. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  25744. origin.listen();
  25745. proxy_tunnel_test::ScopedConnectProxy proxy(
  25746. origin.port(), proxy_tunnel_test::require_proxy_auth(
  25747. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  25748. ASSERT_NE(0, proxy.port());
  25749. ws::WebSocketClient client(
  25750. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  25751. client.enable_server_certificate_verification(false);
  25752. client.set_proxy("127.0.0.1", proxy.port());
  25753. client.set_proxy_bearer_token_auth("proxy-token");
  25754. auto res = client.connect();
  25755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25756. std::string msg;
  25757. ASSERT_TRUE(client.read(msg));
  25758. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  25759. << "Proxy-Authorization must not be sent inside the tunnel";
  25760. client.close();
  25761. EXPECT_EQ(1, proxy.connect_hits());
  25762. }
  25763. #endif